You can assign an iterable to side_effect
, and the mock will return the next value in the sequence each time it is called:
>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'
Quoting the Mock()
documentation:
If side_effect is an iterable then each call to the mock will return the next value from the iterable.
I too faced the same exception, none of the solutions over internet helped me out. my project contains multiple modules. My Junit code resides in Web module. And it's referring to client module's code.
Finally , I tried : Right click on (Web module) project -->build path--> source tab--> Link source --> added the src files location (Client module's)
Thats it! It worked like a charm Hope it helps
For information i removed the action attribute and i got this error when i call an ajax post..Even though my action attribute in the form looks like this action="javascript://;"
I thought I had it from the ajax call and serializing the form but I added the dummy action attribute to the form back again and it worked.
On small device : 4 columns x 3 (= 12) ==> col-sm-3
On extra small : 3 columns x 4 (= 12) ==> col-xs-4
<footer class="row">
<nav class="col-xs-4 col-sm-3">
<ul class="list-unstyled">
<li>Text 1</li>
<li>Text 2</li>
<li>Text 3</li>
</ul>
</nav>
<nav class="col-xs-4 col-sm-3">
<ul class="list-unstyled">
<li>Text 4</li>
<li>Text 5</li>
<li>Text 6</li>
</ul>
</nav>
<nav class="col-xs-4 col-sm-3">
<ul class="list-unstyled">
<li>Text 7</li>
<li>Text 8</li>
<li>Text 9</li>
</ul>
</nav>
<nav class="hidden-xs col-sm-3">
<ul class="list-unstyled">
<li>Text 10</li>
<li>Text 11</li>
<li>Text 12</li>
</ul>
</nav>
</footer>
As you say, hidden-xs is not enough, you have to combine xs and sm class.
Here is links to the official doc about available responsive classes and about the grid system.
Have in head :
With typical 3 level non-diamond non-virtual-inheritance inheritance, when you instantiate a new most-derived-object, new
is called and the size required for the object on the heap is resolved from the class type by the compiler and passed to new.
new
has a signature:
_GLIBCXX_WEAK_DEFINITION void *
operator new (std::size_t sz) _GLIBCXX_THROW (std::bad_alloc)
And makes a call to malloc
, returning the void pointer
This address is then passed to the constructor of the most derived object, which will immediately call the middle constructor and then the middle constructor will immediately call the base constructor. The base then stores a pointer to its virtual table at the start of the object and then its attributes after it. This then returns to the middle constructor which will store its virtual table pointer at the same location and then its attributes after the attributes that would have been stored by the base constructor. It then returns to the most derived constructor, which stores a pointer to its virtual table at the same location and and then stores its attributes after the attributes that would have been stored by the middle constructor.
Because the virtual table pointer is overwritten, the virtual table pointer ends up always being the one of the most derived class. Virtualness propagates towards the most derived class so if a function is virtual in the middle class, it will be virtual in the most derived class but not the base class. If you polymorphically cast an instance of the most derived class to a pointer to the base class then the compiler will not resolve this to an indirect call to the virtual table and instead will call the function directly A::function()
. If a function is virtual for the type you have cast it to then it will resolve to a call into the virtual table which will always be that of the most derived class. If it is not virtual for that type then it will just call Type::function()
and pass the object pointer to it, cast to Type.
Actually when I say pointer to its virtual table, it's actually always an offset of 16 into the virtual table.
vtable for Base:
.quad 0
.quad typeinfo for Base
.quad Base::CommonFunction()
.quad Base::VirtualFunction()
pointer is typically to the first function i.e.
mov edx, OFFSET FLAT:vtable for Base+16
virtual
is not required again in more-derived classes if it is virtual in a less-derived class because it propagates downwards in the direction of the most derived class. But it can be used to show that the function is indeed a virtual function, without having to check the classes it inherits's type definitions. When a function is declared virtual, from that point on, only the last implementation in the inheritance chain is used, but before that, it can still be used non-virtually if the object is cast to a type of a class before that in the inheritance chain that defines that method. It can be defined non-virtually in multiple classes before it in the chain before the virtualhood begins for a method of that name and signature, and they will use their own methods when referenced (and all classes after that definition in the chain will use that definition if they do not have their own definition, as opposed to virtual, which always uses the final definition). When a method is declared virtual, it must be implemented in that class or a more derived class in the inheritance chain for the full object that was constructed in order to be used.
override
is another compiler guard that says that this function is overriding something and if it isn't then throw a compiler error.
= 0
means that this is an abstract function
final
prevents a virtual function from being implemented again in a more derived class and will make sure that the virtual table of the most derived class contains the final function of that class.
= default
makes it explicit in documentation that the compiler will use the default implementation
= delete
give a compiler error if a call to this is attempted
If you call a non-virtual function, it will resolve to the correct method definition without going through the virtual table. If you call a virtual-function that has its final definition in an inherited class then it will use its virtual table and will pass the subobject to it automatically if you don't cast the object pointer to that type when calling the method. If you call a virtual function defined in the most derived class on a pointer of that type then it will use its virtual table, which will be the one at the start of the object. If you call it on a pointer of an inherited type and the function is also virtual in that class then it will use the vtable pointer of that subobject, which in the case of the first subobject will be the same pointer as the most derived class, which will not contain a thunk as the address of the object and the subobject are the same, and therefore it's just as simple as the method automatically recasting this pointer, but in the case of a 2nd sub object, its vtable will contain a non-virtual thunk to convert the pointer of the object of inherited type to the type the implementation in the most derived class expects, which is the full object, and therefore offsets the subobject pointer to point to the full object, and in the case of base subobject, will require a virtual thunk to offset the pointer to the base to the full object, such that it can be recast by the method hidden object parameter type.
Using the object with a reference operator and not through a pointer (dereference operator) breaks polymorphism and will treat virtual methods as regular methods. This is because polymorphic casting on non-pointer types can't occur due to slicing.
Consider
class Base
{
int a = 1;
int b = 2;
public:
void virtual CommonFunction(){} ; //define empty method body
void virtual VirtualFunction(){} ;
};
class DerivedClass1: virtual public Base
{
int c = 3;
public:
void virtual DerivedCommonFunction(){} ;
void virtual VirtualFunction(){} ;
};
class DerivedClass2 : virtual public Base
{
int d = 4;
public:
//void virtual DerivedCommonFunction(){} ;
void virtual VirtualFunction(){} ;
void virtual DerivedCommonFunction2(){} ;
};
class DerivedDerivedClass : public DerivedClass1, public DerivedClass2
{
int e = 5;
public:
void virtual DerivedDerivedCommonFunction(){} ;
void virtual VirtualFunction(){} ;
};
int main () {
DerivedDerivedClass* d = new DerivedDerivedClass;
d->VirtualFunction();
d->DerivedCommonFunction();
d->DerivedCommonFunction2();
d->DerivedDerivedCommonFunction();
((DerivedClass2*)d)->DerivedCommonFunction2();
((Base*)d)->VirtualFunction();
}
Without virtually inheriting the bass class you will get an object that looks like this:
Instead of this:
I.e. there will be 2 base objects.
In the virtual diamond inheritance situation above, after new
is called, it passes the address of the allocated space for the object to the most derived constructor DerivedDerivedClass::DerivedDerivedClass()
, which calls Base::Base()
first, which writes its vtable in the base's dedicated subobject, it then DerivedDerivedClass::DerivedDerivedClass()
calls DerivedClass1::DerivedClass1()
, which writes its virtual table pointer to its subobject as well as overwriting the base subobject's pointer at the end of the object by consulting the passed VTT, and then calls DerivedClass1::DerivedClass1()
to do the same, and finally DerivedDerivedClass::DerivedDerivedClass()
overwrites all 3 pointers with its virtual table pointer for that inherited class. This is instead of (as illustrated in the 1st image above) DerivedDerivedClass::DerivedDerivedClass()
calling DerivedClass1::DerivedClass1()
and that calling Base::Base()
(which overwrites the virtual pointer), returning, offsetting the address to the next subobject, calling DerivedClass2::DerivedClass2()
and then that also calling Base::Base()
, overwriting that virtual pointer, returning and then DerivedDerivedClass
constructor overwriting both virtual pointers with its virtual table pointer (in this instance, the virtual table of the most derived constructor contains 2 subtables instead of 3).
The following is all compiled in debug mode -O0 so there will be redundant assembly
main:
.LFB8:
push rbp
mov rbp, rsp
push rbx
sub rsp, 24
mov edi, 48 //pass size to new
call operator new(unsigned long) //call new
mov rbx, rax //move the address of the allocation to rbx
mov rdi, rbx //move it to rdi i.e. pass to the call
call DerivedDerivedClass::DerivedDerivedClass() [complete object constructor] //construct on this address
mov QWORD PTR [rbp-24], rbx //store the address of the object on the stack as the d pointer variable on -O0, will be optimised off on -Ofast if the address of the pointer itself isn't taken in the code, because this address does not need to be on the stack, it can just be passed in a register to the subsequent methods
Parenthetically, if the code were DerivedDerivedClass d = DerivedDerivedClass()
, the main
function would look like this:
main:
push rbp
mov rbp, rsp
sub rsp, 48 // make room for and zero 48 bytes on the stack for the 48 byte object, no extra padding required as the frame is 64 bytes with `rbp` and return address of the function it calls (no stack params are passed to any function it calls), hence rsp will be aligned by 16 assuming it was aligned at the start of this frame
mov QWORD PTR [rbp-48], 0
mov QWORD PTR [rbp-40], 0
mov QWORD PTR [rbp-32], 0
mov QWORD PTR [rbp-24], 0
mov QWORD PTR [rbp-16], 0
mov QWORD PTR [rbp-8], 0
lea rax, [rbp-48] // load the address of the cleared 48 bytes
mov rdi, rax // pass the address as a pointer to the 48 bytes cleared as the first parameter to the constructor
call DerivedDerivedClass::DerivedDerivedClass() [complete object constructor]
//address is not stored on the stack because the object is used directly -- there is no pointer variable -- d refers to the object on the stack as opposed to being a pointer
Moving back to the original example, the DerivedDerivedClass
constructor:
DerivedDerivedClass::DerivedDerivedClass() [complete object constructor]:
.LFB20:
push rbp
mov rbp, rsp
sub rsp, 16
mov QWORD PTR [rbp-8], rdi
.LBB5:
mov rax, QWORD PTR [rbp-8] // object address now in rax
add rax, 32 //increment address by 32
mov rdi, rax // move object address+32 to rdi i.e. pass to call
call Base::Base() [base object constructor]
mov rax, QWORD PTR [rbp-8] //move object address to rax
mov edx, OFFSET FLAT:VTT for DerivedDerivedClass+8 //move address of VTT+8 to edx
mov rsi, rdx //pass VTT+8 address as 2nd parameter
mov rdi, rax //object address as first (DerivedClass1 subobject)
call DerivedClass1::DerivedClass1() [base object constructor]
mov rax, QWORD PTR [rbp-8] //move object address to rax
add rax, 16 //increment object address by 16
mov edx, OFFSET FLAT:VTT for DerivedDerivedClass+24 //store address of VTT+24 in edx
mov rsi, rdx //pass address of VTT+24 as second parameter
mov rdi, rax //address of DerivedClass2 subobject as first
call DerivedClass2::DerivedClass2() [base object constructor]
mov edx, OFFSET FLAT:vtable for DerivedDerivedClass+24 //move this to edx
mov rax, QWORD PTR [rbp-8] // object address now in rax
mov QWORD PTR [rax], rdx. //store address of vtable for DerivedDerivedClass+24 at the start of the object
mov rax, QWORD PTR [rbp-8] // object address now in rax
add rax, 32 // increment object address by 32
mov edx, OFFSET FLAT:vtable for DerivedDerivedClass+120 //move this to edx
mov QWORD PTR [rax], rdx //store vtable for DerivedDerivedClass+120 at object+32 (Base)
mov edx, OFFSET FLAT:vtable for DerivedDerivedClass+72 //store this in edx
mov rax, QWORD PTR [rbp-8] //move object address to rax
mov QWORD PTR [rax+16], rdx //store vtable for DerivedDerivedClass+72 at object+16 (DerivedClass2)
mov rax, QWORD PTR [rbp-8]
mov DWORD PTR [rax+28], 5 // stores e = 5 in the object
.LBE5:
nop
leave
ret
The DerivedDerivedClass
constructor calls Base::Base()
with a pointer to the object offset 32. Base stores a pointer to its virtual table at the address it receives and its members after it.
Base::Base() [base object constructor]:
.LFB11:
push rbp
mov rbp, rsp
mov QWORD PTR [rbp-8], rdi //stores address of object on stack (-O0)
.LBB2:
mov edx, OFFSET FLAT:vtable for Base+16 //puts vtable for Base+16 in edx
mov rax, QWORD PTR [rbp-8] //copies address of object from stack to rax
mov QWORD PTR [rax], rdx //stores it address of object
mov rax, QWORD PTR [rbp-8] //copies address of object on stack to rax again
mov DWORD PTR [rax+8], 1 //stores a = 1 in the object
mov rax, QWORD PTR [rbp-8] //junk from -O0
mov DWORD PTR [rax+12], 2 //stores b = 2 in the object
.LBE2:
nop
pop rbp
ret
DerivedDerivedClass::DerivedDerivedClass()
then calls DerivedClass1::DerivedClass1()
with a pointer to the object offset 0 and also passes the address of VTT for DerivedDerivedClass+8
DerivedClass1::DerivedClass1() [base object constructor]:
.LFB14:
push rbp
mov rbp, rsp
mov QWORD PTR [rbp-8], rdi //address of object
mov QWORD PTR [rbp-16], rsi //address of VTT+8
.LBB3:
mov rax, QWORD PTR [rbp-16] //address of VTT+8 now in rax
mov rdx, QWORD PTR [rax] //address of DerivedClass1-in-DerivedDerivedClass+24 now in rdx
mov rax, QWORD PTR [rbp-8] //address of object now in rax
mov QWORD PTR [rax], rdx //store address of DerivedClass1-in-.. in the object
mov rax, QWORD PTR [rbp-8] // address of object now in rax
mov rax, QWORD PTR [rax] //address of DerivedClass1-in.. now implicitly in rax
sub rax, 24 //address of DerivedClass1-in-DerivedDerivedClass+0 now in rax
mov rax, QWORD PTR [rax] //value of 32 now in rax
mov rdx, rax // now in rdx
mov rax, QWORD PTR [rbp-8] //address of object now in rax
add rdx, rax //address of object+32 now in rdx
mov rax, QWORD PTR [rbp-16] //address of VTT+8 now in rax
mov rax, QWORD PTR [rax+8] //derference VTT+8+8; address of DerivedClass1-in-DerivedDerivedClass+72 (Base::CommonFunction()) now in rax
mov QWORD PTR [rdx], rax //store at address object+32 (offset to Base)
mov rax, QWORD PTR [rbp-8] //store address of object in rax, return
mov DWORD PTR [rax+8], 3 //store its attribute c = 3 in the object
.LBE3:
nop
pop rbp
ret
VTT for DerivedDerivedClass:
.quad vtable for DerivedDerivedClass+24
.quad construction vtable for DerivedClass1-in-DerivedDerivedClass+24 //(DerivedClass1 uses this to write its vtable pointer)
.quad construction vtable for DerivedClass1-in-DerivedDerivedClass+72 //(DerivedClass1 uses this to overwrite the base vtable pointer)
.quad construction vtable for DerivedClass2-in-DerivedDerivedClass+24
.quad construction vtable for DerivedClass2-in-DerivedDerivedClass+72
.quad vtable for DerivedDerivedClass+120 // DerivedDerivedClass supposed to use this to overwrite Bases's vtable pointer
.quad vtable for DerivedDerivedClass+72 // DerivedDerivedClass supposed to use this to overwrite DerivedClass2's vtable pointer
//although DerivedDerivedClass uses vtable for DerivedDerivedClass+72 and DerivedDerivedClass+120 directly to overwrite them instead of going through the VTT
construction vtable for DerivedClass1-in-DerivedDerivedClass:
.quad 32
.quad 0
.quad typeinfo for DerivedClass1
.quad DerivedClass1::DerivedCommonFunction()
.quad DerivedClass1::VirtualFunction()
.quad -32
.quad 0
.quad -32
.quad typeinfo for DerivedClass1
.quad Base::CommonFunction()
.quad virtual thunk to DerivedClass1::VirtualFunction()
construction vtable for DerivedClass2-in-DerivedDerivedClass:
.quad 16
.quad 0
.quad typeinfo for DerivedClass2
.quad DerivedClass2::VirtualFunction()
.quad DerivedClass2::DerivedCommonFunction2()
.quad -16
.quad 0
.quad -16
.quad typeinfo for DerivedClass2
.quad Base::CommonFunction()
.quad virtual thunk to DerivedClass2::VirtualFunction()
vtable for DerivedDerivedClass:
.quad 32
.quad 0
.quad typeinfo for DerivedDerivedClass
.quad DerivedClass1::DerivedCommonFunction()
.quad DerivedDerivedClass::VirtualFunction()
.quad DerivedDerivedClass::DerivedDerivedCommonFunction()
.quad 16
.quad -16
.quad typeinfo for DerivedDerivedClass
.quad non-virtual thunk to DerivedDerivedClass::VirtualFunction()
.quad DerivedClass2::DerivedCommonFunction2()
.quad -32
.quad 0
.quad -32
.quad typeinfo for DerivedDerivedClass
.quad Base::CommonFunction()
.quad virtual thunk to DerivedDerivedClass::VirtualFunction()
virtual thunk to DerivedClass1::VirtualFunction():
mov r10, QWORD PTR [rdi]
add rdi, QWORD PTR [r10-32]
jmp .LTHUNK0
virtual thunk to DerivedClass2::VirtualFunction():
mov r10, QWORD PTR [rdi]
add rdi, QWORD PTR [r10-32]
jmp .LTHUNK1
virtual thunk to DerivedDerivedClass::VirtualFunction():
mov r10, QWORD PTR [rdi]
add rdi, QWORD PTR [r10-32]
jmp .LTHUNK2
non-virtual thunk to DerivedDerivedClass::VirtualFunction():
sub rdi, 16
jmp .LTHUNK3
.set .LTHUNK0,DerivedClass1::VirtualFunction()
.set .LTHUNK1,DerivedClass2::VirtualFunction()
.set .LTHUNK2,DerivedDerivedClass::VirtualFunction()
.set .LTHUNK3,DerivedDerivedClass::VirtualFunction()
Each inherited class has its own construction virtual table and the most derived class, DerivedDerivedClass
, has a virtual table with a subtable for each, and it uses the pointer to the subtable to overwrite construction vtable pointer that the inherited class's constructor stored for each subobject. Each virtual method that needs a thunk (virtual thunk offsets the object pointer from the base to the start of the object and a non-virtual thunk offsets the object pointer from an inherited class's object that isn't the base object to the start of the whole object of the type DerivedDerivedClass
). The DerivedDerivedClass
constructor also uses a virtual table table (VTT) as a serial list of all the virtual table pointers that it needs to use and passes it to each constructor (along with the subobject address that the constructor is for), which they use to overwrite their and the base's vtable pointer.
DerivedDerivedClass::DerivedDerivedClass()
then passes the address of the object+16 and the address of VTT for DerivedDerivedClass+24
to DerivedClass2::DerivedClass2()
whose assembly is identical to DerivedClass1::DerivedClass1()
except for the line mov DWORD PTR [rax+8], 3
which obviously has a 4 instead of 3 for d = 4
.
After this, it replaces all 3 virtual table pointers in the object with pointers to offsets in DerivedDerivedClass
's vtable to the representation for that class.
The call to d->VirtualFunction()
in main
:
mov rax, QWORD PTR [rbp-24] //store pointer to object (and hence vtable pointer) in rax
mov rax, QWORD PTR [rax] //dereference this pointer to vtable pointer and store virtual table pointer in rax
add rax, 8 // add 8 to the pointer to get the 2nd function pointer in the table
mov rdx, QWORD PTR [rax] //dereference this pointer to get the address of the method to call
mov rax, QWORD PTR [rbp-24] //restore pointer to object in rax (-O0 is inefficient, yes)
mov rdi, rax //pass object to the method
call rdx
d->DerivedCommonFunction();
:
mov rax, QWORD PTR [rbp-24]
mov rdx, QWORD PTR [rbp-24]
mov rdx, QWORD PTR [rdx]
mov rdx, QWORD PTR [rdx]
mov rdi, rax //pass object to method
call rdx //call the first function in the table
d->DerivedCommonFunction2();
:
mov rax, QWORD PTR [rbp-24] //get the object pointer
lea rdx, [rax+16] //get the address of the 2nd subobject in the object
mov rax, QWORD PTR [rbp-24] //get the object pointer
mov rax, QWORD PTR [rax+16] // get the vtable pointer of the 2nd subobject
add rax, 8 //call the 2nd function in this table
mov rax, QWORD PTR [rax] //get the address of the 2nd function
mov rdi, rdx //call it and pass the 2nd subobject to it
call rax
d->DerivedDerivedCommonFunction();
:
mov rax, QWORD PTR [rbp-24] //get the object pointer
mov rax, QWORD PTR [rax] //get the vtable pointer
add rax, 16 //get the 3rd function in the first virtual table (which is where virtual functions that that first appear in the most derived class go, because they belong to the full object which uses the virtual table pointer at the start of the object)
mov rdx, QWORD PTR [rax] //get the address of the object
mov rax, QWORD PTR [rbp-24]
mov rdi, rax //call it and pass the whole object to it
call rdx
((DerivedClass2*)d)->DerivedCommonFunction2();
:
//it casts the object to its subobject and calls the corresponding method in its virtual table, which will be a non-virtual thunk
cmp QWORD PTR [rbp-24], 0
je .L14
mov rax, QWORD PTR [rbp-24]
add rax, 16
jmp .L15
.L14:
mov eax, 0
.L15:
cmp QWORD PTR [rbp-24], 0
cmp QWORD PTR [rbp-24], 0
je .L18
mov rdx, QWORD PTR [rbp-24]
add rdx, 16
jmp .L19
.L18:
mov edx, 0
.L19:
mov rdx, QWORD PTR [rdx]
add rdx, 8
mov rdx, QWORD PTR [rdx]
mov rdi, rax
call rdx
((Base*)d)->VirtualFunction();
:
//it casts the object to its subobject and calls the corresponding function in its virtual table, which will be a virtual thunk
cmp QWORD PTR [rbp-24], 0
je .L20
mov rax, QWORD PTR [rbp-24]
mov rax, QWORD PTR [rax]
sub rax, 24
mov rax, QWORD PTR [rax]
mov rdx, rax
mov rax, QWORD PTR [rbp-24]
add rax, rdx
jmp .L21
.L20:
mov eax, 0
.L21:
cmp QWORD PTR [rbp-24], 0
cmp QWORD PTR [rbp-24], 0
je .L24
mov rdx, QWORD PTR [rbp-24]
mov rdx, QWORD PTR [rdx]
sub rdx, 24
mov rdx, QWORD PTR [rdx]
mov rcx, rdx
mov rdx, QWORD PTR [rbp-24]
add rdx, rcx
jmp .L25
.L24:
mov edx, 0
.L25:
mov rdx, QWORD PTR [rdx]
add rdx, 8
mov rdx, QWORD PTR [rdx]
mov rdi, rax
call rdx
Get a shell of your running container and change the root pass.
docker exec -it <MyContainer> bash
root@MyContainer:/# passwd
Enter new UNIX password:
Retype new UNIX password:
A degree of control is possible over how information travels from a third-party website to Facebook when a page is shared (or liked, etc.). In order to make this possible, information is sent via Open Graph meta tags in the <head>
part of the website’s code.
I had set the new app's application pool to the DefaultAppPool
in IIS which obviously is using the Classic
pipeline with .NET v.2.0
.
To solve the problem I created a new App Pool using the Integrated
pipeline and .NET v4.0
. just for this new application and then everything started working as expected.
Don't forget to assign this new app pool to the application. Select the application in IIS, click Basic Settings
and then pick the new app pool for the app.
I had the same problem with SQLite and Android. Here is my Solution:
List<String> tables = new ArrayList<String>();
Cursor cursor = db.rawQuery("SELECT * FROM sqlite_master WHERE type='table';", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
String tableName = cursor.getString(1);
if (!tableName.equals("android_metadata") &&
!tableName.equals("sqlite_sequence"))
tables.add(tableName);
cursor.moveToNext();
}
cursor.close();
for(String tableName:tables) {
db.execSQL("DROP TABLE IF EXISTS " + tableName);
}
Problems only surface when I am I trying to give the first loaded content an active state
Does this mean that you want to add a class to the first button?
$('.o-links').click(function(e) { // ... }).first().addClass('O_Nav_Current');
instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:
CSS:
.image-area { width: 100%; height: auto; display: none; } .image-area:first-of-type { display: block; }
JavaScript:
var $slides = $('.image-area'), $btns = $('a.o-links'); $btns.on('click', function (e) { var i = $btns.removeClass('O_Nav_Current').index(this); $(this).addClass('O_Nav_Current'); $slides.filter(':visible').fadeOut(1000, function () { $slides.eq(i).fadeIn(1000); }); e.preventDefault(); }).first().addClass('O_Nav_Current');
Use the code below to generate the random number of 11 characters or change the number as per your requirement.
$randomNum=substr(str_shuffle("0123456789abcdefghijklmnopqrstvwxyz"), 0, 11);
or we can use custom function to generate the random number
function randomNumber($length){
$numbers = range(0,9);
shuffle($numbers);
for($i = 0;$i < $length;$i++)
$digits .= $numbers[$i];
return $digits;
}
//generate random number
$randomNum=randomNumber(11);
Please use the below code and let me know
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(c, "root", "MyNewPass");
System.out.println("connection done");
PreparedStatement ps=con.prepareStatement(q);
System.out.println(q);
rs=ps.executeQuery();
System.out.println("done2");
while (rs.next()) {
System.out.println(rs.getString(1));
System.out.println(rs.getString(2));
}
response.sendRedirect("myfolder/welcome.jsp"); // wherever you wanna redirect this page.
}
catch (Exception e) {
// TODO: handle exception
System.out.println("Failed");
}
myfolder/welcome.jsp
is the relative path of your jsp
page. So, change it as per your jsp
page path.
Everything. They're unrelated languages.
Simply Try this:
int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("data is: {0}", Convert.ToChar(n));
Just as a follow up for anyone still running into this – I had added the ServicePointManager.SecurityProfile options as noted in the solution:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
And yet I continued to get the same “The request was aborted: Could not create SSL/TLS secure channel” error. I was attempting to connect to some older voice servers with HTTPS SOAP API interfaces (i.e. voice mail, IP phone systems etc… installed years ago). These only support SSL3 connections as they were last updated years ago.
One would think including SSl3 in the list of SecurityProtocols would do the trick here, but it didn’t. The only way I could force the connection was to include ONLY the Ssl3 protocol and no others:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
Then the connection goes through – seems like a bug to me but this didn’t start throwing errors until recently on tools I provide for these servers that have been out there for years – I believe Microsoft has started rolling out system changes that have updated this behavior to force TLS connections unless there is no other alternative.
Anyway – if you’re still running into this against some old sites/servers, it’s worth giving it a try.
Needs ensure library but you can compare list by:
ensure([1, 2]).contains_only([2, 1])
This will not raise assert exception. Documentation of thin is really thin so i would recommend to look at ensure's codes on github
Use access modifier before the member definition:
private $connection;
As you cannot use function call in member definition in PHP, do it in constructor:
public function __construct() {
$this->connection = sqlite_open("[path]/data/users.sqlite", 0666);
}
Try this, you will know the difference between change and modify,
ALTER TABLE table_name CHANGE curr_column_name new_column_name new_column_datatype [constraints]
ALTER TABLE table_name MODIFY column_name new_column_datatype [constraints]
CHANGE
.MODIFY
. You cannot change the name of the column using this statement.Hope, I explained well in detail.
If you're using Java configs instead of XML configs, put this in your WebSecurityConfigurerAdapter.configure(HttpSecurity http)
method:
http.headers().frameOptions().disable();
The Stack is an area of memory for keeping temporary data. Stack is used by the CALL instruction to keep the return address for procedures The return RET instruction gets this value from the stack and returns to that offset. The same thing happens when an INT instruction calls an interrupt. It stores in the Stack the flag register, code segment and offset. The IRET instruction is used to return from interrupt call.
The Stack is a Last In First Out (LIFO) memory. Data is placed onto the Stack with a PUSH instruction and removed with a POP instruction. The Stack memory is maintained by two registers: the Stack Pointer (SP) and the Stack Segment (SS) register. When a word of data is PUSHED onto the stack the the High order 8-bit Byte is placed in location SP-1 and the Low 8-bit Byte is placed in location SP-2. The SP is then decremented by 2. The SP addds to the (SS x 10H) register, to form the physical stack memory address. The reverse sequence occurs when data is POPPED from the Stack. When a word of data is POPPED from the stack the the High order 8-bit Byte is obtained in location SP-1 and the Low 8-bit Byte is obtained in location SP-2. The SP is then incremented by 2.
I really didn't want to type \n
every single time and @matthause's answer didn't seem to work for me, so I created my own class
class File():
def __init__(self, name, mode='w'):
self.f = open(name, mode, buffering=1)
def write(self, string, newline=True):
if newline:
self.f.write(string + '\n')
else:
self.f.write(string)
And here it is implemented
f = File('console.log')
f.write('This is on the first line')
f.write('This is on the second line', newline=False)
f.write('This is still on the second line')
f.write('This is on the third line')
This should show in the log file as
This is on the first line
This is on the second lineThis is still on the second line
This is on the third line
You can either have the newly inserted ID being output to the SSMS console like this:
INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')
You can use this also from e.g. C#, when you need to get the ID back to your calling app - just execute the SQL query with .ExecuteScalar()
(instead of .ExecuteNonQuery()
) to read the resulting ID
back.
Or if you need to capture the newly inserted ID
inside T-SQL (e.g. for later further processing), you need to create a table variable:
DECLARE @OutputTbl TABLE (ID INT)
INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID INTO @OutputTbl(ID)
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')
This way, you can put multiple values into @OutputTbl
and do further processing on those. You could also use a "regular" temporary table (#temp
) or even a "real" persistent table as your "output target" here.
$.ajax({
url: url,
cache: false,
success: function(response) {
$('.element').html(response);
}
});
< span class = "element" >
//response
< div id = "result" >
Not found
</div>
</span>
var result = $("#result:contains('Not found')").text();
console.log(result); // output: Not found
String strJson="{\"Employee\":
[{\"id\":\"101\",\"name\":\"Pushkar\",\"salary\":\"5000\"},
{\"id\":\"102\",\"name\":\"Rahul\",\"salary\":\"4000\"},
{\"id\":\"103\",\"name\":\"tanveer\",\"salary\":\"56678\"}]}";
This is an example of a JSON string with Employee
as object, then multiple strings and values in an array as a reference to @cregox
...
A bit complicated but can explain a lot in a single JSON string.
in your <head>
<meta id="viewport"
name="viewport"
content="width=1024, height=768, initial-scale=0, minimum-scale=0.25" />
somewhere in your javascript
document.getElementById("viewport").setAttribute("content",
"initial-scale=0.5; maximum-scale=1.0; user-scalable=0;");
... but good luck with tweaking it for your device, fiddling for hours... and i'm still not there!
If I understand correctly, you want to get the String of an Editable object, right? If yes, try using toString()
.
As many answers are written for the same domains, I'll write how to do this in cross domains.
First, you need to know the Post Message API. We need a messenger to communicate between two windows.
Here's a messenger I created.
/**
* Creates a messenger between two windows
* which have two different domains
*/
class CrossMessenger {
/**
*
* @param {object} otherWindow - window object of the other
* @param {string} targetDomain - domain of the other window
* @param {object} eventHandlers - all the event names and handlers
*/
constructor(otherWindow, targetDomain, eventHandlers = {}) {
this.otherWindow = otherWindow;
this.targetDomain = targetDomain;
this.eventHandlers = eventHandlers;
window.addEventListener("message", (e) => this.receive.call(this, e));
}
post(event, data) {
try {
// data obj should have event name
var json = JSON.stringify({
event,
data
});
this.otherWindow.postMessage(json, this.targetDomain);
} catch (e) {}
}
receive(e) {
var json;
try {
json = JSON.parse(e.data ? e.data : "{}");
} catch (e) {
return;
}
var eventName = json.event,
data = json.data;
if (e.origin !== this.targetDomain)
return;
if (typeof this.eventHandlers[eventName] === "function")
this.eventHandlers[eventName](data);
}
}
Using this in two windows to communicate can solve your problem.
In the main windows,
var msger = new CrossMessenger(iframe.contentWindow, "https://iframe.s.domain");
var cssContent = Array.prototype.map.call(yourCSSElement.sheet.cssRules, css_text).join('\n');
msger.post("cssContent", {
css: cssContent
})
Then, receive the event from the Iframe.
In the Iframe:
var msger = new CrossMessenger(window.parent, "https://parent.window.domain", {
cssContent: (data) => {
var cssElem = document.createElement("style");
cssElem.innerHTML = data.css;
document.head.appendChild(cssElem);
}
})
See the Complete Javascript and Iframes tutorial for more details.
My two cents for such and old question
Some people already mentioned, practice and refactoring. I believe the right order to learn about patterns is this:
Most people ignore 1, many believe they can do 2, and almost everybody goes straight for 3.
For me the key to improve my software skills was learning TDD. It might be a long time of painful and slow coding, but writing your tests first certainly makes you think a lot about your code. If a class needs too much boilerplate or breaks easily you start noticing bad smells quite fast
The main benefit of TDD is that you lose your fear of refactoring your code and force you to write classes that are highly independent and cohesive. Without a good set of tests, it is just too painful to touch something that is not broken. With safety net you will really adventure into drastic changes to your code. That is the moment when you can really start learning from practice.
Now comes the point where you must read books about patterns, and to my opinion, it is a complete waste of time trying too hard. I only understood patterns really well after noticing I did something similar, or I could apply that to existing code. Without the safety tests, or habits of refactoring, I would have waited until a new project. The problem of using patterns in a fresh project is that you do not see how they impact or change a working code. I only understood a software pattern once I refactored my code into one of them, never when I introduced one fresh in my code.
Try this regular expression:
\b(\w+)\s+\1\b
Here \b
is a word boundary and \1
references the captured match of the first group.
top
object makes more sense inside frames. Inside a frame, window
refers to current frame's window while top
refers to the outermost window that contains the frame(s). So:
window.location.href = 'somepage.html';
means loading somepage.html
inside the frame.
top.location.href = 'somepage.html';
means loading somepage.html
in the main browser window.
select * from your_table where MONTH(mont_year) = MONTH(NOW()) and YEAR(mont_year) = YEAR(NOW());
Note: (month_year) means your column that contain date format. I think that will solve your problem. Let me know if that query doesn't works.
SmtpClient MyMail = new SmtpClient();
MailMessage MyMsg = new MailMessage();
MyMail.Host = "mail.eraygan.com";
MyMsg.Priority = MailPriority.High;
MyMsg.To.Add(new MailAddress(Mail));
MyMsg.Subject = Subject;
MyMsg.SubjectEncoding = Encoding.UTF8;
MyMsg.IsBodyHtml = true;
MyMsg.From = new MailAddress("username", "displayname");
MyMsg.BodyEncoding = Encoding.UTF8;
MyMsg.Body = Body;
MyMail.UseDefaultCredentials = false;
NetworkCredential MyCredentials = new NetworkCredential("username", "password");
MyMail.Credentials = MyCredentials;
MyMail.Send(MyMsg);
I found that, when you use EXTERNAL TABLE and LOCATION together, Hive creates table and initially no data will present (assuming your data location is different from the Hive 'LOCATION').
When you use 'LOAD DATA INPATH' command, the data get MOVED (instead of copy) from data location to location that you specified while creating Hive table.
If location is not given when you create Hive table, it uses internal Hive warehouse location and data will get moved from your source data location to internal Hive data warehouse location (i.e. /user/hive/warehouse/).
you can use also this way to write css for placeholder
input::placeholder{
text-align: center;
}
You have the word 'document' in a string. Change:
$('document').keypress(function(e){
to
$(document).keypress(function(e){
Did you import it? Importing matplotlib
is not enough.
>>> import matplotlib
>>> matplotlib.pyplot
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'
but
>>> import matplotlib.pyplot
>>> matplotlib.pyplot
works.
pyplot is a submodule of matplotlib and not immediately imported when you import matplotlib.
The most common form of importing pyplot is
import matplotlib.pyplot as plt
Thus, your statements won't be too long, e.g.
plt.plot([1,2,3,4,5])
instead of
matplotlib.pyplot.plot([1,2,3,4,5])
And: pyplot
is not a function, it's a module! So don't call it, use the functions defined inside this module instead. See my example above
Question: Check whether a $_POST value is empty.
Translation: Check to see if an array key/index has a value associated with it.
Answer: Depends on your emphasis on security. Depends on what is allowed as valid input.
1. Some people say use empty().
From the PHP Manual:
"[Empty] determines whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals FALSE."
The following are thus considered empty.
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
If none of these values are valid for your input control, then empty()
would work. The problem here is that empty()
might be too broad to be used consistently (the same way, for the same reason, on different input control submissions to $_POST
or $_GET
). A good use of empty()
is to check if an entire array is empty (has no elements).
2. Some people say use isset().
isset()
(a language construct) cannot operate on entire arrays, as in isset($myArray)
. It can only operate on variables and array elements (via the index/key): isset($var)
and isset($_POST['username'])
. The isset()
language construct does two things. First it checks to see if a variable or array index/key has a value associated with it. Second, it checks to make sure that value is not equal to the PHP NULL value.
In short, the most accurate check can be accomplished best with isset()
, as some input controls do not even register with $_POST when they are not selected or checked. I have never known a form that submitted the PHP NULL value. None of mine do, so I use isset()
to check if a $_POST
key has no value associated with it (and that is not NULL). isset()
is a much stricter test of emptiness (in the sense of your question) than empty()
.
3. Some people say just do if($var), if($myArray), or if($myArray['userName']) to determine emptiness.
You can test anything that evaluates to true or false in an if statement. Empty arrays evaluate to false and so do variables that are not set. Variables that contain the PHP NULL value also evaluate to false. Unfortunately in this case, like with
empty()
, many more things also evaluate to false: 1. the empty string '', zero (0), zero.zero (0.0), the string zero '0', boolean false, and certain empty XML objects.--Doyle, Beginning PHP 5.3
In conclusion, use isset()
and consider combining it with other tests. Example:
May not work due to superglobal screwiness, but would work for other arrays without question.
if (is_array($_POST) && !empty($_POST)) {
// Now test for your successful controls in $_POST with isset()
}
Hence, why look for a value associated with a key before you even know for sure that $_POST
represents an array and has any values stored in it at all (something many people fail to consider)? Remember, people can send data to your form without using a web browser. You may one day get to the point of testing that $_POST
only has the allowed keys, but that conversation is for another day.
Useful reference:
... starting in Java SE 8, a local class can access local variables and parameters of the enclosing block that are final or effectively final. A variable or parameter whose value is never changed after it is initialized is effectively final.
For example, suppose that the variable numberLength
is not declared final, and you add the marked assignment statement in the PhoneNumber
constructor:
public class OutterClass {
int numberLength; // <== not *final*
class PhoneNumber {
PhoneNumber(String phoneNumber) {
numberLength = 7; // <== assignment to numberLength
String currentNumber = phoneNumber.replaceAll(
regularExpression, "");
if (currentNumber.length() == numberLength)
formattedPhoneNumber = currentNumber;
else
formattedPhoneNumber = null;
}
...
}
...
}
Because of this assignment statement, the variable numberLength is not effectively final anymore. As a result, the Java compiler generates an error message similar to "local variables referenced from an inner class must be final or effectively final" where the inner class PhoneNumber tries to access the numberLength variable:
http://codeinventions.blogspot.in/2014/07/difference-between-final-and.html
http://docs.oracle.com/javase/tutorial/java/javaOO/localclasses.html
In Xcode 7 you can have multiple storyBoards. It will be better if you can keep the Login flow in a separate storyboard.
This can be done using SELECT VIEWCONTROLLER > Editor > Refactor to Storyboard
And here is the Swift version for setting a view as the RootViewContoller-
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.window!.rootViewController = newRootViewController
let rootViewController: UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("LoginViewController")
I know this thread is almost 2 years old but still need to close this since I also came to this Q/A session with same issue...
Please read this definition of illegalMonitorException again and again...
IllegalMonitorException is thrown to indicate that a thread has attempted to wait on an object's monitor or to notify other threads waiting on an object's monitor without owning the specified monitor.
This line again and again says, IllegalMonitorException comes when one of the 2 situation occurs....
1> wait on an object's monitor without owning the specified monitor.
2> notify other threads waiting on an object's monitor without owning the specified monitor.
Some might have got their answers... who all doesn't, then please check 2 statements....
synchronized (object)
object.wait()
If both object are same... then no illegalMonitorException can come.
Now again read the IllegalMonitorException definition and you wont forget it again...
Bash can get the last part of a path without having to call the external basename
:
subdir="/path/to/whatever/${1##*/}"
In Notepad++ go to Plugins > Plugin manager > Show Plugin Manager
then find Xml Tools
plugin. Tick the box and click Install
Open XML document you want to validate and click Ctrl+Shift+Alt+M (Or use Menu if this is your preference Plugins > XML Tools > Validate Now
).
Following dialog will open:
Click on ...
. Point to XSD file and I am pretty sure you'll be able to handle things from here.
Hope this saves you some time.
EDIT:
Plugin manager was not included in some versions of Notepad++ because many users didn't like commercials that it used to show. If you want to keep an older version, however still want plugin manager, you can get it on github, and install it by extracting the archive and copying contents to plugins and updates folder.
In version 7.7.1
plugin manager is back under a different guise... Plugin Admin
so now you can simply update notepad++ and have it back.
There's no fixed time for retransmission. Simple implementations estimate the RTT (round-trip-time) and if no ACK to send data has been received in 2x that time then they re-send.
They then double the wait-time and re-send once more if again there is no reply. Rinse. Repeat.
More sophisticated systems make better estimates of how long it should take for the ACK as well as guesses about exactly which data has been lost.
The bottom-line is that there is no hard-and-fast rule about exactly when to retransmit. It's up to the implementation. All retransmissions are triggered solely by the sender based on lack of response from the receiver.
TCP never drops data so no, there is no way to indicate a server should forget about some segment.
I encounter this problem when trying to use matlab eng to call m functions from c code.
which occurs with command mex -f .. ..
My solution:
strings /usr/lib/i386-<tab>/libstdc++.so.6 | grep GLIBC
I found it includes 3.4.15
so my system has the newest libs.
the problem comes from matlab itself, it calls its own libstdc++.so.6 from {MATLAB}/bin
so, just replace it with the updated system lib.
Please refer this link :
Select Windows or linked base command, In my case I have used Linux :
Create a new Anaconda virtual environment Open a new Terminal window
Type the following command: The above will create a new virtual environment with name tensorflow
conda create -n tensorflow pip python=3.8
conda activate tensorflow
The differences between an Abstract Class
and an Interface
:
Abstract Classes
An abstract class can provide some functionality and leave the rest for derived class.
The derived class may or may not override the concrete functions defined in the base class.
A child class extended from an abstract class should logically be related.
Interface
An interface cannot contain any functionality. It only contains definitions of the methods.
The derived class MUST provide code for all the methods defined in the interface.
Completely different and non-related classes can be logically grouped together using an interface.
There is no hack available at this stage to circumvent asking for permissions from different groups together. That is the nature of how android has developed runtime permissions, to give users a choice of which permissions to accept. Of course not accepting all permissions required by an app, may make the app fail to work properly.
CAMERA and WRITE_EXTERNAL_STORAGE are both regarded as dangerous permissions, and in separate groups, thus both requiring a runtime permission request.
Once permission is granted for a particular group, it does not need to be requested again for the lifetime of the app run, or until it is revoked if given as a default setting.
The only thing you can do is ask the user to accept the decisions as default, which can be revoked, by using "never ask again"
Much simpler approach is to use OdeToCode.UseNodeModules Nuget package. I just tested it with .Net Core 3.0. All you need to do is add the package to the solution and reference it in the Configure method of the Startup class:
app.UseNodeModules();
I learned about it from the excellent Building a Web App with ASP.NET Core, MVC, Entity Framework Core, Bootstrap, and Angular Pluralsight course by Shawn Wildermuth.
$count = DB::table('category_issue')->count();
will give you the number of items.
For more detailed information check Fluent Query Builder section in beautiful Laravel Documentation.
Try this:
$('#id').change();
Works for me.
On one line together with setting the value:
$('#id').val(16).change();
You can also add a middleware to add CORS headers, something like this would work:
/**
* Adds CORS headers to the response
*
* {@link https://en.wikipedia.org/wiki/Cross-origin_resource_sharing}
* {@link http://expressjs.com/en/4x/api.html#res.set}
* @param {object} request the Request object
* @param {object} response the Response object
* @param {function} next function to continue execution
* @returns {void}
* @example
* <code>
* const express = require('express');
* const corsHeaders = require('./middleware/cors-headers');
*
* const app = express();
* app.use(corsHeaders);
* </code>
*/
module.exports = (request, response, next) => {
// http://expressjs.com/en/4x/api.html#res.set
response.set({
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'DELETE,GET,PATCH,POST,PUT',
'Access-Control-Allow-Headers': 'Content-Type,Authorization'
});
// intercept OPTIONS method
if(request.method === 'OPTIONS') {
response.send(200);
} else {
next();
}
};
you could use awk. like this...
cat <yourFile> | awk '/word1/ && /word2/'
Order is not important. So if you have a file and...
a file named , file1 contains:
word1 is in this file as well as word2
word2 is in this file as well as word1
word4 is in this file as well as word1
word5 is in this file as well as word2
then,
/tmp$ cat file1| awk '/word1/ && /word2/'
will result in,
word1 is in this file as well as word2
word2 is in this file as well as word1
yes, awk is slower.
I face the similar issue and surprisingly meta tag didn't work this time. Turns out the company I currently cooperate with has this enterprise mode setting which has priority over meta tag.
We can't change the setting cause policy issue. Luckily I don't really need any fancy features but basic usage of jQuery so my final solution is to switch its version to 1.12 for better compatibility.
It works like this:
mpintro = MediaPlayer.create(this, Uri.parse(Environment.getExternalStorageDirectory().getPath()+ "/Music/intro.mp3"));
mpintro.setLooping(true);
mpintro.start();
It did not work properly as string filepath...
Suppose you have a function that returns a substantial object:
Matrix multiply(const Matrix &a, const Matrix &b);
When you write code like this:
Matrix r = multiply(a, b);
then an ordinary C++ compiler will create a temporary object for the result of multiply()
, call the copy constructor to initialise r
, and then destruct the temporary return value. Move semantics in C++0x allow the "move constructor" to be called to initialise r
by copying its contents, and then discard the temporary value without having to destruct it.
This is especially important if (like perhaps the Matrix
example above), the object being copied allocates extra memory on the heap to store its internal representation. A copy constructor would have to either make a full copy of the internal representation, or use reference counting and copy-on-write semantics interally. A move constructor would leave the heap memory alone and just copy the pointer inside the Matrix
object.
Sometimes using
instead of spaces will work. Clearly it has drawbacks, though.
I've found the following works on Firefox and Chrome.
<form ... > <!-- more stuff -->
<input name="person" type="text" size=30 value="">
<input name="mypswd" type="password" size=6 value="" autocomplete="off">
<input name="userid" type="text" value="security" style="display:none">
<input name="passwd" type="password" value="faker" style="display:none">
<!-- more stuff --> </form>
All of these are within the forms section. "person" and "mypswd" are what you want, but the browser will save "userid" and "passwd" once, and never again since they don't change. You could eliminate the "person" field if you don't really need it. In that case, all you want is the "mypswd" field, which could change in some way known to the user of your web-page.
I am using the same technique in a media query which effectively turns a bullet list into an inline list on smaller devices as they save space.
So the change from:
to:
List Item 1; List Item 2; List Item 3.
NOTE if you are using python 3.x:
request.FILES
is a multivalue dictionary like object that keeps the files uploaded through an upload file button. Say in your html code the name of the button (type="file") is "myfile" so "myfile" will be the key in this dictionary. If you uploaded one file, then the value for this key will be only one and if you uploaded multiple files, then you will have multiple values for that specific key. If you use request.FILES['myfile']
you will get the first or last value (I cannot say for sure). This is fine if you only uploaded one file, but if you want to get all files you should do this:
list=[] #myfile is the key of a multi value dictionary, values are the uploaded files
for f in request.FILES.getlist('myfile'): #myfile is the name of your html file button
filename = f.name
list.append(filename)
of course one can squeeze the whole thing in one line, but this is easy to understand
This is the tip provided to resolve the issue which does not work:
Tip - If your instance doesn't have a public DNS name, open the VPC console, select the VPC, and check the Summary tab. If either DNS resolution or DNS hostnames is no, click Edit and change the value to yes.
Assuming you have done this and you are still not getting a Public IP then go over to the subnet in question in the VPC admin screen and you will probably discover "Auto-Assign Public IP" is not set to yes. Modify that setting then, and I know you don't want to here this, create a new instance in that subnet. As far as I can tell you cannot modify this on the host, I tried and tried, just terminate it.
Replace [True | False (default)]
Effect
1. Replace the directive element.
Dependency:
1. When replace: true, the template or templateUrl must be required.
@Howard Hinnant's answer is both correct and comprehensive. But it might be misunderstood if it's read too quickly, because std::terminate()
(whole process) happens to have the same name as the "terminating" that @Alexander V had in mind (1 thread).
Summary: "terminate 1 thread + forcefully (target thread doesn't cooperate) + pure C++11 = No way."
To concatenate two strings in 2008 or prior:
SELECT ISNULL(FirstName, '') + ' ' + ISNULL(SurName, '')
good to use ISNULL because "String + NULL" will give you a NULL only
One more thing: Make sure you are concatenating strings otherwise use a CAST operator:
SELECT 2 + 3
Will give 5
SELECT '2' + '3'
Will give 23
SET myParam = IFNULL(myParam, 0);
Explanation: IFNULL(expression_1, expression_2)
The IFNULL
function returns expression_1
if expression_1
is not NULL
; otherwise it returns expression_2
. The IFNULL
function returns a string or a numeric based on the context where it is used.
It because every time
void pthread_exit(void *ret);
will be called from thread function so which ever you want to return simply its pointer pass with pthread_exit().
Now at
int pthread_join(pthread_t tid, void **ret);
will be always called from where thread is created so here to accept that returned pointer you need double pointer ..
i think this code will help you to understand this
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
void* thread_function(void *ignoredInThisExample)
{
char *a = malloc(10);
strcpy(a,"hello world");
pthread_exit((void*)a);
}
int main()
{
pthread_t thread_id;
char *b;
pthread_create (&thread_id, NULL,&thread_function, NULL);
pthread_join(thread_id,(void**)&b); //here we are reciving one pointer
value so to use that we need double pointer
printf("b is %s\n",b);
free(b); // lets free the memory
}
In general, one doesn't expand out log(a + b)
; you just deal with it as is. That said, there are occasionally circumstances where it makes sense to use the following identity:
log(a + b) = log(a * (1 + b/a)) = log a + log(1 + b/a)
(In fact, this identity is often used when implementing log
in math libraries).
Arrays are objects and they have a length field.
String[] haha = {"olle", "bulle"};
haha.length would be 2
//do the edit in your javascript
$('.signinform').submit(function() {
$(this).ajaxSubmit({
type : "POST",
//set the data type
dataType:'json',
url: 'index.php/user/signin', // target element(s) to be updated with server response
cache : false,
//check this in Firefox browser
success : function(response){ console.log(response); alert(response)},
error: onFailRegistered
});
return false;
});
//controller function
public function signin() {
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
//add the header here
header('Content-Type: application/json');
echo json_encode( $arr );
}
Using "<h1>STRING<h1>".getBytes();
you can create a ByteArrayDataSource
with content-type and set setDataHandler
in your MimeBodyPart
try:
String html "Test JavaMail API example. <br><br> Regards, <br>Ivonei Jr"
byte[] bytes = html.getBytes();
DataSource dataSourceHtml= new ByteArrayDataSource(bytes, "text/html");
MimeBodyPart bodyPart = new MimeBodyPart();
bodyPart.setDataHandler(new DataHandler(dataSourceHtml));
MimeMultipart mimeMultipart = new MimeMultipart();
mimeMultipart.addBodyPart(bodyPart);
I think you can use ndmin option of numpy.array. Keeping it to 2 says that it will be a (4,1) and transpose will be (1,4).
>>> a = np.array([12, 3, 4, 5], ndmin=2)
>>> print a.shape
>>> (1,4)
>>> print a.T.shape
>>> (4,1)
If you want to append
text or html to span
then you can do it as below.
$('p span#add_here').append('text goes here');
append will add text to span tag at the end.
to replace entire text or html inside of span you can use .text()
or .html()
You could set a margin for the table. Alternatively, wrap the table in a div and use the div's padding.
You can use the Google Maps API for that. See the blog post below for more information.
http://stuff.nekhbet.ro/2008/12/12/how-to-get-coordinates-for-a-given-address-using-php.html
I've put up some algorithms to do image interpolation on html canvas pixel arrays that might be useful here:
https://web.archive.org/web/20170104190425/http://jsperf.com:80/pixel-interpolation/2
These can be copy/pasted and can be used inside of web workers to resize images (or any other operation that requires interpolation - I'm using them to defish images at the moment).
I haven't added the lanczos stuff above, so feel free to add that as a comparison if you'd like.
Even though the ID selector is the simplest, you can also use the name selector as below:
$('[name='submitted[first_name]']').removeAttr('required');
For more see: https://api.jquery.com/attribute-equals-selector/
string decodedUrl = Uri.UnescapeDataString(url)
or
string decodedUrl = HttpUtility.UrlDecode(url)
Url is not fully decoded with one call. To fully decode you can call one of this methods in a loop:
private static string DecodeUrlString(string url) {
string newUrl;
while ((newUrl = Uri.UnescapeDataString(url)) != url)
url = newUrl;
return newUrl;
}
I have experienced the same problem when trying to publish my nodejs app in a private server running CentOs using root user. The same error is fired by "postinstall": "./node_modules/bower/bin/bower install" in my package.json file so the only solution that was working for me is to use both options to avoid the error:
1: use --allow-root option for bower install command
"postinstall": "./node_modules/bower/bin/bower --allow-root install"
2: use --unsafe-perm option for npm install command
npm install --unsafe-perm
Ad hoc query is type of computer definition. Which means this query is specially design to obtain any information when it is only needed. Predefined. refer this https://www.youtube.com/watch?v=0c8JEKmVXhU
"... that are independent of their timezone"
var timezone = d.getTimezoneOffset() // difference in minutes from GMT
You can use -k
option to run test cases with different patterns:
py.test tests_directory/foo.py tests_directory/bar.py -k 'test_001 or test_some_other_test'
This will run test cases with name test_001 and test_some_other_test deselecting the rest of the test cases.
Note: This will select any test case starting with test_001 or test_some_other_test. For example, if you have test case test_0012 it will also be selected.
I'm using a newer version of the SPO Management Shell. For me to get the error to go away, I changed my Import-Module statement to use:
Import-Module Microsoft.Online.SharePoint.PowerShell -DisableNameChecking;
I also use the newer command:
Connect-SPOService
Here is a solution under 19API lvl:
First of all. Make a Gson obj. --> Gson gson = new Gson();
Second step is get your jsonObj as String with StringRequest(instead of JsonObjectRequest)
YoursObjArray[] yoursObjArray = gson.fromJson(response, YoursObjArray[].class);
As a heads up to others, I've oberserved that at least as manifested by TypeScript compiled by WebPack for Angular 2, you quietly get overWRITTEN instead of overLOADED methods.
myComponent {
method(): { console.info("no args"); },
method(arg): { console.info("with arg"); }
}
Calling:
myComponent.method()
seems to execute the method with arguments, silently ignoring the no-arg version, with output:
with arg
Solution #1: Your statement
.Range(Cells(RangeStartRow, RangeStartColumn), Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues
does not refer to a proper Range
to act upon. Instead,
.Range(.Cells(RangeStartRow, RangeStartColumn), .Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues
does (and similarly in some other cases).
Solution #2:
Activate Worksheets("Cable Cards")
prior to using its cells.
Explanation:
Cells(RangeStartRow, RangeStartColumn)
(e.g.) gives you a Range
, that would be ok, and that is why you often see Cells
used in this way. But since it is not applied to a specific object, it applies to the ActiveSheet
. Thus, your code attempts using .Range(rng1, rng2)
, where .Range
is a method of one Worksheet
object and rng1
and rng2
are in a different Worksheet
.
There are two checks that you can do to make this quite evident:
Activate your Worksheets("Cable Cards")
prior to executing your Sub
and it will start working (now you have well-formed references to Range
s). For the code you posted, adding .Activate
right after With...
would indeed be a solution, although you might have a similar problem somewhere else in your code when referring to a Range
in another Worksheet
.
With a sheet other than Worksheets("Cable Cards")
active, set a breakpoint at the line throwing the error, start your Sub
, and when execution breaks, write at the immediate window
Debug.Print Cells(RangeStartRow, RangeStartColumn).Address(external:=True)
Debug.Print .Cells(RangeStartRow, RangeStartColumn).Address(external:=True)
and see the different outcomes.
Conclusion:
Using Cells
or Range
without a specified object (e.g., Worksheet
, or Range
) might be dangerous, especially when working with more than one Sheet
, unless one is quite sure about what Sheet
is active.
If you could use List
as a data structure to store your data, instead of using Map
to store the result in the value of the Map, you can use following snippet and store the result in the same object.
Here is a Node class:
private class Node {
public int row, col, distance;
public Node(int row, int col, int distance) {
this.row = row;
this.col = col;
this.distance = distance;
}
public boolean equals(Object o) {
return (o instanceof Node &&
row == ((Node) o).row &&
col == ((Node) o).col);
}
}
If you store your result in distance variable and the items in the list are checked based on their coordinates, you can use the following to change the distance to a new one with the help of lastIndexOf method as long as you only need to store one element for each data:
List<Node> nodeList;
nodeList = new ArrayList<>(Arrays.asList(new Node(1, 2, 1), new Node(3, 4, 5)));
Node tempNode = new Node(1, 2, 10);
if(nodeList.contains(tempNode))
nodeList.get(nodeList.lastIndexOf(tempNode)).distance += tempNode.distance;
It is basically reimplementing Set
whose items can be accessed and changed.
I would say no, because the Developer docs on RAM usage state:
...
GC_EXPLICIT
An explicit GC, such as when you call gc() (which you should avoid calling and instead trust the GC to run when needed).
...
I've highlighted the relevant part in bold.
Have a look at the YouTube series, Android Performance Patterns - it will show you tips on managing your app's memory usage (such as using Android's ArrayMap
s and SparseArray
s instead of HashMap
s).
This function will clear the sheet data starting from specified row and column :
Sub ClearWKSData(wksCur As Worksheet, iFirstRow As Integer, iFirstCol As Integer)
Dim iUsedCols As Integer
Dim iUsedRows As Integer
iUsedRows = wksCur.UsedRange.Row + wksCur.UsedRange.Rows.Count - 1
iUsedCols = wksCur.UsedRange.Column + wksCur.UsedRange.Columns.Count - 1
If iUsedRows > iFirstRow And iUsedCols > iFirstCol Then
wksCur.Range(wksCur.Cells(iFirstRow, iFirstCol), wksCur.Cells(iUsedRows, iUsedCols)).Clear
End If
End Sub
ord()
will not work because your end string is two characters long.
Returns the ASCII value of the first character of string.
From my testing, you need to check that the end
string doesn't get "stepped over". The perl-style character incrementation is a cool method, but it is a single-stepping method. For this reason, an inner loop helps it along when necessary. This is actually not a bother, in fact, it is useful because we need to check if the loop(s) should be broken on each single step.
Code: (Demo)
function excelCols($letter,$end,$step=1){ // function doesn't check that $end is "later" than $letter
if($step==0)return []; // prevent infinite loop
do{
$letters[]=$letter; // store letter
for($x=0; $x<$step; ++$x){ // increment in accordance with $step declaration
if($letter===$end)break(2); // break if end is "stepped on"
++$letter;
}
}while(true);
return $letters;
}
echo implode(' ',excelCols('A','JJ',4));
echo "\n --- \n";
echo implode(' ',excelCols('A','BB',3));
echo "\n --- \n";
echo implode(' ',excelCols('A','ZZ',1));
echo "\n --- \n";
echo implode(' ',excelCols('A','ZZ',3));
Output:
A E I M Q U Y AC AG AK AO AS AW BA BE BI BM BQ BU BY CC CG CK CO CS CW DA DE DI DM DQ DU DY EC EG EK EO ES EW FA FE FI FM FQ FU FY GC GG GK GO GS GW HA HE HI HM HQ HU HY IC IG IK IO IS IW JA JE JI
---
A D G J M P S V Y AB AE AH AK AN AQ AT AW AZ
---
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z AA AB AC AD AE AF AG AH AI AJ AK AL AM AN AO AP AQ AR AS AT AU AV AW AX AY AZ BA BB BC BD BE BF BG BH BI BJ BK BL BM BN BO BP BQ BR BS BT BU BV BW BX BY BZ CA CB CC CD CE CF CG CH CI CJ CK CL CM CN CO CP CQ CR CS CT CU CV CW CX CY CZ DA DB DC DD DE DF DG DH DI DJ DK DL DM DN DO DP DQ DR DS DT DU DV DW DX DY DZ EA EB EC ED EE EF EG EH EI EJ EK EL EM EN EO EP EQ ER ES ET EU EV EW EX EY EZ FA FB FC FD FE FF FG FH FI FJ FK FL FM FN FO FP FQ FR FS FT FU FV FW FX FY FZ GA GB GC GD GE GF GG GH GI GJ GK GL GM GN GO GP GQ GR GS GT GU GV GW GX GY GZ HA HB HC HD HE HF HG HH HI HJ HK HL HM HN HO HP HQ HR HS HT HU HV HW HX HY HZ IA IB IC ID IE IF IG IH II IJ IK IL IM IN IO IP IQ IR IS IT IU IV IW IX IY IZ JA JB JC JD JE JF JG JH JI JJ JK JL JM JN JO JP JQ JR JS JT JU JV JW JX JY JZ KA KB KC KD KE KF KG KH KI KJ KK KL KM KN KO KP KQ KR KS KT KU KV KW KX KY KZ LA LB LC LD LE LF LG LH LI LJ LK LL LM LN LO LP LQ LR LS LT LU LV LW LX LY LZ MA MB MC MD ME MF MG MH MI MJ MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ NA NB NC ND NE NF NG NH NI NJ NK NL NM NN NO NP NQ NR NS NT NU NV NW NX NY NZ OA OB OC OD OE OF OG OH OI OJ OK OL OM ON OO OP OQ OR OS OT OU OV OW OX OY OZ PA PB PC PD PE PF PG PH PI PJ PK PL PM PN PO PP PQ PR PS PT PU PV PW PX PY PZ QA QB QC QD QE QF QG QH QI QJ QK QL QM QN QO QP QQ QR QS QT QU QV QW QX QY QZ RA RB RC RD RE RF RG RH RI RJ RK RL RM RN RO RP RQ RR RS RT RU RV RW RX RY RZ SA SB SC SD SE SF SG SH SI SJ SK SL SM SN SO SP SQ SR SS ST SU SV SW SX SY SZ TA TB TC TD TE TF TG TH TI TJ TK TL TM TN TO TP TQ TR TS TT TU TV TW TX TY TZ UA UB UC UD UE UF UG UH UI UJ UK UL UM UN UO UP UQ UR US UT UU UV UW UX UY UZ VA VB VC VD VE VF VG VH VI VJ VK VL VM VN VO VP VQ VR VS VT VU VV VW VX VY VZ WA WB WC WD WE WF WG WH WI WJ WK WL WM WN WO WP WQ WR WS WT WU WV WW WX WY WZ XA XB XC XD XE XF XG XH XI XJ XK XL XM XN XO XP XQ XR XS XT XU XV XW XX XY XZ YA YB YC YD YE YF YG YH YI YJ YK YL YM YN YO YP YQ YR YS YT YU YV YW YX YY YZ ZA ZB ZC ZD ZE ZF ZG ZH ZI ZJ ZK ZL ZM ZN ZO ZP ZQ ZR ZS ZT ZU ZV ZW ZX ZY ZZ
---
A D G J M P S V Y AB AE AH AK AN AQ AT AW AZ BC BF BI BL BO BR BU BX CA CD CG CJ CM CP CS CV CY DB DE DH DK DN DQ DT DW DZ EC EF EI EL EO ER EU EX FA FD FG FJ FM FP FS FV FY GB GE GH GK GN GQ GT GW GZ HC HF HI HL HO HR HU HX IA ID IG IJ IM IP IS IV IY JB JE JH JK JN JQ JT JW JZ KC KF KI KL KO KR KU KX LA LD LG LJ LM LP LS LV LY MB ME MH MK MN MQ MT MW MZ NC NF NI NL NO NR NU NX OA OD OG OJ OM OP OS OV OY PB PE PH PK PN PQ PT PW PZ QC QF QI QL QO QR QU QX RA RD RG RJ RM RP RS RV RY SB SE SH SK SN SQ ST SW SZ TC TF TI TL TO TR TU TX UA UD UG UJ UM UP US UV UY VB VE VH VK VN VQ VT VW VZ WC WF WI WL WO WR WU WX XA XD XG XJ XM XP XS XV XY YB YE YH YK YN YQ YT YW YZ ZC ZF ZI ZL ZO ZR ZU ZX
Here is an array-functions approach:
Code: (Demo)
$start='C';
$end='DD';
$step=4;
// generate and store more than we need (this is an obvious method disadvantage)
$result=$array=range('A','Z',1); // store A - Z as $array and $result
foreach($array as $a){
foreach($array as $b){
$result[]="$a$b"; // store double letter combinations
if(in_array($end,$result)){break(2);} // stop asap
}
}
//echo implode(' ',$result),"\n\n";
// slice away from the front of the array
$result=array_slice($result,array_search($start,$result)); // reindex keys
//echo implode(' ',$result),"\n\n";
// punch out elements that are not "stepped on"
$result=array_filter($result,function($k)use($step){return $k%$step==0;},ARRAY_FILTER_USE_KEY); // use modulo
// result is ready
echo implode(' ',$result);
Output:
C G K O S W AA AE AI AM AQ AU AY BC BG BK BO BS BW CA CE CI CM CQ CU CY DC
There is a random password string generator with selected length
let input = document.querySelector("textarea");_x000D_
let button = document.querySelector("button");_x000D_
let length = document.querySelector("input");_x000D_
_x000D_
function generatePassword(n) _x000D_
{_x000D_
let pwd = "";_x000D_
_x000D_
while(!pwd || pwd.length < n)_x000D_
{_x000D_
pwd += Math.random().toString(36).slice(-22);_x000D_
}_x000D_
_x000D_
return pwd.substring(0, n);_x000D_
}_x000D_
_x000D_
button.addEventListener("click", function()_x000D_
{_x000D_
input.value = generatePassword(length.value);_x000D_
});
_x000D_
<div>password:</div>_x000D_
<div><textarea cols="70" rows="10"></textarea></div>_x000D_
<div>length:</div>_x000D_
<div><input type="number" value="200"></div>_x000D_
<br>_x000D_
<button>gen</button>
_x000D_
Looks like you're already using request
module.
in this case all you need to post multipart/form-data
is to use its form
feature:
var req = request.post(url, function (err, resp, body) {
if (err) {
console.log('Error!');
} else {
console.log('URL: ' + body);
}
});
var form = req.form();
form.append('file', '<FILE_DATA>', {
filename: 'myfile.txt',
contentType: 'text/plain'
});
but if you want to post some existing file from your file system, then you may simply pass it as a readable stream:
form.append('file', fs.createReadStream(filepath));
request
will extract all related metadata by itself.
For more information on posting multipart/form-data
see node-form-data
module, which is internally used by request
.
I followed around five different answers as well as all the blog posts in the previous answers and still had problems. I was trying to add a listener to some existing code that was tracing using the TraceSource.TraceEvent(TraceEventType, Int32, String)
method where the TraceSource
object was initialised with a string making it a 'named source'.
For me the issue was not creating a valid combination of source and switch elements to target this source. Here is an example that will log to a file called tracelog.txt
. For the following code:
TraceSource source = new TraceSource("sourceName");
source.TraceEvent(TraceEventType.Verbose, 1, "Trace message");
I successfully managed to log with the following diagnostics configuration:
<system.diagnostics>
<sources>
<source name="sourceName" switchName="switchName">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="tracelog.txt" />
</listeners>
</source>
</sources>
<switches>
<add name="switchName" value="Verbose" />
</switches>
</system.diagnostics>
Encountered the same error in different use case.
Use Case: In chrome when tried to call Spring REST end point in angular.
Solution: Add @CrossOrigin("*") annotation on top of respective Controller Class.
Use this cmd to display the packages in your device (for windows users)
adb shell pm list packages
then you can delete completely the package with the following cmd
adb uninstall com.example.myapp
What's happening is the onClick function you are trying to implement gets executed immediately.
As our code is not HTML it is javascript so it is interpreted as a function execution.
onClick function takes a function as argument not an function execution.
const items = ['EN', 'IT', 'FR', 'GR', 'RU'].map((item) => {
return (<li onClick={(e) => onItemClick(e, item)} key={item}>{item}</li>);
});
this will define an onClick function on List Item that will get executed after clicking on it not as soon as our component renders.
Actually, Eclipse support for Java 8 is available: see here and here.
parent {_x000D_
position: relative;_x000D_
}_x000D_
child {_x000D_
position: absolute;_x000D_
left: 50%;_x000D_
transform: translateX(-50%);_x000D_
}
_x000D_
<parent>_x000D_
<child>_x000D_
</child>_x000D_
</parent>
_x000D_
I use XCOPY
with the following parameters for copying .NET assemblies:
/D /Y /R /H
/D:m-d-y - Copies files changed on or after the specified date. If no date is given, copies only those files whose source time is newer than the destination time.
/Y - Suppresses prompting to confirm you want to overwrite an existing destination file.
/R - Overwrites read-only files.
/H - Copies hidden and system files also.
If each file only has one sequence of aminoacids, I wouldn't use regular expressions at all. Just something like this:
def read_amino_acid_sequence(path):
with open(path) as sequence_file:
title = sequence_file.readline() # read 1st line
aminoacid_sequence = sequence_file.read() # read the rest
# some cleanup, if necessary
title = title.strip() # remove trailing white spaces and newline
aminoacid_sequence = aminoacid_sequence.replace(" ","").replace("\n","")
return title, aminoacid_sequence
str.replace is the wrong function for what you want to do (apart from it being used incorrectly). You want to replace any character of a set with a space, not the whole set with a single space (the latter is what replace does). You can use translate like this:
removeSpecialChars = z.translate ({ord(c): " " for c in "!@#$%^&*()[]{};:,./<>?\|`~-=_+"})
This creates a mapping which maps every character in your list of special characters to a space, then calls translate() on the string, replacing every single character in the set of special characters with a space.
You asked:
I was looking for a one-liner like:
Ask and ye shall receive. Convert from terrible legacy class Date
to its modern replacement, Instant
.
myJavaUtilDate.toInstant().toString()
2020-05-05T19:46:12.912Z
In Java 8 and later we have the new java.time package built in (Tutorial). Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project.
The best solution is to sort your date-time objects rather than strings. But if you must work in strings, read on.
An Instant
represents a moment on the timeline, basically in UTC (see class doc for precise details). The toString
implementation uses the DateTimeFormatter.ISO_INSTANT
format by default. This format includes zero, three, six or nine digits digits as needed to display fraction of a second up to nanosecond precision.
String output = Instant.now().toString(); // Example: '2015-12-03T10:15:30.120Z'
If you must interoperate with the old Date
class, convert to/from java.time via new methods added to the old classes. Example: Date::toInstant
.
myJavaUtilDate.toInstant().toString()
You may want to use an alternate formatter if you need a consistent number of digits in the fractional second or if you need no fractional second.
Another route if you want to truncate fractions of a second is to use ZonedDateTime
instead of Instant
, calling its method to change the fraction to zero.
Note that we must specify a time zone for ZonedDateTime
(thus the name). In our case that means UTC. The subclass of ZoneID
, ZoneOffset
, holds a convenient constant for UTC. If we omit the time zone, the JVM’s current default time zone is implicitly applied.
String output = ZonedDateTime.now( ZoneOffset.UTC ).withNano( 0 ).toString(); // Example: 2015-08-27T19:28:58Z
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
UPDATE: The Joda -Time project is now in maintenance mode, with the team advising migration to the java.time classes.
I was looking for a one-liner
Easy if using the Joda-Time 2.3 library. ISO 8601 is the default formatting.
In the code example below, note that I am specifying a time zone rather than depending on the default time zone. In this case, I'm specifying UTC per your question. The Z
on the end, spoken as "Zulu", means no time zone offset from UTC.
// import org.joda.time.*;
String output = new DateTime( DateTimeZone.UTC );
Output…
2013-12-12T18:29:50.588Z
Your other option is to initialize j
:
j = [None] * len(i)
try this code I think it is more optimal.
HeaderRow is used to repeat the header of the table for each new page automatically
BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
iTextSharp.text.Font times = new iTextSharp.text.Font(bfTimes, 6, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
PdfPTable table = new PdfPTable(10) { HorizontalAlignment = Element.ALIGN_CENTER, WidthPercentage = 100, HeaderRows = 2 };
table.SetWidths(new float[] { 2f, 6f, 6f, 3f, 5f, 8f, 5f, 5f, 5f, 5f });
table.AddCell(new PdfPCell(new Phrase("SER.\nNO.", times)) { Rowspan = 2, GrayFill = 0.95f });
table.AddCell(new PdfPCell(new Phrase("TYPE OF SHIPPING", times)) { GrayFill = 0.95f });
table.AddCell(new PdfPCell(new Phrase("ORDER NO.", times)) { GrayFill = 0.95f });
table.AddCell(new PdfPCell(new Phrase("QTY.", times)) { GrayFill = 0.95f });
table.AddCell(new PdfPCell(new Phrase("DISCHARGE PPORT", times)) { GrayFill = 0.95f });
table.AddCell(new PdfPCell(new Phrase("DESCRIPTION OF GOODS", times)) { Rowspan = 2, GrayFill = 0.95f });
table.AddCell(new PdfPCell(new Phrase("LINE DOC. RECL DATE", times)) { GrayFill = 0.95f });
table.AddCell(new PdfPCell(new Phrase("CLEARANCE DATE", times)) { Rowspan = 2, GrayFill = 0.95f });
table.AddCell(new PdfPCell(new Phrase("CUSTOM PERMIT NO.", times)) { Rowspan = 2, GrayFill = 0.95f });
table.AddCell(new PdfPCell(new Phrase("DISPATCH DATE", times)) { Rowspan = 2, GrayFill = 0.95f });
table.AddCell(new PdfPCell(new Phrase("AWB/BL NO.", times)) { GrayFill = 0.95f });
table.AddCell(new PdfPCell(new Phrase("COMPLEX NAME", times)) { GrayFill = 0.95f });
table.AddCell(new PdfPCell(new Phrase("G. W. Kgs.", times)) { GrayFill = 0.95f });
table.AddCell(new PdfPCell(new Phrase("DESTINATION", times)) { GrayFill = 0.95f });
table.AddCell(new PdfPCell(new Phrase("OWNER DOC. RECL DATE", times)) { GrayFill = 0.95f });
I prefer not to alter the df
.
An option is to retrieve the index
of the start
and end
dates:
import numpy as np
import pandas as pd
#Dummy DataFrame
df = pd.DataFrame(np.random.random((30, 3)))
df['date'] = pd.date_range('2017-1-1', periods=30, freq='D')
#Get the index of the start and end dates respectively
start = df[df['date']=='2017-01-07'].index[0]
end = df[df['date']=='2017-01-14'].index[0]
#Show the sliced df (from 2017-01-07 to 2017-01-14)
df.loc[start:end]
which results in:
0 1 2 date
6 0.5 0.8 0.8 2017-01-07
7 0.0 0.7 0.3 2017-01-08
8 0.8 0.9 0.0 2017-01-09
9 0.0 0.2 1.0 2017-01-10
10 0.6 0.1 0.9 2017-01-11
11 0.5 0.3 0.9 2017-01-12
12 0.5 0.4 0.3 2017-01-13
13 0.4 0.9 0.9 2017-01-14
It is OK, but at the same time can cause some browsers to become slow.
http://webdesignfan.com/yslow-tutorial-part-2-of-3-reducing-server-calls/
My advice is use <a href="#"></a>
If you're using JQuery remember to also use:
.click(function(event){
event.preventDefault();
// Click code here...
});
In case others have a hard time making sense of this, I think it might help to explain it in very straightforward terms. If you have a variable that you don't use, for example a function for which you've commented out the invocation (a common use-case):
myFn := func () { }
// myFn()
You can assign a useless/blank variable to the function so that it's no longer unused:
myFn := func () { }
_ = myFn
// myFn()
Updated 5 September 2010
Seeing as everyone seems to get directed here for this issue, I'm adding my answer to a similar question, which contains the same code as this answer but with full background for those who are interested:
IE's document.selection.createRange doesn't include leading or trailing blank lines
To account for trailing line breaks is tricky in IE, and I haven't seen any solution that does this correctly, including any other answers to this question. It is possible, however, using the following function, which will return you the start and end of the selection (which are the same in the case of a caret) within a <textarea>
or text <input>
.
Note that the textarea must have focus for this function to work properly in IE. If in doubt, call the textarea's focus()
method first.
function getInputSelection(el) {
var start = 0, end = 0, normalizedValue, range,
textInputRange, len, endRange;
if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
start = el.selectionStart;
end = el.selectionEnd;
} else {
range = document.selection.createRange();
if (range && range.parentElement() == el) {
len = el.value.length;
normalizedValue = el.value.replace(/\r\n/g, "\n");
// Create a working TextRange that lives only in the input
textInputRange = el.createTextRange();
textInputRange.moveToBookmark(range.getBookmark());
// Check if the start and end of the selection are at the very end
// of the input, since moveStart/moveEnd doesn't return what we want
// in those cases
endRange = el.createTextRange();
endRange.collapse(false);
if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
start = end = len;
} else {
start = -textInputRange.moveStart("character", -len);
start += normalizedValue.slice(0, start).split("\n").length - 1;
if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
end = len;
} else {
end = -textInputRange.moveEnd("character", -len);
end += normalizedValue.slice(0, end).split("\n").length - 1;
}
}
}
}
return {
start: start,
end: end
};
}
How about something like this?
val newDF = df.filter($"B" === "").take(1) match {
case Array() => df
case _ => df.withColumn("D", $"B" === "")
}
Using take(1)
should have a minimal hit
Using the TreeMap you can sort the Map.
Map<String, String> map = new HashMap<String, String>();
Map<String, String> treeMap = new TreeMap<String, String>(map);
//show hashmap after the sort
for (String str : treeMap.keySet()) {
System.out.println(str);
}
I think it is good to categorize relations like this
When to use eager loading
When to use lazy loading
Note: like Transcendent said there may be disposal problem with lazy loading.
As Jason says, you can create a variable of the right type and pass that. You might want to encapsulate it in your own method:
public static DateTime? TryParse(string text)
{
DateTime date;
if (DateTime.TryParse(text, out date))
{
return date;
}
else
{
return null;
}
}
... or if you like the conditional operator:
public static DateTime? TryParse(string text)
{
DateTime date;
return DateTime.TryParse(text, out date) ? date : (DateTime?) null;
}
Or in C# 7:
public static DateTime? TryParse(string text) =>
DateTime.TryParse(text, out var date) ? date : (DateTime?) null;
Give something like this a try:
$(document).ready(function(){
$("#thisTable tr").click(function(){
$(this).find("td").each(function(){
alert($(this).html());
});
});
});?
Here is a fiddle of the code in action: http://jsfiddle.net/YhZsW/
The correct default choice is add InterruptedException to your throws list. An Interrupt indicates that another thread wishes your thread to end. The reason for this request is not made evident and is entirely contextual, so if you don't have any additional knowledge you should assume it's just a friendly shutdown, and anything that avoids that shutdown is a non-friendly response.
Java will not randomly throw InterruptedException's, all advice will not affect your application but I have run into a case where developer's following the "swallow" strategy became very inconvenient. A team had developed a large set of tests and used Thread.Sleep a lot. Now we started to run the tests in our CI server, and sometimes due to defects in the code would get stuck into permanent waits. To make the situation worse, when attempting to cancel the CI job it never closed because the Thread.Interrupt that was intended to abort the test did not abort the job. We had to login to the box and manually kill the processes.
So long story short, if you simply throw the InterruptedException you are matching the default intent that your thread should end. If you can't add InterruptedException to your throw list, I'd wrap it in a RuntimeException.
There is a very rational argument to be made that InterruptedException should be a RuntimeException itself, since that would encourage a better "default" handling. It's not a RuntimeException only because the designers stuck to a categorical rule that a RuntimeException should represent an error in your code. Since an InterruptedException does not arise directly from an error in your code, it's not. But the reality is that often an InterruptedException arises because there is an error in your code, (i.e. endless loop, dead-lock), and the Interrupt is some other thread's method for dealing with that error.
If you know there is rational cleanup to be done, then do it. If you know a deeper cause for the Interrupt, you can take on more comprehensive handling.
So in summary your choices for handling should follow this list:
To merge the two arrays on id
, assuming the arrays are equal length:
arr1.map(item => ({
...item,
...arr2.find(({ id }) => id === item.id),
}));
Please see the answer by Martin Smith for a better illustations and explanations of the different joins, including and especially differences between FULL OUTER JOIN
, RIGHT OUTER JOIN
and LEFT OUTER JOIN
.
These two table form a basis for the representation of the JOIN
s below:
SELECT *
FROM citizen
CROSS JOIN postalcode
The result will be the Cartesian products of all combinations. No JOIN
condition required:
INNER JOIN
is the same as simply: JOIN
SELECT *
FROM citizen c
JOIN postalcode p ON c.postal = p.postal
The result will be combinations that satisfies the required JOIN
condition:
LEFT OUTER JOIN
is the same as LEFT JOIN
SELECT *
FROM citizen c
LEFT JOIN postalcode p ON c.postal = p.postal
The result will be everything from citizen
even if there are no matches in postalcode
. Again a JOIN
condition is required:
All examples have been run on an Oracle 18c. They're available at dbfiddle.uk which is also where screenshots of tables came from.
CREATE TABLE citizen (id NUMBER,
name VARCHAR2(20),
postal NUMBER, -- <-- could do with a redesign to postalcode.id instead.
leader NUMBER);
CREATE TABLE postalcode (id NUMBER,
postal NUMBER,
city VARCHAR2(20),
area VARCHAR2(20));
INSERT INTO citizen (id, name, postal, leader)
SELECT 1, 'Smith', 2200, null FROM DUAL
UNION SELECT 2, 'Green', 31006, 1 FROM DUAL
UNION SELECT 3, 'Jensen', 623, 1 FROM DUAL;
INSERT INTO postalcode (id, postal, city, area)
SELECT 1, 2200, 'BigCity', 'Geancy' FROM DUAL
UNION SELECT 2, 31006, 'SmallTown', 'Snizkim' FROM DUAL
UNION SELECT 3, 31006, 'Settlement', 'Moon' FROM DUAL -- <-- Uuh-uhh.
UNION SELECT 4, 78567390, 'LookoutTowerX89', 'Space' FROM DUAL;
JOIN
and WHERE
CROSS JOIN
resulting in rows as The General Idea/INNER JOIN
:
SELECT *
FROM citizen c
CROSS JOIN postalcode p
WHERE c.postal = p.postal -- < -- The WHERE condition is limiting the resulting rows
Using CROSS JOIN
to get the result of a LEFT OUTER JOIN
requires tricks like adding in a NULL
row. It's omitted.
INNER JOIN
becomes a cartesian products. It's the same as The General Idea/CROSS JOIN
:
SELECT *
FROM citizen c
JOIN postalcode p ON 1 = 1 -- < -- The ON condition makes it a CROSS JOIN
This is where the inner join can really be seen as the cross join with results not matching the condition removed. Here none of the resulting rows are removed.
Using INNER JOIN
to get the result of a LEFT OUTER JOIN
also requires tricks. It's omitted.
LEFT JOIN
results in rows as The General Idea/CROSS JOIN
:
SELECT *
FROM citizen c
LEFT JOIN postalcode p ON 1 = 1 -- < -- The ON condition makes it a CROSS JOIN
LEFT JOIN
results in rows as The General Idea/INNER JOIN
:
SELECT *
FROM citizen c
LEFT JOIN postalcode p ON c.postal = p.postal
WHERE p.postal IS NOT NULL -- < -- removed the row where there's no mathcing result from postalcode
An image internet search on "sql join cross inner outer" will show a multitude of Venn diagrams. I used to have a printed copy of one on my desk. But there are issues with the representation.
Venn diagram are excellent for set theory, where an element can be in one or both sets. But for databases, an element in one "set" seem, to me, to be a row in a table, and therefore not also present in any other tables. There is no such thing as one row present in multiple tables. A row is unique to the table.
Self joins are a corner case where each element is in fact the same in both sets. But it's still not free of any of the issues below.
The set A
represents the set on the left (the citizen
table) and the set B
is the set on the right (the postalcode
table) in below discussion.
Every element in both sets are matched with every element in the other set, meaning we need A
amount of every B
elements and B
amount of every A
elements to properly represent this Cartesian product. Set theory isn't made for multiple identical elements in a set, so I find Venn diagrams to properly represent it impractical/impossible. It doesn't seem that UNION
fits at all.
The rows are distinct. The UNION
is 7 rows in total. But they're incompatible for a common SQL
results set. And this is not how a CROSS JOIN
works at all:
Trying to represent it like this:
..but now it just looks like an INTERSECTION
, which it's certainly not. Furthermore there's no element in the INTERSECTION
that is actually in any of the two distinct sets. However, it looks very much like the searchable results similar to this:
For reference one searchable result for CROSS JOIN
s can be seen at Tutorialgateway. The INTERSECTION
, just like this one, is empty.
The value of an element depends on the JOIN
condition. It's possible to represent this under the condition that every row becomes unique to that condition. Meaning id=x
is only true for one row. Once a row in table A
(citizen
) matches multiple rows in table B
(postalcode
) under the JOIN
condition, the result has the same problems as the CROSS JOIN
: The row needs to be represented multiple times, and the set theory isn't really made for that. Under the condition of uniqueness, the diagram could work though, but keep in mind that the JOIN
condition determines the placement of an element in the diagram. Looking only at the values of the JOIN
condition with the rest of the row just along for the ride:
This representation falls completely apart when using an INNER JOIN
with a ON 1 = 1
condition making it into a CROSS JOIN
.
With a self-JOIN
, the rows are in fact idential elements in both tables, but representing the tables as both A
and B
isn't very suitable. For example a common self-JOIN
condition that makes an element in A
to be matching a different element in B is ON A.parent = B.child
, making the match from A
to B
on seperate elements. From the examples that would be a SQL
like this:
SELECT *
FROM citizen c1
JOIN citizen c2 ON c1.id = c2.leader
Meaning Smith is the leader of both Green and Jensen.
Again the troubles begin when one row has multiple matches to rows in the other table. This is further complicated because the OUTER JOIN
can be though of as to match the empty set. But in set theory the union of any set C
and an empty set, is always just C
. The empty set adds nothing. The representation of this LEFT OUTER JOIN
is usually just showing all of A
to illustrate that rows in A
are selected regardless of whether there is a match or not from B
. The "matching elements" however has the same problems as the illustration above. They depend on the condition. And the empty set seems to have wandered over to A
:
Finding all rows from a CROSS JOIN
with Smith and postalcode on the Moon:
SELECT *
FROM citizen c
CROSS JOIN postalcode p
WHERE c.name = 'Smith'
AND p.area = 'Moon';
Now the Venn diagram isn't used to reflect the JOIN
. It's used only for the WHERE
clause:
..and that makes sense.
As explained an INNER JOIN
is not really an INTERSECT
. However INTERSECT
s can be used on results of seperate queries. Here a Venn diagram makes sense, because the elements from the seperate queries are in fact rows that either belonging to just one of the results or both. Intersect will obviously only return results where the row is present in both queries. This SQL
will result in the same row as the one above WHERE
, and the Venn diagram will also be the same:
SELECT *
FROM citizen c
CROSS JOIN postalcode p
WHERE c.name = 'Smith'
INTERSECT
SELECT *
FROM citizen c
CROSS JOIN postalcode p
WHERE p.area = 'Moon';
An OUTER JOIN
is not a UNION
. However UNION
work under the same conditions as INTERSECT
, resulting in a return of all results combining both SELECT
s:
SELECT *
FROM citizen c
CROSS JOIN postalcode p
WHERE c.name = 'Smith'
UNION
SELECT *
FROM citizen c
CROSS JOIN postalcode p
WHERE p.area = 'Moon';
which is equivalent to:
SELECT *
FROM citizen c
CROSS JOIN postalcode p
WHERE c.name = 'Smith'
OR p.area = 'Moon';
..and gives the result:
Also here a Venn diagram makes sense:
An important note is that these only work when the structure of the results from the two SELECT's are the same, enabling a comparison or union. The results of these two will not enable that:
SELECT *
FROM citizen
WHERE name = 'Smith'
SELECT *
FROM postalcode
WHERE area = 'Moon';
..trying to combine the results with UNION
gives a
ORA-01790: expression must have same datatype as corresponding expression
For further interest read Say NO to Venn Diagrams When Explaining JOINs and sql joins as venn diagram. Both also cover EXCEPT
.
It is depends on the case and the usage. Generally, in TypeScript there are no default values for interfaces.
If you don't use the default values
You can declare x
as:
let x: IX | undefined; // declaration: x = undefined
Then, in your init function you can set real values:
x = {
a: 'xyz'
b: 123
c: new AnotherType()
};
In this way, x
can be undefined or defined - undefined
represents that the object is uninitialized, without set the default values, if they are unnecessary. This is loggically better than define "garbage".
If you want to partially assign the object:
You can define the type with optional properties like:
interface IX {
a: string,
b?: any,
c?: AnotherType
}
In this case you have to set only a
. The other types are marked with ?
which mean that they are optional and have undefined
as default value.
In any case you can use undefined
as a default value, it is just depends on your use case.
I recommend Pygments. It accepts a piece of code in any language and outputs syntax highlighted LaTeX code. It uses fancyvrb and color packages to produce its output. I personally prefer it to the listing package. I think fancyvrb creates much prettier results.
This answer was for @
Neha Gandhi but I modified it for people who use pdo and mysqli sing mysql functions are not supported. Here is the new answer
<html>
<!--Save this as index.php-->
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#display").click(function() {
$.ajax({ //create an ajax request to display.php
type: "GET",
url: "display.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
</script>
<body>
<h3 align="center">Manage Student Details</h3>
<table border="1" align="center">
<tr>
<td> <input type="button" id="display" value="Display All Data" /> </td>
</tr>
</table>
<div id="responsecontainer" align="center">
</div>
</body>
</html>
<?php
// save this as display.php
// show errors
error_reporting(E_ALL);
ini_set('display_errors', 1);
//errors ends here
// call the page for connecting to the db
require_once('dbconnector.php');
?>
<?php
$get_member =" SELECT
empid, lastName, firstName, email, usercode, companyid, userid, jobTitle, cell, employeetype, address ,initials FROM employees";
$user_coder1 = $con->prepare($get_member);
$user_coder1 ->execute();
echo "<table border='1' >
<tr>
<td align=center> <b>Roll No</b></td>
<td align=center><b>Name</b></td>
<td align=center><b>Address</b></td>
<td align=center><b>Stream</b></td></td>
<td align=center><b>Status</b></td>";
while($row =$user_coder1->fetch(PDO::FETCH_ASSOC)){
$firstName = $row['firstName'];
$empid = $row['empid'];
$lastName = $row['lastName'];
$cell = $row['cell'];
echo "<tr>";
echo "<td align=center>$firstName</td>";
echo "<td align=center>$empid</td>";
echo "<td align=center>$lastName </td>";
echo "<td align=center>$cell</td>";
echo "<td align=center>$cell</td>";
echo "</tr>";
}
echo "</table>";
?>
<?php
// save this as dbconnector.php
function connected_Db(){
$dsn = 'mysql:host=localhost;dbname=mydb;charset=utf8';
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
#echo "Yes we are connected";
return new PDO($dsn,'username','password', $opt);
}
$con = connected_Db();
if($con){
//echo "me is connected ";
}
else {
//echo "Connection faid ";
exit();
}
?>
Just download and install "Samsung Kies" from this link. and everything would work as required.
Before installing, uninstall the drivers you have installed for your device.
Update:
Two possible solutions:
This solution appears better to me, regarding maintainability and design for change:
Create the logging property file embedding it in the resource project folder, to be included in the jar file:
# Logging
handlers = java.util.logging.ConsoleHandler
.level = ALL
# Console Logging
java.util.logging.ConsoleHandler.level = ALL
Load the property file from code:
public static java.net.URL retrieveURLOfJarResource(String resourceName) {
return Thread.currentThread().getContextClassLoader().getResource(resourceName);
}
public synchronized void initializeLogger() {
try (InputStream is = retrieveURLOfJarResource("logging.properties").openStream()) {
LogManager.getLogManager().readConfiguration(is);
} catch (IOException e) {
// ...
}
}
I had mostly the same problem and ended up a a different solution that makes this type of problem trivial to query.
I have a table of sensor data (1 minute data from about 30 sensors)
SensorReadings->(timestamp,value,idSensor)
and I have a sensor table that has lots of mostly static stuff about the sensor but the relevant fields are these:
Sensors->(idSensor,Description,tvLastUpdate,tvLastValue,...)
The tvLastupdate and tvLastValue are set in a trigger on inserts to the SensorReadings table. I always have direct access to these values without needing to do any expensive queries. This does denormalize slightly. The query is trivial:
SELECT idSensor,Description,tvLastUpdate,tvLastValue
FROM Sensors
I use this method for data that is queried often. In my case I have a sensor table, and a large event table, that have data coming in at the minute level AND dozens of machines are updating dashboards and graphs with that data. With my data scenario the trigger-and-cache method works well.
The app object is instantiated on creation of the Express server. It has a middleware stack that can be customized in app.configure()
(this is now deprecated in version 4.x).
To setup your middleware, you can invoke app.use(<specific_middleware_layer_here>)
for every middleware layer that you want to add (it can be generic to all paths, or triggered only on specific path(s) your server handles), and it will add onto your Express middleware stack. Middleware layers can be added one by one in multiple invocations of use
, or even all at once in series with one invocation.
See use
documentation for more details.
To give an example for conceptual understanding of Express Middleware, here is what my app middleware stack (app.stack) looks like when logging my app object to the console as JSON:
stack:
[ { route: '', handle: [Function] },
{ route: '', handle: [Function: static] },
{ route: '', handle: [Function: bodyParser] },
{ route: '', handle: [Function: cookieParser] },
{ route: '', handle: [Function: session] },
{ route: '', handle: [Function: methodOverride] },
{ route: '', handle: [Function] },
{ route: '', handle: [Function] } ]
As you might be able to deduce, I called app.use(express.bodyParser())
, app.use(express.cookieParser())
, etc, which added these express middleware 'layers' to the middleware stack. Notice that the routes are blank, meaning that when I added those middleware layers I specified that they be triggered on any route. If I added a custom middleware layer that only triggered on the path /user/:id
that would be reflected as a string in the route
field of that middleware layer object in the stack printout above.
Each layer is essentially adding a function that specifically handles something to your flow through the middleware.
E.g. by adding bodyParser
, you're ensuring your server handles incoming requests through the express middleware. So, now parsing the body of incoming requests is part of the procedure that your middleware takes when handling incoming requests -- all because you called app.use(bodyParser)
.
The standard Pinterest button code (which you can generate here), is an <a>
tag wrapping an <img>
of the Pinterest button.
If you don't include the pinit.js
script on your page, this <a>
tag will work "as-is". You could improve the experience by registering your own click handler on these tags that opens a new window with appropriate dimensions, or at least adding target="_blank"
to the tag to make it open clicks in a new window.
The tag syntax would look like:
<a href="http://pinterest.com/pin/create/button/?url={URI-encoded URL of the page to pin}&media={URI-encoded URL of the image to pin}&description={optional URI-encoded description}" class="pin-it-button" count-layout="horizontal">
<img border="0" src="//assets.pinterest.com/images/PinExt.png" title="Pin It" />
</a>
If using the JavaScript versions of sharing buttons are ruining your page load times, you can improve your site by using asynchronous loading methods. For an example of doing this with the Pinterest button, check out my GitHub Pinterest button project with an improved HTML5 syntax.
You'll need different sized icons for iOS and Android, like Rockvic said. In addition, I recommend this site for generating different sized icons if anybody is interested. You don't need to download anything and it works perfectly.
Hope it helps.
The typical strategy for dodging static methods that you have no way of avoiding using, is by creating wrapped objects and using the wrapper objects instead.
The wrapper objects become facades to the real static classes, and you do not test those.
A wrapper object could be something like
public class Slf4jMdcWrapper {
public static final Slf4jMdcWrapper SINGLETON = new Slf4jMdcWrapper();
public String myApisToTheSaticMethodsInSlf4jMdcStaticUtilityClass() {
return MDC.getWhateverIWant();
}
}
Finally, your class under test can use this singleton object by, for example, having a default constructor for real life use:
public class SomeClassUnderTest {
final Slf4jMdcWrapper myMockableObject;
/** constructor used by CDI or whatever real life use case */
public myClassUnderTestContructor() {
this.myMockableObject = Slf4jMdcWrapper.SINGLETON;
}
/** constructor used in tests*/
myClassUnderTestContructor(Slf4jMdcWrapper myMock) {
this.myMockableObject = myMock;
}
}
And here you have a class that can easily be tested, because you do not directly use a class with static methods.
If you are using CDI and can make use of the @Inject annotation then it is even easier. Just make your Wrapper bean @ApplicationScoped, get that thing injected as a collaborator (you do not even need messy constructors for testing), and go on with the mocking.
Parsing means we are analyzing an object specifically. For example, when we enter some keywords in a search engine, they parse the keywords and give back results by searching for each word. So it is basically taking a string from the file and processing it to extract the information we want.
Example of parsing using indexOf
to calculate the position of a string in another string:
String s="What a Beautiful day!";
int i=s.indexOf("day");//value of i would be 17
int j=s.indexOf("be");//value of j would be -1
int k=s.indexOf("ea");//value of k would be 8
paresInt
essentially converts a String
to a Integer
.
String s="9876543";
int a=new Integer(s);//uses constructor
System.out.println("Constructor method: " + a);
a=Integer.parseInt(s);//uses parseInt() method
System.out.println("parseInt() method: " + a);
Output:
Constructor method: 9876543 parseInt() method: 9876543
Short answer: There's no way to do it using CSS only.
Long(er) answer: Why? Because when you do position: absolute;
, that takes your element out of the document's regular flow, so there's no way for the text to have any positional-relationship with it, unfortunately.
One of the possible alternatives is to float: right;
your div
, but if that doesn't achieve what you want, you'll have to use JavaScript/jQuery, or just come up with a better layout.
As already stated, screen -S SESSIONTITLE
works for starting a session with a title (SESSIONTITLE
), but if you start a session and later decide to change its title. This can be accomplished by using the default key bindings:
Ctrl+a, A
Which prompts:
Set windows title to:SESSIONTITLE
Change SESSIONTITLE
by backspacing and typing in the desired title. To confirm the name change and list all titles.
Ctrl+a, "
Just wanted to add my 2 cents to this in case this helps anyone, I had a similar problem but needed to remove multiple elements from an array list while it was being iterated over. the highest upvoted answer did it for me for the most part until I ran into errors and realized that the index was greater than the size of the array list in some instances because multiple elements were being removed but the index of the loop didn't keep track of that. I fixed this with a simple check:
ArrayList place_holder = new ArrayList();
place_holder.Add("1");
place_holder.Add("2");
place_holder.Add("3");
place_holder.Add("4");
for(int i = place_holder.Count-1; i>= 0; i--){
if(i>= place_holder.Count){
i = place_holder.Count-1;
}
// some method that removes multiple elements here
}
Simple version for Python 2.7+
my_ordered_dict = json.loads(json_str, object_pairs_hook=collections.OrderedDict)
Or for Python 2.4 to 2.6
import simplejson as json
import ordereddict
my_ordered_dict = json.loads(json_str, object_pairs_hook=ordereddict.OrderedDict)
I increase max memory to start node-chrome with -Xmx3g
, and it's work for me
CREATE PROCEDURE sp_deleteUserDetails
@Email varchar(255)
AS
declare @tempRegId as int
Delete UserRegistration where Email=@Email
set @tempRegId = (select Id from UserRegistration where Email = @Email)
Delete UserProfile where RegID=@tempRegId
RETURN 0
Just in case you are not sure the string starts with a word...
$input = ' Test me more ';
echo preg_replace('/(\s*)([^\s]*)(.*)/', '$2', $input); //Test
Sometimes you really want to set the axes limits before you plot the data. In that case, you can set the "autoscaling" feature of the Axes
or AxesSubplot
object. The functions of interest are set_autoscale_on
, set_autoscalex_on
, and set_autoscaley_on
.
In your case, you want to freeze the y axis' limits, but allow the x axis to expand to accommodate your data. Therefore, you want to change the autoscaley_on
property to False
. Here is a modified version of the FFT subplot snippet from your code:
fft_axes = pylab.subplot(h,w,2)
pylab.title("FFT")
fft = scipy.fft(rawsignal)
pylab.ylim([0,1000])
fft_axes.set_autoscaley_on(False)
pylab.plot(abs(fft))
But if you really want to add some animation while scrolling, you can try my simple plugin (AnimateScroll) which currently supports more than 30 easing styles
First of all, you can't import fonts to CSS that way.
You can add this code in HTML head:
<link href='http://fonts.googleapis.com/css?family=Oswald:400,300,700' rel='stylesheet' type='text/css'>
or to import it in CSS file like this:
@import url("http://fonts.googleapis.com/css?family=Oswald:400,300,700");
Then, in your css, you can edit the body's font-family:
body {
font-family: 'Oswald', sans-serif !important;
}
X509Certificate clientKey1 = null;
clientKey1 = new X509Certificate(AppSetting["certificatePath"],
AppSetting["pswd"]);
string url = "https://EndPointAddress";
FileStream fs = File.OpenRead(FilePath);
var streamContent = new StreamContent(fs);
var FileContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result);
FileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("ContentType");
var handler = new WebRequestHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ClientCertificates.Add(clientKey1);
handler.ServerCertificateValidationCallback = (httpRequestMessage, cert, cetChain, policyErrors) =>
{
return true;
};
using (var client = new HttpClient(handler))
{
// Post it
HttpResponseMessage httpResponseMessage = client.PostAsync(url, FileContent).Result;
if (!httpResponseMessage.IsSuccessStatusCode)
{
string ss = httpResponseMessage.StatusCode.ToString();
}
}
I didn't see how to add parameters to the method call, it took me a while to find it, so I add it here. How to pass parameters in (to the javascript function), use "arguments[0]" as the parameter place and then set the parameter as input parameter in the executeScript function.
driver.executeScript("function(arguments[0]);","parameter to send in");
In phpMyAdmin, click the table, and then click the Import tab at the top of the page.
Browse and open the csv file. Leave the charset as-is. Uncheck partial import unless you have a HUGE dataset (or slow server). The format should already have selected “CSV” after selecting your file, if not then select it (not using LOAD DATA). If you want to clear the whole table before importing, check “Replace table data with file”. Optionally check “Ignore duplicate rows” if you think you have duplicates in the CSV file. Now the important part, set the next four fields to these values:
Fields terminated by: ,
Fields enclosed by: “
Fields escaped by: \
Lines terminated by: auto
Currently these match the defaults except for “Fields terminated by”, which defaults to a semicolon.
Now click the Go button, and it should run successfully.
Some time when we use Environ()
function we may get the Library or property not found error. Use VBA.Environ()
or VBA.Environ$()
to avoid the error.
I wanted to add an answer if the checkboxes are being generated in a loop. For example if your structure is like this (Assuming you are using server side constructs on your View
, like a foreach
loop):
<li id="checkboxlist" class="list-group-item card">
<div class="checkbox checkbox-inline">
<label><input type="checkbox" id="checkbox1">Checkbox 1</label>
<label><input type="checkbox" id="checkbox2">Checkbox 2</label>
</div>
</li>
<li id="checkboxlist" class="list-group-item card">
<div class="checkbox checkbox-inline">
<label><input type="checkbox" id="checkbox1">Checkbox 1</label>
<label><input type="checkbox" id="checkbox2">Checkbox 2</label>
</div>
</li>
Corresponding Jquery
:
$(".list-group-item").each(function (i, li) {
var currentli = $(li);
$(currentli).find("#checkbox1").on('change', function () {
$(currentli).find("#checkbox2").not(this).prop('checked',false);
});
$(currentli).find("#checkbox2").on('change', function () {
$(currentli).find("#checkbox1").not(this).prop('checked', false);
});
});
Working DEMO: https://jsfiddle.net/gr67qk20/
FYI: g++ offers the non-standard __PRETTY_FUNCTION__ macro. Until just now I did not know about C99 __func__ (thanks Evan!). I think I still prefer __PRETTY_FUNCTION__ when it's available for the extra class scoping.
PS:
static string getScopedClassMethod( string thePrettyFunction )
{
size_t index = thePrettyFunction . find( "(" );
if ( index == string::npos )
return thePrettyFunction; /* Degenerate case */
thePrettyFunction . erase( index );
index = thePrettyFunction . rfind( " " );
if ( index == string::npos )
return thePrettyFunction; /* Degenerate case */
thePrettyFunction . erase( 0, index + 1 );
return thePrettyFunction; /* The scoped class name. */
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Login Page</title>
<style>
/* Basics */
html, body {
width: 100%;
height: 100%;
font-family: "Helvetica Neue", Helvetica, sans-serif;
color: #444;
-webkit-font-smoothing: antialiased;
background: #f0f0f0;
}
#container {
position: fixed;
width: 340px;
height: 280px;
top: 50%;
left: 50%;
margin-top: -140px;
margin-left: -170px;
background: #fff;
border-radius: 3px;
border: 1px solid #ccc;
box-shadow: 0 1px 2px rgba(0, 0, 0, .1);
}
form {
margin: 0 auto;
margin-top: 20px;
}
label {
color: #555;
display: inline-block;
margin-left: 18px;
padding-top: 10px;
font-size: 14px;
}
p a {
font-size: 11px;
color: #aaa;
float: right;
margin-top: -13px;
margin-right: 20px;
-webkit-transition: all .4s ease;
-moz-transition: all .4s ease;
transition: all .4s ease;
}
p a:hover {
color: #555;
}
input {
font-family: "Helvetica Neue", Helvetica, sans-serif;
font-size: 12px;
outline: none;
}
input[type=text],
input[type=password] ,input[type=time]{
color: #777;
padding-left: 10px;
margin: 10px;
margin-top: 12px;
margin-left: 18px;
width: 290px;
height: 35px;
border: 1px solid #c7d0d2;
border-radius: 2px;
box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .4), 0 0 0 5px #f5f7f8;
-webkit-transition: all .4s ease;
-moz-transition: all .4s ease;
transition: all .4s ease;
}
input[type=text]:hover,
input[type=password]:hover,input[type=time]:hover {
border: 1px solid #b6bfc0;
box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .7), 0 0 0 5px #f5f7f8;
}
input[type=text]:focus,
input[type=password]:focus,input[type=time]:focus {
border: 1px solid #a8c9e4;
box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .4), 0 0 0 5px #e6f2f9;
}
#lower {
background: #ecf2f5;
width: 100%;
height: 69px;
margin-top: 20px;
box-shadow: inset 0 1px 1px #fff;
border-top: 1px solid #ccc;
border-bottom-right-radius: 3px;
border-bottom-left-radius: 3px;
}
input[type=checkbox] {
margin-left: 20px;
margin-top: 30px;
}
.check {
margin-left: 3px;
font-size: 11px;
color: #444;
text-shadow: 0 1px 0 #fff;
}
input[type=submit] {
float: right;
margin-right: 20px;
margin-top: 20px;
width: 80px;
height: 30px;
font-size: 14px;
font-weight: bold;
color: #fff;
background-color: #acd6ef; /*IE fallback*/
background-image: -webkit-gradient(linear, left top, left bottom, from(#acd6ef), to(#6ec2e8));
background-image: -moz-linear-gradient(top left 90deg, #acd6ef 0%, #6ec2e8 100%);
background-image: linear-gradient(top left 90deg, #acd6ef 0%, #6ec2e8 100%);
border-radius: 30px;
border: 1px solid #66add6;
box-shadow: 0 1px 2px rgba(0, 0, 0, .3), inset 0 1px 0 rgba(255, 255, 255, .5);
cursor: pointer;
}
input[type=submit]:hover {
background-image: -webkit-gradient(linear, left top, left bottom, from(#b6e2ff), to(#6ec2e8));
background-image: -moz-linear-gradient(top left 90deg, #b6e2ff 0%, #6ec2e8 100%);
background-image: linear-gradient(top left 90deg, #b6e2ff 0%, #6ec2e8 100%);
}
input[type=submit]:active {
background-image: -webkit-gradient(linear, left top, left bottom, from(#6ec2e8), to(#b6e2ff));
background-image: -moz-linear-gradient(top left 90deg, #6ec2e8 0%, #b6e2ff 100%);
background-image: linear-gradient(top left 90deg, #6ec2e8 0%, #b6e2ff 100%);
}
</style>
</head>
<body>
<!-- Begin Page Content -->
<div id="container">
<form action="login_process.php" method="post">
<label for="loginmsg" style="color:hsla(0,100%,50%,0.5); font-family:"Helvetica Neue",Helvetica,sans-serif;"><?php echo @$_GET['msg'];?></label>
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<div id="lower">
<input type="checkbox"><label class="check" for="checkbox">Keep me logged in</label>
<input type="submit" value="Login">
</div>
<!--/ lower-->
</form>
</div>
<!--/ container-->
<!-- End Page Content -->
</body>
</html>
Powershell has an alias mapping echo to Write-Output
, so:
echo "filesizecounter : $filesizecounter"
MD5 is bad because of collision problems - two different passwords possibly generating the same md-5.
Sha-1 would be plenty secure for this. The reason you store the salted sha-1 version of the password is so that you the swerver do not keep the user's apassword on file, that they may be using with other people's servers. Otherwise, what difference does it make?
If the hacker steals your entire unencrypted database some how, the only thing a hashed salted password does is prevent him from impersonating the user for future signons - the hacker already has the data.
What good does it do the attacker to have the hashed value, if what your user inputs is a plain password?
And even if the hacker with future technology could generate a million sha-1 keys a second for a brute force attack, would your server handle a million logons a second for the hacker to test his keys? That's if you are letting the hacker try to logon with the salted sha-1 instead of a password like a normal logon.
The best bet is to limit bad logon attempts to some reasonable number - 25 for example, and then time the user out for a minute or two. And if the cumulative bady logon attempts hits 250 within 24 hours, shut the account access down and email the owner.
with
statementDifferentiating between exceptions that occur in a with
statement is tricky because they can originate in different places. Exceptions can be raised from either of the following places (or functions called therein):
ContextManager.__init__
ContextManager.__enter__
with
ContextManager.__exit__
For more details see the documentation about Context Manager Types.
If we want to distinguish between these different cases, just wrapping the with
into a try .. except
is not sufficient. Consider the following example (using ValueError
as an example but of course it could be substituted with any other exception type):
try:
with ContextManager():
BLOCK
except ValueError as err:
print(err)
Here the except
will catch exceptions originating in all of the four different places and thus does not allow to distinguish between them. If we move the instantiation of the context manager object outside the with
, we can distinguish between __init__
and BLOCK / __enter__ / __exit__
:
try:
mgr = ContextManager()
except ValueError as err:
print('__init__ raised:', err)
else:
try:
with mgr:
try:
BLOCK
except TypeError: # catching another type (which we want to handle here)
pass
except ValueError as err:
# At this point we still cannot distinguish between exceptions raised from
# __enter__, BLOCK, __exit__ (also BLOCK since we didn't catch ValueError in the body)
pass
Effectively this just helped with the __init__
part but we can add an extra sentinel variable to check whether the body of the with
started to execute (i.e. differentiating between __enter__
and the others):
try:
mgr = ContextManager() # __init__ could raise
except ValueError as err:
print('__init__ raised:', err)
else:
try:
entered_body = False
with mgr:
entered_body = True # __enter__ did not raise at this point
try:
BLOCK
except TypeError: # catching another type (which we want to handle here)
pass
except ValueError as err:
if not entered_body:
print('__enter__ raised:', err)
else:
# At this point we know the exception came either from BLOCK or from __exit__
pass
The tricky part is to differentiate between exceptions originating from BLOCK
and __exit__
because an exception that escapes the body of the with
will be passed to __exit__
which can decide how to handle it (see the docs). If however __exit__
raises itself, the original exception will be replaced by the new one. To deal with these cases we can add a general except
clause in the body of the with
to store any potential exception that would have otherwise escaped unnoticed and compare it with the one caught in the outermost except
later on - if they are the same this means the origin was BLOCK
or otherwise it was __exit__
(in case __exit__
suppresses the exception by returning a true value the outermost except
will simply not be executed).
try:
mgr = ContextManager() # __init__ could raise
except ValueError as err:
print('__init__ raised:', err)
else:
entered_body = exc_escaped_from_body = False
try:
with mgr:
entered_body = True # __enter__ did not raise at this point
try:
BLOCK
except TypeError: # catching another type (which we want to handle here)
pass
except Exception as err: # this exception would normally escape without notice
# we store this exception to check in the outer `except` clause
# whether it is the same (otherwise it comes from __exit__)
exc_escaped_from_body = err
raise # re-raise since we didn't intend to handle it, just needed to store it
except ValueError as err:
if not entered_body:
print('__enter__ raised:', err)
elif err is exc_escaped_from_body:
print('BLOCK raised:', err)
else:
print('__exit__ raised:', err)
PEP 343 -- The "with" Statement specifies an equivalent "non-with" version of the with
statement. Here we can readily wrap the various parts with try ... except
and thus differentiate between the different potential error sources:
import sys
try:
mgr = ContextManager()
except ValueError as err:
print('__init__ raised:', err)
else:
try:
value = type(mgr).__enter__(mgr)
except ValueError as err:
print('__enter__ raised:', err)
else:
exit = type(mgr).__exit__
exc = True
try:
try:
BLOCK
except TypeError:
pass
except:
exc = False
try:
exit_val = exit(mgr, *sys.exc_info())
except ValueError as err:
print('__exit__ raised:', err)
else:
if not exit_val:
raise
except ValueError as err:
print('BLOCK raised:', err)
finally:
if exc:
try:
exit(mgr, None, None, None)
except ValueError as err:
print('__exit__ raised:', err)
The need for such special exception handling should be quite rare and normally wrapping the whole with
in a try ... except
block will be sufficient. Especially if the various error sources are indicated by different (custom) exception types (the context managers need to be designed accordingly) we can readily distinguish between them. For example:
try:
with ContextManager():
BLOCK
except InitError: # raised from __init__
...
except AcquireResourceError: # raised from __enter__
...
except ValueError: # raised from BLOCK
...
except ReleaseResourceError: # raised from __exit__
...
What you really want here is:
<col align="right"/>
but it looks like Gecko doesn't support this yet: it's been an open bug for over a decade.
(Geez, why can't Firefox have decent standards support like IE6?)
Short and simple: Because the elements you are looking for do not exist in the document (yet).
For the remainder of this answer I will use getElementById
as example, but the same applies to getElementsByTagName
, querySelector
and any other DOM method that selects elements.
Possible Reasons
There are two reasons why an element might not exist:
An element with the passed ID really does not exist in the document. You should double check that the ID you pass to getElementById
really matches an ID of an existing element in the (generated) HTML and that you have not misspelled the ID (IDs are case-sensitive!).
Incidentally, in the majority of contemporary browsers, which implement querySelector()
and querySelectorAll()
methods, CSS-style notation is used to retrieve an element by its id
, for example: document.querySelector('#elementID')
, as opposed to the method by which an element is retrieved by its id
under document.getElementById('elementID')
; in the first the #
character is essential, in the second it would lead to the element not being retrieved.
The element does not exist at the moment you call getElementById
.
The latter case is quite common. Browsers parse and process the HTML from top to bottom. That means that any call to a DOM element which occurs before that DOM element appears in the HTML, will fail.
Consider the following example:
<script>
var element = document.getElementById('my_element');
</script>
<div id="my_element"></div>
The div
appears after the script
. At the moment the script is executed, the element does not exist yet and getElementById
will return null
.
jQuery
The same applies to all selectors with jQuery. jQuery won't find elements if you misspelled your selector or you are trying to select them before they actually exist.
An added twist is when jQuery is not found because you have loaded the script without protocol and are running from file system:
<script src="//somecdn.somewhere.com/jquery.min.js"></script>
this syntax is used to allow the script to load via HTTPS on a page with protocol https:// and to load the HTTP version on a page with protocol http://
It has the unfortunate side effect of attempting and failing to load file://somecdn.somewhere.com...
Solutions
Before you make a call to getElementById
(or any DOM method for that matter), make sure the elements you want to access exist, i.e. the DOM is loaded.
This can be ensured by simply putting your JavaScript after the corresponding DOM element
<div id="my_element"></div>
<script>
var element = document.getElementById('my_element');
</script>
in which case you can also put the code just before the closing body tag (</body>
) (all DOM elements will be available at the time the script is executed).
Other solutions include listening to the load
[MDN] or DOMContentLoaded
[MDN] events. In these cases it does not matter where in the document you place the JavaScript code, you just have to remember to put all DOM processing code in the event handlers.
Example:
window.onload = function() {
// process DOM elements here
};
// or
// does not work IE 8 and below
document.addEventListener('DOMContentLoaded', function() {
// process DOM elements here
});
Please see the articles at quirksmode.org for more information regarding event handling and browser differences.
jQuery
First make sure that jQuery is loaded properly. Use the browser's developer tools to find out whether the jQuery file was found and correct the URL if it wasn't (e.g. add the http:
or https:
scheme at the beginning, adjust the path, etc.)
Listening to the load
/DOMContentLoaded
events is exactly what jQuery is doing with .ready()
[docs]. All your jQuery code that affects DOM element should be inside that event handler.
In fact, the jQuery tutorial explicitly states:
As almost everything we do when using jQuery reads or manipulates the document object model (DOM), we need to make sure that we start adding events etc. as soon as the DOM is ready.
To do this, we register a ready event for the document.
$(document).ready(function() { // do stuff when DOM is ready });
Alternatively you can also use the shorthand syntax:
$(function() {
// do stuff when DOM is ready
});
Both are equivalent.
This answer shows usage of LINQ (Aggregate
) as requested in the question and is not intended for everyday use. Because this does not use a StringBuilder
it will have horrible performance for very long sequences. For regular code use String.Join
as shown in the other answer
Use aggregate queries like this:
string[] words = { "one", "two", "three" };
var res = words.Aggregate(
"", // start with empty string to handle empty list case.
(current, next) => current + ", " + next);
Console.WriteLine(res);
This outputs:
, one, two, three
An aggregate is a function that takes a collection of values and returns a scalar value. Examples from T-SQL include min, max, and sum. Both VB and C# have support for aggregates. Both VB and C# support aggregates as extension methods. Using the dot-notation, one simply calls a method on an IEnumerable object.
Remember that aggregate queries are executed immediately.
More information - MSDN: Aggregate Queries
If you really want to use Aggregate
use variant using StringBuilder
proposed in comment by CodeMonkeyKing which would be about the same code as regular String.Join
including good performance for large number of objects:
var res = words.Aggregate(
new StringBuilder(),
(current, next) => current.Append(current.Length == 0? "" : ", ").Append(next))
.ToString();
If you use ThreadPoolExecutor
, and you use submit() method, it will give you a Future
back. You can call cancel() on the returned Future to stop your Runnable
task.
function sendemail(Array $id,$userid){ // forces $id must be an array
Some Process....
}
$ids = array(121,122,123);
sendmail($ids, $userId);
Bootstrap has it's own centering class named text-center.
<div class="span7 text-center"></div>
Simple to understand. In Below code, maxKey is the key which is holding the max value.
int maxKey = 0;
int maxValue = 0;
for(int i : birds.keySet())
{
if(birds.get(i) > maxValue)
{
maxKey = i;
maxValue = birds.get(i);
}
}
It may help:
import csv
with open('csv_file','r') as f:
# Printing Specific Part of CSV_file
# Printing last line of second column
lines = list(csv.reader(f, delimiter = ' ', skipinitialspace = True))
print(lines[-1][1])
# For printing a range of rows except 10 last rows of second column
for i in range(len(lines)-10):
print(lines[i][1])
Use the scrollTop
property of the frame's content to set the content's vertical scroll-offset to a specific number of pixels (like 100):
<iframe src="foo.html" onload="this.contentWindow.document.documentElement.scrollTop=100"></iframe>
I would suggest the P: drive is not mapped for the account that sql server has started as.
You need to set for Hibernate5.x <property name="hibernate.id.new_generator_mappings">false</property>
.. see and link.
For older version of hibernate 4.x:
<prop key="hibernate.id.new_generator_mappings">false</prop>
I used mkdir -p /root/.android && touch /root/.android/repositories.cfg to make it works
This function will return the results of a query as an array of powershell objects so you can use them in filters and access columns easily:
function sql($sqlText, $database = "master", $server = ".")
{
$connection = new-object System.Data.SqlClient.SQLConnection("Data Source=$server;Integrated Security=SSPI;Initial Catalog=$database");
$cmd = new-object System.Data.SqlClient.SqlCommand($sqlText, $connection);
$connection.Open();
$reader = $cmd.ExecuteReader()
$results = @()
while ($reader.Read())
{
$row = @{}
for ($i = 0; $i -lt $reader.FieldCount; $i++)
{
$row[$reader.GetName($i)] = $reader.GetValue($i)
}
$results += new-object psobject -property $row
}
$connection.Close();
$results
}
To clarify, the above example does work, my code in the example did not work for unrelated reasons.
If myvar is false, null or has never been used before (i.e. $scope.myvar or $rootScope.myvar never called), the div will not show. Once any value has been assigned to it, the div will show, except if the value is specifically false.
The following will cause the div to show:
$scope.myvar = "Hello World";
or
$scope.myvar = true;
The following will hide the div:
$scope.myvar = null;
or
$scope.myvar = false;
Use this as a method with x being any number initially. The string y being passed in by console and v is the array to search!
public static int getIndex(int x, String y, String[]v){
for(int m = 0; m < v.length; m++){
if (v[m].equalsIgnoreCase(y)){
x = m;
}
}
return x;
}
In addition to @enyo's answer in checking for files that are still uploading or in the queue, I also created a new function in dropzone.js to check for any files in an ERROR state (ie bad file type, size, etc).
Dropzone.prototype.getErroredFiles = function () {
var file, _i, _len, _ref, _results;
_ref = this.files;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
file = _ref[_i];
if (file.status === Dropzone.ERROR) {
_results.push(file);
}
}
return _results;
};
And thus, the check would become:
if (this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0 && this.getErroredFiles().length === 0) {
doSomething();
}
If you are at a certain branch mybranch
, just go ahead and git checkout commit_hash
. Then you can return to your branch by git checkout mybranch
. I had the same game bisecting a bug today :) Also, you should know about git bisect.
If you're just looking for a single character, this would work:
string = "dooobiedoobiedoobie"
match = 'o'
reduce(lambda count, char: count + 1 if char == match else count, string, 0)
# produces 7
Also,
string = "test test test test"
match = "test"
len(string.split(match)) - 1
# produces 4
My hunch is that neither of these (especially #2) is terribly performant.
To enable deserialization of multiple implementations of interfaces, you can use JsonConverter, but not through an attribute:
Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
serializer.Converters.Add(new DTOJsonConverter());
Interfaces.IEntity entity = serializer.Deserialize(jsonReader);
DTOJsonConverter maps each interface with a concrete implementation:
class DTOJsonConverter : Newtonsoft.Json.JsonConverter
{
private static readonly string ISCALAR_FULLNAME = typeof(Interfaces.IScalar).FullName;
private static readonly string IENTITY_FULLNAME = typeof(Interfaces.IEntity).FullName;
public override bool CanConvert(Type objectType)
{
if (objectType.FullName == ISCALAR_FULLNAME
|| objectType.FullName == IENTITY_FULLNAME)
{
return true;
}
return false;
}
public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
{
if (objectType.FullName == ISCALAR_FULLNAME)
return serializer.Deserialize(reader, typeof(DTO.ClientScalar));
else if (objectType.FullName == IENTITY_FULLNAME)
return serializer.Deserialize(reader, typeof(DTO.ClientEntity));
throw new NotSupportedException(string.Format("Type {0} unexpected.", objectType));
}
public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
{
serializer.Serialize(writer, value);
}
}
DTOJsonConverter is required only for the deserializer. The serialization process is unchanged. The Json object do not need to embed concrete types names.
This SO post offers the same solution one step further with a generic JsonConverter.
As of today (November 2019), Microsoft's TypeScript plugin does what the OP required: https://packagecontrol.io/packages/TypeScript.
Else this will helps you
The ADB is now located in the Android SDK platform-tools.
Check your [sdk directory]/platform-tools directory and if it does not exist, then open the SDK manager in the Android Studio (a button somewhere in the top menu, android logo with a down arrow), switch to SDK tools tab and and select/install the Android SDK Platform-tools.
Alternatively, you can try the standalone SDK Manager: Open the SDK manager and you should see a "Launch Standalone SDK manager" link somewhere at the bottom of the settings window. Click and open the standalone SDK manager, then install/update the
"Tools > Android SDK platform tools". If the above does not solve the problem, try reinstalling the tools: open the "Standalone SDK manager" and uninstall the Android SDK platform-tools, delete the [your sdk directory]/platform-tools directory completely and install it again using the SDK manager.
Hope this helps!
For varchars, you may need to do something like this:
select convert(varchar(25), NULL) as abc_column into xyz_table
If you try
select '' as abc_column into xyz_table
you may get errors related to truncation, or an issue with null values, once you populate.
The command free
is nice. Takes a short while to understand the "+/- buffers/cache", but the idea is that cache and buffers doesn't really count when evaluating "free", as it can be dumped right away. Therefore, to see how much free (and used) memory you have, you need to remove the cache/buffer usage - which is conveniently done for you.
Consider the case statement as well which is compatible with most sh-based shells:
case $str in
/*)
echo 1
;;
*)
echo 0
;;
esac
It depends whether you ListBox object of the System.Windows.Forms.ListBox
class, which does have the ListBox.IndexFromPoint()
method. But if the ListBox object is from the System.Windows.Control.Listbox
class, the answer from @dark-knight (marked as correct answer) does not work.
Im running Win 10 (1903) and current versions of the .NET framework (4.8). This issue should not be version dependant though, only whether your Application is using WPF or Windows Form for the UI. See also: WPF vs Windows Form
You could try if using opendir()
and readdir()
in Perl
is faster. For an example of those function, look here.
Here's a method I wrote to check if an URL exists or not. I had a requirement to add a request header. It's Groovy but should be fairly simple to adapt to Java. Essentially I'm using the org.springframework.web.client.RestTemplate#execute(java.lang.String, org.springframework.http.HttpMethod, org.springframework.web.client.RequestCallback, org.springframework.web.client.ResponseExtractor<T>, java.lang.Object...)
API method. I guess the solution you arrive at depends at least in part on the HTTP method you want to execute. The key take away from example below is that I'm passing a Groovy closure (The third parameter to method restTemplate.execute()
, which is more or less, loosely speaking a Lambda in Java world) that is executed by the Spring API as a callback to be able to manipulate the request object before Spring executes the command,
boolean isUrlExists(String url) {
try {
return (restTemplate.execute(url, HttpMethod.HEAD,
{ ClientHttpRequest request -> request.headers.add('header-name', 'header-value') },
{ ClientHttpResponse response -> response.headers }) as HttpHeaders)?.get('some-response-header-name')?.contains('some-response-header-value')
} catch (Exception e) {
log.warn("Problem checking if $url exists", e)
}
false
}
use DataTable object instead:
private void doMore(DataTable dt)
{
foreach(DataColumn dc in dt.Columns)
{
MessageBox.Show(dc.ColumnName);
}
}
All of these schemes, except AES and Blowfish, have known vulnerabilities and should not be used.
However, Blowfish has been replaced by Twofish.
SHA and AES serve different purposes. SHA is used to generate a hash of data and AES is used to encrypt data.
Here's an example of when an SHA hash is useful to you. Say you wanted to download a DVD ISO image of some Linux distro. This is a large file and sometimes things go wrong - so you want to validate that what you downloaded is correct. What you would do is go to a trusted source (such as the offical distro download point) and they typically have the SHA hash for the ISO image available. You can now generated the comparable SHA hash (using any number of open tools) for your downloaded data. You can now compare the two hashs to make sure they match - which would validate that the image you downloaded is correct. This is especially important if you get the ISO image from an untrusted source (such as a torrent) or if you are having trouble using the ISO and want to check if the image is corrupted.
As you can see in this case the SHA has was used to validate data that was not corrupted. You have every right to see the data in the ISO.
AES, on the other hand, is used to encrypt data, or prevent people from viewing that data with knowing some secret.
AES uses a shared key which means that the same key (or a related key) is used to encrypted the data as is used to decrypt the data. For example if I encrypted an email using AES and I sent that email to you then you and I would both need to know the shared key used to encrypt and decrypt the email. This is different than algorithms that use a public key such PGP or SSL.
If you wanted to put them together you could encrypt a message using AES and then send along an SHA1 hash of the unencrypted message so that when the message was decrypted they were able to validate the data. This is a somewhat contrived example.
If you want to know more about these some Wikipedia search terms (beyond AES and SHA) you want want to try include:
Symmetric-key algorithm (for AES) Cryptographic hash function (for SHA) Public-key cryptography (for PGP and SSL)
If your database recovery model is full and you didn't have a log backup maintenance plan, you will get this error because the transaction log becomes full due to LOG_BACKUP
.
This will prevent any action on this database (e.g. shrink), and the SQL Server Database Engine will raise a 9002 error.
To overcome this behavior I advise you to check this The transaction log for database ‘SharePoint_Config’ is full due to LOG_BACKUP that shows detailed steps to solve the issue.
For future reference Python is strongly typed. Unlike other dynamic languages, it will not automagically cast objects from one type or the other (say from str
to int
) so you must do this yourself. You'll like that in the long-run, trust me!
Update: Leaving this answer for historical reasons, but I don't recommend it. Please see the accepted answer above.
Tell Jackson to map using your custom [de]serialization classes:
@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
private LocalDateTime ignoreUntil;
provide custom classes:
public class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
@Override
public void serialize(LocalDateTime arg0, JsonGenerator arg1, SerializerProvider arg2) throws IOException {
arg1.writeString(arg0.toString());
}
}
public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
@Override
public LocalDateTime deserialize(JsonParser arg0, DeserializationContext arg1) throws IOException {
return LocalDateTime.parse(arg0.getText());
}
}
random fact: if i nest above classes and don't make them static, the error message is weird:
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json;charset=UTF-8' not supported
The easiest way is to redirect the output of the echo
by >>
:
echo 'VNCSERVERS="1:root"' >> /etc/sysconfig/configfile
echo 'VNCSERVERARGS[1]="-geometry 1600x1200"' >> /etc/sysconfig/configfile
The only reason that I know of why a formula wouldn't be available to summarize on is if it didn't reference any database fields or whose value wasn't dynamic throughout sections of the report. For example, if you have a formula that returns a constant it won't be available. Or if it only references a field that is set throughout the report and returns a value based on that field, like "if {parameter}=1 then 1" would not be available either.
In general, the formula's value should not be static through the sections of the report you're summarizing over (Though the way Crystal determines this is beyond me and this doesn't seem to be a hard and fast rule)
EDIT: One other reason why a formula wouldn't be available is if you're already using a summary function in that formula. Only one level of summaries at a time!
You can't selectively escape %
, as %
always has a special meaning depending on the following character.
In the documentation of Python, at the bottem of the second table in that section, it states:
'%' No argument is converted, results in a '%' character in the result.
Therefore you should use:
selectiveEscape = "Print percent %% in sentence and not %s" % (test, )
(please note the expicit change to tuple as argument to %
)
Without knowing about the above, I would have done:
selectiveEscape = "Print percent %s in sentence and not %s" % ('%', test)
with the knowledge you obviously already had.
Here is one neat way with easy to understand algorithm.
import copy
nums = [2,3,4,5]
subsets = [[]]
for n in nums:
prev = copy.deepcopy(subsets)
[k.append(n) for k in subsets]
subsets.extend(prev)
print(subsets)
print(len(subsets))
# [[2, 3, 4, 5], [3, 4, 5], [2, 4, 5], [4, 5], [2, 3, 5], [3, 5], [2, 5], [5],
# [2, 3, 4], [3, 4], [2, 4], [4], [2, 3], [3], [2], []]
# 16 (2^len(nums))
For this html:
<div class="outer">
<div class="inner"></div>
</div>
This selector should work:
$('.outer > .inner')
module.exports = { ClientIDUnsplash : 'SuperSecretKey' };
var { ClientIDUnsplash } = require('./FileOne');
This example works best for React.
Solution that works with both positional and keyword arguments independently of order in which keyword args were passed (using inspect.getargspec):
import inspect
import functools
def memoize(fn):
cache = fn.cache = {}
@functools.wraps(fn)
def memoizer(*args, **kwargs):
kwargs.update(dict(zip(inspect.getargspec(fn).args, args)))
key = tuple(kwargs.get(k, None) for k in inspect.getargspec(fn).args)
if key not in cache:
cache[key] = fn(**kwargs)
return cache[key]
return memoizer
Similar question: Identifying equivalent varargs function calls for memoization in Python
SELECT * FROM all_tab_modifications;
Have a look at ImmutableMap JavaDoc: doc
There is information about that there:
Unlike Collections.unmodifiableMap(java.util.Map), which is a view of a separate map which can still change, an instance of ImmutableMap contains its own data and will never change. ImmutableMap is convenient for public static final maps ("constant maps") and also lets you easily make a "defensive copy" of a map provided to your class by a caller.
You could also try this
Private Sub CommandButton1_Click()
Sheets("Sheet1").Range("A3:E3").Copy
Dim lastrow As Long
lastrow = Range("A65536").End(xlUp).Row
Sheets("Summary Info").Activate
Cells(lastrow + 1, 1).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
End Sub
The easy way is by using sprintf
. I know others have suggested itoa
, but a) it isn't part of the standard library, and b) sprintf
gives you formatting options that itoa
doesn't.
Java implementation without recursion
public Set<String> permutate(String s){
Queue<String> permutations = new LinkedList<String>();
Set<String> v = new HashSet<String>();
permutations.add(s);
while(permutations.size()!=0){
String str = permutations.poll();
if(!v.contains(str)){
v.add(str);
for(int i = 0;i<str.length();i++){
String c = String.valueOf(str.charAt(i));
permutations.add(str.substring(i+1) + c + str.substring(0,i));
}
}
}
return v;
}
As to me, you can first(find version.hpp the version variable is in it, if you know where it is(in ubuntu it usually in /usr/include/boost/version.hpp
by default install)):
locate `boost/version.hpp`
Second show it's version by:
grep BOOST_LIB_VERSION /usr/include/boost/version.hpp
or
grep BOOST_VERSION /usr/include/boost/version.hpp.
As to me, I have two version boost installed in my system. Output as below:
xy@xy:~$ locate boost/version.hpp |grep boost
/home/xy/boost_install/boost_1_61_0/boost/version.hpp
/home/xy/boost_install/lib/include/boost/version.hpp
/usr/include/boost/version.hpp
xy@xy:~$ grep BOOST_VERSION /usr/include/boost/version.hpp
#ifndef BOOST_VERSION_HPP
#define BOOST_VERSION_HPP
// BOOST_VERSION % 100 is the patch level
// BOOST_VERSION / 100 % 1000 is the minor version
// BOOST_VERSION / 100000 is the major version
#define BOOST_VERSION 105800
// BOOST_LIB_VERSION must be defined to be the same as BOOST_VERSION
# or this way more readable
xy@xy:~$ grep BOOST_LIB_VERSION /usr/include/boost/version.hpp
// BOOST_LIB_VERSION must be defined to be the same as BOOST_VERSION
#define BOOST_LIB_VERSION "1_58"
Show local installed version:
xy@xy:~$ grep BOOST_LIB_VERSION /home/xy/boost_install/lib/include/boost/version.hpp
// BOOST_LIB_VERSION must be defined to be the same as BOOST_VERSION
#define BOOST_LIB_VERSION "1_61"
Google guides me here but it didn't fix mine, this is a very general question and there are various causes, so I post my problem and solution here for reference in case anyone might read this later.
Another possible cause of 500 error is syntax error in header(...)
function, like this one:
header($_SERVER['SERVER_PROTOCOL'] . '200 OK');
Be aware there should be space between server protocol and status code, so it should be:
header($_SERVER['SERVER_PROTOCOL'] . ' 200 OK');
So I suggest check your http header call if you have it in your code.
if you want to encode or decode an array from or to JSON you can use these functions
$myJSONString = json_encode($myArray);
$myArray = json_decode($myString);
json_encode will result in a JSON string, built from an (multi-dimensional) array. json_decode will result in an Array, built from a well formed JSON string
with json_decode you can take the results from the API and only output what you want, for example:
echo $myArray['payload']['ign'];
I was porting one application from Visual C to gcc over Linux and I had the same problem with
malloc.c:3096: sYSMALLOc: Assertion using gcc on UBUNTU 11.
I moved the same code to a Suse distribution (on other computer ) and I don't have any problem.
I suspect that the problems are not in our programs but in the own libc.
I got this error generating a data frame consisting of timestamps and data:
df = pd.DataFrame({'data':value}, index=pd.DatetimeIndex(timestamp))
Adding the suggested solution works for me:
df = pd.DataFrame({'data':value}, index=pd.DatetimeIndex(timestamp), dtype=float))
Thanks Chang She!
Example:
data
2005-01-01 00:10:00 7.53
2005-01-01 00:20:00 7.54
2005-01-01 00:30:00 7.62
2005-01-01 00:40:00 7.68
2005-01-01 00:50:00 7.81
2005-01-01 01:00:00 7.95
2005-01-01 01:10:00 7.96
2005-01-01 01:20:00 7.95
2005-01-01 01:30:00 7.98
2005-01-01 01:40:00 8.06
2005-01-01 01:50:00 8.04
2005-01-01 02:00:00 8.06
2005-01-01 02:10:00 8.12
2005-01-01 02:20:00 8.12
2005-01-01 02:30:00 8.25
2005-01-01 02:40:00 8.27
2005-01-01 02:50:00 8.17
2005-01-01 03:00:00 8.21
2005-01-01 03:10:00 8.29
2005-01-01 03:20:00 8.31
2005-01-01 03:30:00 8.25
2005-01-01 03:40:00 8.19
2005-01-01 03:50:00 8.17
2005-01-01 04:00:00 8.18
data
2005-01-01 00:00:00 7.636000
2005-01-01 01:00:00 7.990000
2005-01-01 02:00:00 8.165000
2005-01-01 03:00:00 8.236667
2005-01-01 04:00:00 8.180000
extract($_POST);
$error=array();
$extension=array("jpeg","jpg","png","gif");
foreach($_FILES["files"]["tmp_name"] as $key=>$tmp_name) {
$file_name=$_FILES["files"]["name"][$key];
$file_tmp=$_FILES["files"]["tmp_name"][$key];
$ext=pathinfo($file_name,PATHINFO_EXTENSION);
if(in_array($ext,$extension)) {
if(!file_exists("photo_gallery/".$txtGalleryName."/".$file_name)) {
move_uploaded_file($file_tmp=$_FILES["files"]["tmp_name"][$key],"photo_gallery/".$txtGalleryName."/".$file_name);
}
else {
$filename=basename($file_name,$ext);
$newFileName=$filename.time().".".$ext;
move_uploaded_file($file_tmp=$_FILES["files"]["tmp_name"][$key],"photo_gallery/".$txtGalleryName."/".$newFileName);
}
}
else {
array_push($error,"$file_name, ");
}
}
and you must check your HTML code
<form action="create_photo_gallery.php" method="post" enctype="multipart/form-data">
<table width="100%">
<tr>
<td>Select Photo (one or multiple):</td>
<td><input type="file" name="files[]" multiple/></td>
</tr>
<tr>
<td colspan="2" align="center">Note: Supported image format: .jpeg, .jpg, .png, .gif</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Create Gallery" id="selectedButton"/></td>
</tr>
</table>
</form>
#include<iostream>
#include<ctime>
int main()
{
std::time_t t = std::time(0); // t is an integer type
std::cout << t << " seconds since 01-Jan-1970\n";
return 0;
}
Use method=POST then it will pass key&value.