You can use gcc/clang's unused attribute, however I use these macros in a header to avoid having gcc specific attributes all over the source, also having __attribute__
everywhere is a bit verbose/ugly.
#ifdef __GNUC__
# define UNUSED(x) UNUSED_ ## x __attribute__((__unused__))
#else
# define UNUSED(x) UNUSED_ ## x
#endif
#ifdef __GNUC__
# define UNUSED_FUNCTION(x) __attribute__((__unused__)) UNUSED_ ## x
#else
# define UNUSED_FUNCTION(x) UNUSED_ ## x
#endif
Then you can do...
void foo(int UNUSED(bar)) { ... }
I prefer this because you get an error if you try use bar
in the code anywhere so you can't leave the attribute in by mistake.
and for functions...
static void UNUSED_FUNCTION(foo)(int bar) { ... }
Note 1):
As far as I know, MSVC doesn't have an equivalent to __attribute__((__unused__))
.
Note 2):
The UNUSED
macro won't work for arguments which contain parenthesis,
so if you have an argument like float (*coords)[3]
you can't do,float UNUSED((*coords)[3])
or float (*UNUSED(coords))[3]
, This is the only downside to the UNUSED
macro I found so far, in these cases I fall back to (void)coords;
Export should be specific about which version of GCC/G++ to use, because if user had multiple compiler version, it would not compile successfully.
export CC=path_of_gcc/gcc-version
export CXX=path_of_g++/g++-version
cmake path_of_project_contain_CMakeList.txt
make
In case project use C++11 this can be handled by using -std=C++-11
flag in CMakeList.txt
CXXFLAGS = -O3 -o prog -rdynamic -D_GNU_SOURCE -L./libmine
LIBS = libmine.a -lpthread
Using an UNREFERENCED_PARAMETER(p)
could work. I know it is defined in WinNT.h for Windows systems and can easily be defined for gcc as well (if it doesn't already have it).
UNREFERENCED PARAMETER(p)
is defined as
#define UNREFERENCED_PARAMETER(P) (P)
in WinNT.h.
Arrays can't be passed as function parameters by value in C.
You can put the array in a struct:
typedef struct type24 {
char byte[3];
} type24;
and then pass that by value, but of course then it's less convenient to use: x.byte[0]
instead of x[0]
.
Your function type24_to_int32(char value[3])
actually passes by pointer, not by value. It's exactly equivalent to type24_to_int32(char *value)
, and the 3
is ignored.
If you're happy passing by pointer, you could stick with the array and do:
type24_to_int32(const type24 *value);
This will pass a pointer-to-array, not pointer-to-first-element, so you use it as:
(*value)[0]
I'm not sure that's really a gain, since if you accidentally write value[1]
then something stupid happens.
Turning off optimization fixes the problem, but it is unnecessary. A safer alternative is to make it illegal for the compiler to optimize out the store by using the volatile
type qualifier.
// Assuming pageptr is unsigned char * already...
unsigned char *pageptr = ...;
((unsigned char volatile *)pageptr)[0] = pageptr[0];
The volatile
type qualifier instructs the compiler to be strict about memory stores and loads. One purpose of volatile
is to let the compiler know that the memory access has side effects, and therefore must be preserved. In this case, the store has the side effect of causing a page fault, and you want the compiler to preserve the page fault.
This way, the surrounding code can still be optimized, and your code is portable to other compilers which don't understand GCC's #pragma
or __attribute__
syntax.
Found the answer. What I did was was first
sudo apt-get install aptitude
sudo aptitude install libglib2.0-0
sudo aptitude install gcc-4.7 make linux-headers-`uname -r` -y
and tried it but it didn't work so I continued and did
sudo apt-get install build-essential
sudo apt-get install gcc-4.7 linux-headers-`uname -r`
after doing these two steps and trying again, it worked.
In my case there was a static variable which was not initialized. When I initialized it, the error was removed. I don't know the logic behind it but worked for me. I know its a little late but other people with similar problem might get some help.
LIBRARY_PATH
is used by gcc before compilation to search directories containing static and shared libraries that need to be linked to your program.
LD_LIBRARY_PATH
is used by your program to search directories containing shared libraries after it has been successfully compiled and linked.
EDIT:
As pointed below, your libraries can be static or shared. If it is static then the code is copied over into your program and you don't need to search for the library after your program is compiled and linked. If your library is shared then it needs to be dynamically linked to your program and that's when LD_LIBRARY_PATH
comes into play.
In this case the user has done mistake in definition and its usage.
If someone has done a typedef
to a structure the same should be used without using struct
following is the example.
typedef struct
{
int a;
}studyT;
When using in a function
int main()
{
struct studyT study; // This will give above error.
studyT stud; // This will eliminate the above error.
return 0;
}
finally solved my problem.
I created a new project in XCode with the sources and changed the C++ Standard Library from the default libc++ to libstdc++ as in this and this.
The gcc option -O
enables different levels of optimization. Use -O0
to disable them and use -S
to output assembly. -O3
is the highest level of optimization.
Starting with gcc 4.8 the optimization level -Og
is available. It enables optimizations that do not interfere with debugging and is the recommended default for the standard edit-compile-debug cycle.
To change the dialect of the assembly to either intel or att use -masm=intel
or -masm=att
.
You can also enable certain optimizations manually with -fname
.
Have a look at the gcc manual for much more.
With CMake, it's generally recommended to do an "out of source" build. Create your CMakeLists.txt
in the root of your project. Then from the root of your project:
mkdir Release
cd Release
cmake -DCMAKE_BUILD_TYPE=Release ..
make
And for Debug
(again from the root of your project):
mkdir Debug
cd Debug
cmake -DCMAKE_BUILD_TYPE=Debug ..
make
Release
/ Debug
will add the appropriate flags for your compiler. There are also RelWithDebInfo
and MinSizeRel
build configurations.
You can modify/add to the flags by specifying a toolchain file in which you can add CMAKE_<LANG>_FLAGS_<CONFIG>_INIT
variables, e.g.:
set(CMAKE_CXX_FLAGS_DEBUG_INIT "-Wall")
set(CMAKE_CXX_FLAGS_RELEASE_INIT "-Wall")
See CMAKE_BUILD_TYPE for more details.
As for your third question, I'm not sure what you are asking exactly. CMake should automatically detect and use the compiler appropriate for your different source files.
Mac version: $ ld -v 2, don't know how to get detailed paths. output
Library search paths:
/usr/lib
/usr/local/lib
Framework search paths:
/Library/Frameworks/
/System/Library/Frameworks/
Add foo1.c , foo2.c , foo3.c and makefile in one folder the type make in bash
if you do not want to use the makefile, you can run the command
gcc -c foo1.c foo2.c foo3.c
then
gcc -o output foo1.o foo2.o foo3.o
foo1.c
#include <stdio.h>
#include <string.h>
void funk1();
void funk1() {
printf ("\nfunk1\n");
}
int main(void) {
char *arg2;
size_t nbytes = 100;
while ( 1 ) {
printf ("\nargv2 = %s\n" , arg2);
printf ("\n:> ");
getline (&arg2 , &nbytes , stdin);
if( strcmp (arg2 , "1\n") == 0 ) {
funk1 ();
} else if( strcmp (arg2 , "2\n") == 0 ) {
funk2 ();
} else if( strcmp (arg2 , "3\n") == 0 ) {
funk3 ();
} else if( strcmp (arg2 , "4\n") == 0 ) {
funk4 ();
} else {
funk5 ();
}
}
}
foo2.c
#include <stdio.h>
void funk2(){
printf("\nfunk2\n");
}
void funk3(){
printf("\nfunk3\n");
}
foo3.c
#include <stdio.h>
void funk4(){
printf("\nfunk4\n");
}
void funk5(){
printf("\nfunk5\n");
}
makefile
outputTest: foo1.o foo2.o foo3.o
gcc -o output foo1.o foo2.o foo3.o
make removeO
outputTest.o: foo1.c foo2.c foo3.c
gcc -c foo1.c foo2.c foo3.c
clean:
rm -f *.o output
removeO:
rm -f *.o
Just to summarize, here are some commands that navigate to a directory and compile code using Cygwin and Windows Vista:
At the prompt, use cd
to change to the appropriate directory:
$ cd /cygdrive/c/Users/nate/Desktop
Use ls
to list the files in the directory:
$ ls
prog.c
Use the gcc
command to compile a file in this directory:
$ gcc prog.c -o prog
If you don't see any errors, you should be able to run the resulting program:
$ ./prog
Update:
For the "Cygwin1.dll not found
" error, I like Nik's answer. You might also check out this related post about cygwin1.dll not found, which suggests adding c:\cygwin\bin\
to your Windows PATH.
There are instructions on how to change the Windows PATH variable for Windows XP, and on Vista I think it's similar.
c:\cygwin\bin
to the list, making sure to separate it from any previous items with a semicolonI have had this issue in a case where the static
function was called before it was declared. Moving the function declaration to anywhere above the call solved my problem.
It means you asked it to include the library 'libz.a' or 'libz.so' containing a compression package, and although the compiler found some files, none of them was suitable for the build you are using.
You either need to change your build parameters or you need to get the correct library installed or you need to specify where the correct library is on the link command line with a -L/where/it/is/lib
type option.
The warning from your compiler is telling you that your format specifier doesn't match the data type you're passing to it.
Try using %lx
or %llx
. For more portability, include inttypes.h
and use the PRIx64
macro.
For example: printf("val = 0x%" PRIx64 "\n", val);
(note that it's string concatenation)
Minimal example that generates the error
main.S
moves an address into %eax
(32-bit).
main.S
_start:
mov $_start, %eax
linker.ld
SECTIONS
{
/* This says where `.text` will go in the executable. */
. = 0x100000000;
.text :
{
*(*)
}
}
Compile on x86-64:
as -o main.o main.S
ld -o main.out -T linker.ld main.o
Outcome of ld
:
(.text+0x1): relocation truncated to fit: R_X86_64_32 against `.text'
Keep in mind that:
as
puts everything on the .text
if no other section is specifiedld
uses the .text
as the default entry point if ENTRY
. Thus _start
is the very first byte of .text
.How to fix it: use this linker.ld
instead, and subtract 1 from the start:
SECTIONS
{
. = 0xFFFFFFFF;
.text :
{
*(*)
}
}
Notes:
we cannot make _start
global in this example with .global _start
, otherwise it still fails. I think this happens because global symbols have alignment constraints (0xFFFFFFF0
works). TODO where is that documented in the ELF standard?
the .text
segment also has an alignment constraint of p_align == 2M
. But our linker is smart enough to place the segment at 0xFFE00000
, fill with zeros until 0xFFFFFFFF
and set e_entry == 0xFFFFFFFF
. This works, but generates an oversized executable.
Tested on Ubuntu 14.04 AMD64, Binutils 2.24.
Explanation
First you must understand what relocation is with a minimal example: https://stackoverflow.com/a/30507725/895245
Next, take a look at objdump -Sr main.o
:
0000000000000000 <_start>:
0: b8 00 00 00 00 mov $0x0,%eax
1: R_X86_64_32 .text
If we look into how instructions are encoded in the Intel manual, we see that:
b8
says that this is a mov
to %eax
0
is an immediate value to be moved to %eax
. Relocation will then modify it to contain the address of _start
.When moving to 32-bit registers, the immediate must also be 32-bit.
But here, the relocation has to modify those 32-bit to put the address of _start
into them after linking happens.
0x100000000
does not fit into 32-bit, but 0xFFFFFFFF
does. Thus the error.
This error can only happen on relocations that generate truncation, e.g. R_X86_64_32
(8 bytes to 4 bytes), but never on R_X86_64_64
.
And there are some types of relocation that require sign extension instead of zero extension as shown here, e.g. R_X86_64_32S
. See also: https://stackoverflow.com/a/33289761/895245
R_AARCH64_PREL32
I had multiple versions of the gcc compiler installed and needed to use a more recent version than the default installation. Since I am not a system administrator for our Linux systems, I cannot just change /usr/lib or many of the other suggestions above. I was encountering this problem and eventually tracked it down to setting my path to the 32-bit library directory instead of the 64-bit library (lib64) directory. Since the libraries in the 32-bit directory were incompatible, the system defaulted to the older version which was out of date.
Using -L to the path I was referencing gave warnings about "skipping incompatible libstdc++.so when searching for -lstdc++". This was the hint that helped me finally resolve the problem.
For any complex application, I suggest to use an lxc container. lxc containers are 'something in the middle between a chroot on steroids and a full fledged virtual machine'.
For example, here's a way to build 32-bit wine using lxc on an Ubuntu Trusty system:
sudo apt-get install lxc lxc-templates
sudo lxc-create -t ubuntu -n my32bitbox -- --bindhome $LOGNAME -a i386 --release trusty
sudo lxc-start -n my32bitbox
# login as yourself
sudo sh -c "sed s/deb/deb-src/ /etc/apt/sources.list >> /etc/apt/sources.list"
sudo apt-get install devscripts
sudo apt-get build-dep wine1.7
apt-get source wine1.7
cd wine1.7-*
debuild -eDEB_BUILD_OPTIONS="parallel=8" -i -us -uc -b
shutdown -h now # to exit the container
Here is the wiki page about how to build 32-bit wine on a 64-bit host using lxc.
Try adding a semi colon to the end of your structure:
struct sotrudnik {
string name;
string speciality;
string razread;
int zarplata;
} //Semi colon here
nasm -f bin -o 2_hello 2_hello.asm
(The following is a very artificial example cooked up to illustrate.) One major use of packed structs is where you have a stream of data (say 256 bytes) to which you wish to supply meaning. If I take a smaller example, suppose I have a program running on my Arduino which sends via serial a packet of 16 bytes which have the following meaning:
0: message type (1 byte)
1: target address, MSB
2: target address, LSB
3: data (chars)
...
F: checksum (1 byte)
Then I can declare something like
typedef struct {
uint8_t msgType;
uint16_t targetAddr; // may have to bswap
uint8_t data[12];
uint8_t checksum;
} __attribute__((packed)) myStruct;
and then I can refer to the targetAddr bytes via aStruct.targetAddr rather than fiddling with pointer arithmetic.
Now with alignment stuff happening, taking a void* pointer in memory to the received data and casting it to a myStruct* will not work unless the compiler treats the struct as packed (that is, it stores data in the order specified and uses exactly 16 bytes for this example). There are performance penalties for unaligned reads, so using packed structs for data your program is actively working with is not necessarily a good idea. But when your program is supplied with a list of bytes, packed structs make it easier to write programs which access the contents.
Otherwise you end up using C++ and writing a class with accessor methods and stuff that does pointer arithmetic behind the scenes. In short, packed structs are for dealing efficiently with packed data, and packed data may be what your program is given to work with. For the most part, you code should read values out of the structure, work with them, and write them back when done. All else should be done outside the packed structure. Part of the problem is the low level stuff that C tries to hide from the programmer, and the hoop jumping that is needed if such things really do matter to the programmer. (You almost need a different 'data layout' construct in the language so that you can say 'this thing is 48 bytes long, foo refers to the data 13 bytes in, and should be interpreted thus'; and a separate structured data construct, where you say 'I want a structure containing two ints, called alice and bob, and a float called carol, and I don't care how you implement it' -- in C both these use cases are shoehorned into the struct construct.)
The below packages are also helps you,
yum install gcc glibc glibc-common gd gd-devel -y
If you give the code a .c extension the compiler thinks it is C code, not C++. And the C++ compiler driver is called g++, if you use the gcc driver you will have linker problems, as the standard C++ libraries will not be linked by default. So you want:
g++ myprog.cpp
And do not even consider using an uppercase .C extension, unless you never want to port your code, and are prepared to be hated by those you work with.
Do you want to know if a type is the same type as int64_t or do you want to know if something is 64 bits? Based on your proposed solution, I think you're asking about the latter. In that case, I would do something like
template<typename T>
bool is_64bits() { return sizeof(T) * CHAR_BIT == 64; } // or >= 64
Here are some thoughts and ideas:
Use ROM more creatively.
Store anything you can in ROM. Instead of calculating things, store look-up tables in ROM. (Make sure your compiler is outputting your look-up tables to the read-only section! Print out memory addresses at runtime to check!) Store your interrupt vector table in ROM. Of course, run some tests to see how reliable your ROM is compared to your RAM.
Use your best RAM for the stack.
SEUs in the stack are probably the most likely source of crashes, because it is where things like index variables, status variables, return addresses, and pointers of various sorts typically live.
Implement timer-tick and watchdog timer routines.
You can run a "sanity check" routine every timer tick, as well as a watchdog routine to handle the system locking up. Your main code could also periodically increment a counter to indicate progress, and the sanity-check routine could ensure this has occurred.
Implement error-correcting-codes in software.
You can add redundancy to your data to be able to detect and/or correct errors. This will add processing time, potentially leaving the processor exposed to radiation for a longer time, thus increasing the chance of errors, so you must consider the trade-off.
Remember the caches.
Check the sizes of your CPU caches. Data that you have accessed or modified recently will probably be within a cache. I believe you can disable at least some of the caches (at a big performance cost); you should try this to see how susceptible the caches are to SEUs. If the caches are hardier than RAM then you could regularly read and re-write critical data to make sure it stays in cache and bring RAM back into line.
Use page-fault handlers cleverly.
If you mark a memory page as not-present, the CPU will issue a page fault when you try to access it. You can create a page-fault handler that does some checking before servicing the read request. (PC operating systems use this to transparently load pages that have been swapped to disk.)
Use assembly language for critical things (which could be everything).
With assembly language, you know what is in registers and what is in RAM; you know what special RAM tables the CPU is using, and you can design things in a roundabout way to keep your risk down.
Use objdump
to actually look at the generated assembly language, and work out how much code each of your routines takes up.
If you are using a big OS like Linux then you are asking for trouble; there is just so much complexity and so many things to go wrong.
Remember it is a game of probabilities.
A commenter said
Every routine you write to catch errors will be subject to failing itself from the same cause.
While this is true, the chances of errors in the (say) 100 bytes of code and data required for a check routine to function correctly is much smaller than the chance of errors elsewhere. If your ROM is pretty reliable and almost all the code/data is actually in ROM then your odds are even better.
Use redundant hardware.
Use 2 or more identical hardware setups with identical code. If the results differ, a reset should be triggered. With 3 or more devices you can use a "voting" system to try to identify which one has been compromised.
Apparently this is a known bug of Eclipse. This bug is resolved with the resolution of WONT-FIX. I have no idea why though. here is the link: Eclipse C Console Bug.
Tim Cas one liner is amazing for strings obtained by a call to fgets, because you know they contain a single newline at the end.
If you are in a different context and want to handle strings that may contain more than one newline, you might be looking for strrspn. It is not POSIX, meaning you will not find it on all Unices. I wrote one for my own needs.
/* Returns the length of the segment leading to the last
characters of s in accept. */
size_t strrspn (const char *s, const char *accept)
{
const char *ch;
size_t len = strlen(s);
more:
if (len > 0) {
for (ch = accept ; *ch != 0 ; ch++) {
if (s[len - 1] == *ch) {
len--;
goto more;
}
}
}
return len;
}
For those looking for a Perl chomp equivalent in C, I think this is it (chomp only removes the trailing newline).
line[strrspn(string, "\r\n")] = 0;
The strrcspn function:
/* Returns the length of the segment leading to the last
character of reject in s. */
size_t strrcspn (const char *s, const char *reject)
{
const char *ch;
size_t len = strlen(s);
size_t origlen = len;
while (len > 0) {
for (ch = reject ; *ch != 0 ; ch++) {
if (s[len - 1] == *ch) {
return len;
}
}
len--;
}
return origlen;
}
This is a function online, I created a header file with it, and I use Setcolor();
instead, I hope this helped! You can change the color by choosing any color in the range of 0-256. :) Sadly, I believe CodeBlocks has a later build of the window.h library...
#include <windows.h> //This is the header file for windows.
#include <stdio.h> //C standard library header file
void SetColor(int ForgC);
int main()
{
printf("Test color"); //Here the text color is white
SetColor(30); //Function call to change the text color
printf("Test color"); //Now the text color is green
return 0;
}
void SetColor(int ForgC)
{
WORD wColor;
//This handle is needed to get the current background attribute
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi;
//csbi is used for wAttributes word
if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
{
//To mask out all but the background attribute, and to add the color
wColor = (csbi.wAttributes & 0xF0) + (ForgC & 0x0F);
SetConsoleTextAttribute(hStdOut, wColor);
}
return;
}
LLVM is basically a library used to build compilers and/or language oriented software. The basic gist is although you have gcc which is probably the most common suite of compilers, it is not built to be re-usable ie. it is difficult to take components from gcc and use it to build your own application. LLVM addresses this issue well by building a set of "modular and reusable compiler and toolchain technologies" which anyone could use to build compilers and language oriented software.
Since it seems impossible to do just with symbol versioning hacks, let's go one step further and compile glibc ourselves.
This setup might work and is quick as it does not recompile the whole GCC toolchain, just glibc.
But it is not reliable as it uses host C runtime objects such as crt1.o
, crti.o
, and crtn.o
provided by glibc. This is mentioned at: https://sourceware.org/glibc/wiki/Testing/Builds?action=recall&rev=21#Compile_against_glibc_in_an_installed_location Those objects do early setup that glibc relies on, so I wouldn't be surprised if things crashed in wonderful and awesomely subtle ways.
For a more reliable setup, see Setup 2 below.
Build glibc and install locally:
export glibc_install="$(pwd)/glibc/build/install"
git clone git://sourceware.org/git/glibc.git
cd glibc
git checkout glibc-2.28
mkdir build
cd build
../configure --prefix "$glibc_install"
make -j `nproc`
make install -j `nproc`
test_glibc.c
#define _GNU_SOURCE
#include <assert.h>
#include <gnu/libc-version.h>
#include <stdatomic.h>
#include <stdio.h>
#include <threads.h>
atomic_int acnt;
int cnt;
int f(void* thr_data) {
for(int n = 0; n < 1000; ++n) {
++cnt;
++acnt;
}
return 0;
}
int main(int argc, char **argv) {
/* Basic library version check. */
printf("gnu_get_libc_version() = %s\n", gnu_get_libc_version());
/* Exercise thrd_create from -pthread,
* which is not present in glibc 2.27 in Ubuntu 18.04.
* https://stackoverflow.com/questions/56810/how-do-i-start-threads-in-plain-c/52453291#52453291 */
thrd_t thr[10];
for(int n = 0; n < 10; ++n)
thrd_create(&thr[n], f, NULL);
for(int n = 0; n < 10; ++n)
thrd_join(thr[n], NULL);
printf("The atomic counter is %u\n", acnt);
printf("The non-atomic counter is %u\n", cnt);
}
Compile and run with test_glibc.sh
:
#!/usr/bin/env bash
set -eux
gcc \
-L "${glibc_install}/lib" \
-I "${glibc_install}/include" \
-Wl,--rpath="${glibc_install}/lib" \
-Wl,--dynamic-linker="${glibc_install}/lib/ld-linux-x86-64.so.2" \
-std=c11 \
-o test_glibc.out \
-v \
test_glibc.c \
-pthread \
;
ldd ./test_glibc.out
./test_glibc.out
The program outputs the expected:
gnu_get_libc_version() = 2.28
The atomic counter is 10000
The non-atomic counter is 8674
Command adapted from https://sourceware.org/glibc/wiki/Testing/Builds?action=recall&rev=21#Compile_against_glibc_in_an_installed_location but --sysroot
made it fail with:
cannot find /home/ciro/glibc/build/install/lib/libc.so.6 inside /home/ciro/glibc/build/install
so I removed it.
ldd
output confirms that the ldd
and libraries that we've just built are actually being used as expected:
+ ldd test_glibc.out
linux-vdso.so.1 (0x00007ffe4bfd3000)
libpthread.so.0 => /home/ciro/glibc/build/install/lib/libpthread.so.0 (0x00007fc12ed92000)
libc.so.6 => /home/ciro/glibc/build/install/lib/libc.so.6 (0x00007fc12e9dc000)
/home/ciro/glibc/build/install/lib/ld-linux-x86-64.so.2 => /lib64/ld-linux-x86-64.so.2 (0x00007fc12f1b3000)
The gcc
compilation debug output shows that my host runtime objects were used, which is bad as mentioned previously, but I don't know how to work around it, e.g. it contains:
COLLECT_GCC_OPTIONS=/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/crt1.o
Now let's modify glibc with:
diff --git a/nptl/thrd_create.c b/nptl/thrd_create.c
index 113ba0d93e..b00f088abb 100644
--- a/nptl/thrd_create.c
+++ b/nptl/thrd_create.c
@@ -16,11 +16,14 @@
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
+#include <stdio.h>
+
#include "thrd_priv.h"
int
thrd_create (thrd_t *thr, thrd_start_t func, void *arg)
{
+ puts("hacked");
_Static_assert (sizeof (thr) == sizeof (pthread_t),
"sizeof (thr) != sizeof (pthread_t)");
Then recompile and re-install glibc, and recompile and re-run our program:
cd glibc/build
make -j `nproc`
make -j `nproc` install
./test_glibc.sh
and we see hacked
printed a few times as expected.
This further confirms that we actually used the glibc that we compiled and not the host one.
Tested on Ubuntu 18.04.
This is an alternative to setup 1, and it is the most correct setup I've achieved far: everything is correct as far as I can observe, including the C runtime objects such as crt1.o
, crti.o
, and crtn.o
.
In this setup, we will compile a full dedicated GCC toolchain that uses the glibc that we want.
The only downside to this method is that the build will take longer. But I wouldn't risk a production setup with anything less.
crosstool-NG is a set of scripts that downloads and compiles everything from source for us, including GCC, glibc and binutils.
Yes the GCC build system is so bad that we need a separate project for that.
This setup is only not perfect because crosstool-NG does not support building the executables without extra -Wl
flags, which feels weird since we've built GCC itself. But everything seems to work, so this is only an inconvenience.
Get crosstool-NG and configure it:
git clone https://github.com/crosstool-ng/crosstool-ng
cd crosstool-ng
git checkout a6580b8e8b55345a5a342b5bd96e42c83e640ac5
export CT_PREFIX="$(pwd)/.build/install"
export PATH="/usr/lib/ccache:${PATH}"
./bootstrap
./configure --enable-local
make -j `nproc`
./ct-ng x86_64-unknown-linux-gnu
./ct-ng menuconfig
The only mandatory option that I can see, is making it match your host kernel version to use the correct kernel headers. Find your host kernel version with:
uname -a
which shows me:
4.15.0-34-generic
so in menuconfig
I do:
Operating System
Version of linux
so I select:
4.14.71
which is the first equal or older version. It has to be older since the kernel is backwards compatible.
Now you can build with:
env -u LD_LIBRARY_PATH time ./ct-ng build CT_JOBS=`nproc`
and now wait for about thirty minutes to two hours for compilation.
The .config
that we generated with ./ct-ng x86_64-unknown-linux-gnu
has:
CT_GLIBC_V_2_27=y
To change that, in menuconfig
do:
C-library
Version of glibc
save the .config
, and continue with the build.
Or, if you want to use your own glibc source, e.g. to use glibc from the latest git, proceed like this:
Paths and misc options
Try features marked as EXPERIMENTAL
: set to trueC-library
Source of glibc
Custom location
: say yesCustom location
Custom source location
: point to a directory containing your glibc sourcewhere glibc was cloned as:
git clone git://sourceware.org/git/glibc.git
cd glibc
git checkout glibc-2.28
Once you have built he toolchain that you want, test it out with:
#!/usr/bin/env bash
set -eux
install_dir="${CT_PREFIX}/x86_64-unknown-linux-gnu"
PATH="${PATH}:${install_dir}/bin" \
x86_64-unknown-linux-gnu-gcc \
-Wl,--dynamic-linker="${install_dir}/x86_64-unknown-linux-gnu/sysroot/lib/ld-linux-x86-64.so.2" \
-Wl,--rpath="${install_dir}/x86_64-unknown-linux-gnu/sysroot/lib" \
-v \
-o test_glibc.out \
test_glibc.c \
-pthread \
;
ldd test_glibc.out
./test_glibc.out
Everything seems to work as in Setup 1, except that now the correct runtime objects were used:
COLLECT_GCC_OPTIONS=/home/ciro/crosstool-ng/.build/install/x86_64-unknown-linux-gnu/bin/../x86_64-unknown-linux-gnu/sysroot/usr/lib/../lib64/crt1.o
It does not seem possible with crosstool-NG, as explained below.
If you just re-build;
env -u LD_LIBRARY_PATH time ./ct-ng build CT_JOBS=`nproc`
then your changes to the custom glibc source location are taken into account, but it builds everything from scratch, making it unusable for iterative development.
If we do:
./ct-ng list-steps
it gives a nice overview of the build steps:
Available build steps, in order:
- companion_tools_for_build
- companion_libs_for_build
- binutils_for_build
- companion_tools_for_host
- companion_libs_for_host
- binutils_for_host
- cc_core_pass_1
- kernel_headers
- libc_start_files
- cc_core_pass_2
- libc
- cc_for_build
- cc_for_host
- libc_post_cc
- companion_libs_for_target
- binutils_for_target
- debug
- test_suite
- finish
Use "<step>" as action to execute only that step.
Use "+<step>" as action to execute up to that step.
Use "<step>+" as action to execute from that step onward.
therefore, we see that there are glibc steps intertwined with several GCC steps, most notably libc_start_files
comes before cc_core_pass_2
, which is likely the most expensive step together with cc_core_pass_1
.
In order to build just one step, you must first set the "Save intermediate steps" in .config
option for the intial build:
Paths and misc options
Debug crosstool-NG
Save intermediate steps
and then you can try:
env -u LD_LIBRARY_PATH time ./ct-ng libc+ -j`nproc`
but unfortunately, the +
required as mentioned at: https://github.com/crosstool-ng/crosstool-ng/issues/1033#issuecomment-424877536
Note however that restarting at an intermediate step resets the installation directory to the state it had during that step. I.e., you will have a rebuilt libc - but no final compiler built with this libc (and hence, no compiler libraries like libstdc++ either).
and basically still makes the rebuild too slow to be feasible for development, and I don't see how to overcome this without patching crosstool-NG.
Furthermore, starting from the libc
step didn't seem to copy over the source again from Custom source location
, further making this method unusable.
A bonus if you're also interested in the C++ standard library: How to edit and re-build the GCC libstdc++ C++ standard library source?
Use this command
gcc -dM -E - < /dev/null
to get this
#define _LP64 1
#define _STDC_PREDEF_H 1
#define __ATOMIC_ACQUIRE 2
#define __ATOMIC_ACQ_REL 4
#define __ATOMIC_CONSUME 1
#define __ATOMIC_HLE_ACQUIRE 65536
#define __ATOMIC_HLE_RELEASE 131072
#define __ATOMIC_RELAXED 0
#define __ATOMIC_RELEASE 3
#define __ATOMIC_SEQ_CST 5
#define __BIGGEST_ALIGNMENT__ 16
#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
#define __CHAR16_TYPE__ short unsigned int
#define __CHAR32_TYPE__ unsigned int
#define __CHAR_BIT__ 8
#define __DBL_DECIMAL_DIG__ 17
#define __DBL_DENORM_MIN__ ((double)4.94065645841246544177e-324L)
#define __DBL_DIG__ 15
#define __DBL_EPSILON__ ((double)2.22044604925031308085e-16L)
#define __DBL_HAS_DENORM__ 1
#define __DBL_HAS_INFINITY__ 1
#define __DBL_HAS_QUIET_NAN__ 1
#define __DBL_MANT_DIG__ 53
#define __DBL_MAX_10_EXP__ 308
#define __DBL_MAX_EXP__ 1024
#define __DBL_MAX__ ((double)1.79769313486231570815e+308L)
#define __DBL_MIN_10_EXP__ (-307)
#define __DBL_MIN_EXP__ (-1021)
#define __DBL_MIN__ ((double)2.22507385850720138309e-308L)
#define __DEC128_EPSILON__ 1E-33DL
#define __DEC128_MANT_DIG__ 34
#define __DEC128_MAX_EXP__ 6145
#define __DEC128_MAX__ 9.999999999999999999999999999999999E6144DL
#define __DEC128_MIN_EXP__ (-6142)
#define __DEC128_MIN__ 1E-6143DL
#define __DEC128_SUBNORMAL_MIN__ 0.000000000000000000000000000000001E-6143DL
#define __DEC32_EPSILON__ 1E-6DF
#define __DEC32_MANT_DIG__ 7
#define __DEC32_MAX_EXP__ 97
#define __DEC32_MAX__ 9.999999E96DF
#define __DEC32_MIN_EXP__ (-94)
#define __DEC32_MIN__ 1E-95DF
#define __DEC32_SUBNORMAL_MIN__ 0.000001E-95DF
#define __DEC64_EPSILON__ 1E-15DD
#define __DEC64_MANT_DIG__ 16
#define __DEC64_MAX_EXP__ 385
#define __DEC64_MAX__ 9.999999999999999E384DD
#define __DEC64_MIN_EXP__ (-382)
#define __DEC64_MIN__ 1E-383DD
#define __DEC64_SUBNORMAL_MIN__ 0.000000000000001E-383DD
#define __DECIMAL_BID_FORMAT__ 1
#define __DECIMAL_DIG__ 21
#define __DEC_EVAL_METHOD__ 2
#define __ELF__ 1
#define __FINITE_MATH_ONLY__ 0
#define __FLOAT_WORD_ORDER__ __ORDER_LITTLE_ENDIAN__
#define __FLT_DECIMAL_DIG__ 9
#define __FLT_DENORM_MIN__ 1.40129846432481707092e-45F
#define __FLT_DIG__ 6
#define __FLT_EPSILON__ 1.19209289550781250000e-7F
#define __FLT_EVAL_METHOD__ 0
#define __FLT_HAS_DENORM__ 1
#define __FLT_HAS_INFINITY__ 1
#define __FLT_HAS_QUIET_NAN__ 1
#define __FLT_MANT_DIG__ 24
#define __FLT_MAX_10_EXP__ 38
#define __FLT_MAX_EXP__ 128
#define __FLT_MAX__ 3.40282346638528859812e+38F
#define __FLT_MIN_10_EXP__ (-37)
#define __FLT_MIN_EXP__ (-125)
#define __FLT_MIN__ 1.17549435082228750797e-38F
#define __FLT_RADIX__ 2
#define __FXSR__ 1
#define __GCC_ASM_FLAG_OUTPUTS__ 1
#define __GCC_ATOMIC_BOOL_LOCK_FREE 2
#define __GCC_ATOMIC_CHAR16_T_LOCK_FREE 2
#define __GCC_ATOMIC_CHAR32_T_LOCK_FREE 2
#define __GCC_ATOMIC_CHAR_LOCK_FREE 2
#define __GCC_ATOMIC_INT_LOCK_FREE 2
#define __GCC_ATOMIC_LLONG_LOCK_FREE 2
#define __GCC_ATOMIC_LONG_LOCK_FREE 2
#define __GCC_ATOMIC_POINTER_LOCK_FREE 2
#define __GCC_ATOMIC_SHORT_LOCK_FREE 2
#define __GCC_ATOMIC_TEST_AND_SET_TRUEVAL 1
#define __GCC_ATOMIC_WCHAR_T_LOCK_FREE 2
#define __GCC_HAVE_DWARF2_CFI_ASM 1
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 1
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 1
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 1
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 1
#define __GCC_IEC_559 2
#define __GCC_IEC_559_COMPLEX 2
#define __GNUC_MINOR__ 3
#define __GNUC_PATCHLEVEL__ 0
#define __GNUC_STDC_INLINE__ 1
#define __GNUC__ 6
#define __GXX_ABI_VERSION 1010
#define __INT16_C(c) c
#define __INT16_MAX__ 0x7fff
#define __INT16_TYPE__ short int
#define __INT32_C(c) c
#define __INT32_MAX__ 0x7fffffff
#define __INT32_TYPE__ int
#define __INT64_C(c) c ## L
#define __INT64_MAX__ 0x7fffffffffffffffL
#define __INT64_TYPE__ long int
#define __INT8_C(c) c
#define __INT8_MAX__ 0x7f
#define __INT8_TYPE__ signed char
#define __INTMAX_C(c) c ## L
#define __INTMAX_MAX__ 0x7fffffffffffffffL
#define __INTMAX_TYPE__ long int
#define __INTPTR_MAX__ 0x7fffffffffffffffL
#define __INTPTR_TYPE__ long int
#define __INT_FAST16_MAX__ 0x7fffffffffffffffL
#define __INT_FAST16_TYPE__ long int
#define __INT_FAST32_MAX__ 0x7fffffffffffffffL
#define __INT_FAST32_TYPE__ long int
#define __INT_FAST64_MAX__ 0x7fffffffffffffffL
#define __INT_FAST64_TYPE__ long int
#define __INT_FAST8_MAX__ 0x7f
#define __INT_FAST8_TYPE__ signed char
#define __INT_LEAST16_MAX__ 0x7fff
#define __INT_LEAST16_TYPE__ short int
#define __INT_LEAST32_MAX__ 0x7fffffff
#define __INT_LEAST32_TYPE__ int
#define __INT_LEAST64_MAX__ 0x7fffffffffffffffL
#define __INT_LEAST64_TYPE__ long int
#define __INT_LEAST8_MAX__ 0x7f
#define __INT_LEAST8_TYPE__ signed char
#define __INT_MAX__ 0x7fffffff
#define __LDBL_DENORM_MIN__ 3.64519953188247460253e-4951L
#define __LDBL_DIG__ 18
#define __LDBL_EPSILON__ 1.08420217248550443401e-19L
#define __LDBL_HAS_DENORM__ 1
#define __LDBL_HAS_INFINITY__ 1
#define __LDBL_HAS_QUIET_NAN__ 1
#define __LDBL_MANT_DIG__ 64
#define __LDBL_MAX_10_EXP__ 4932
#define __LDBL_MAX_EXP__ 16384
#define __LDBL_MAX__ 1.18973149535723176502e+4932L
#define __LDBL_MIN_10_EXP__ (-4931)
#define __LDBL_MIN_EXP__ (-16381)
#define __LDBL_MIN__ 3.36210314311209350626e-4932L
#define __LONG_LONG_MAX__ 0x7fffffffffffffffLL
#define __LONG_MAX__ 0x7fffffffffffffffL
#define __LP64__ 1
#define __MMX__ 1
#define __NO_INLINE__ 1
#define __ORDER_BIG_ENDIAN__ 4321
#define __ORDER_LITTLE_ENDIAN__ 1234
#define __ORDER_PDP_ENDIAN__ 3412
#define __PIC__ 2
#define __PIE__ 2
#define __PRAGMA_REDEFINE_EXTNAME 1
#define __PTRDIFF_MAX__ 0x7fffffffffffffffL
#define __PTRDIFF_TYPE__ long int
#define __REGISTER_PREFIX__
#define __SCHAR_MAX__ 0x7f
#define __SEG_FS 1
#define __SEG_GS 1
#define __SHRT_MAX__ 0x7fff
#define __SIG_ATOMIC_MAX__ 0x7fffffff
#define __SIG_ATOMIC_MIN__ (-__SIG_ATOMIC_MAX__ - 1)
#define __SIG_ATOMIC_TYPE__ int
#define __SIZEOF_DOUBLE__ 8
#define __SIZEOF_FLOAT128__ 16
#define __SIZEOF_FLOAT80__ 16
#define __SIZEOF_FLOAT__ 4
#define __SIZEOF_INT128__ 16
#define __SIZEOF_INT__ 4
#define __SIZEOF_LONG_DOUBLE__ 16
#define __SIZEOF_LONG_LONG__ 8
#define __SIZEOF_LONG__ 8
#define __SIZEOF_POINTER__ 8
#define __SIZEOF_PTRDIFF_T__ 8
#define __SIZEOF_SHORT__ 2
#define __SIZEOF_SIZE_T__ 8
#define __SIZEOF_WCHAR_T__ 4
#define __SIZEOF_WINT_T__ 4
#define __SIZE_MAX__ 0xffffffffffffffffUL
#define __SIZE_TYPE__ long unsigned int
#define __SSE2_MATH__ 1
#define __SSE2__ 1
#define __SSE_MATH__ 1
#define __SSE__ 1
#define __SSP_STRONG__ 3
#define __STDC_HOSTED__ 1
#define __STDC_IEC_559_COMPLEX__ 1
#define __STDC_IEC_559__ 1
#define __STDC_ISO_10646__ 201605L
#define __STDC_NO_THREADS__ 1
#define __STDC_UTF_16__ 1
#define __STDC_UTF_32__ 1
#define __STDC_VERSION__ 201112L
#define __STDC__ 1
#define __UINT16_C(c) c
#define __UINT16_MAX__ 0xffff
#define __UINT16_TYPE__ short unsigned int
#define __UINT32_C(c) c ## U
#define __UINT32_MAX__ 0xffffffffU
#define __UINT32_TYPE__ unsigned int
#define __UINT64_C(c) c ## UL
#define __UINT64_MAX__ 0xffffffffffffffffUL
#define __UINT64_TYPE__ long unsigned int
#define __UINT8_C(c) c
#define __UINT8_MAX__ 0xff
#define __UINT8_TYPE__ unsigned char
#define __UINTMAX_C(c) c ## UL
#define __UINTMAX_MAX__ 0xffffffffffffffffUL
#define __UINTMAX_TYPE__ long unsigned int
#define __UINTPTR_MAX__ 0xffffffffffffffffUL
#define __UINTPTR_TYPE__ long unsigned int
#define __UINT_FAST16_MAX__ 0xffffffffffffffffUL
#define __UINT_FAST16_TYPE__ long unsigned int
#define __UINT_FAST32_MAX__ 0xffffffffffffffffUL
#define __UINT_FAST32_TYPE__ long unsigned int
#define __UINT_FAST64_MAX__ 0xffffffffffffffffUL
#define __UINT_FAST64_TYPE__ long unsigned int
#define __UINT_FAST8_MAX__ 0xff
#define __UINT_FAST8_TYPE__ unsigned char
#define __UINT_LEAST16_MAX__ 0xffff
#define __UINT_LEAST16_TYPE__ short unsigned int
#define __UINT_LEAST32_MAX__ 0xffffffffU
#define __UINT_LEAST32_TYPE__ unsigned int
#define __UINT_LEAST64_MAX__ 0xffffffffffffffffUL
#define __UINT_LEAST64_TYPE__ long unsigned int
#define __UINT_LEAST8_MAX__ 0xff
#define __UINT_LEAST8_TYPE__ unsigned char
#define __USER_LABEL_PREFIX__
#define __VERSION__ "6.3.0 20170406"
#define __WCHAR_MAX__ 0x7fffffff
#define __WCHAR_MIN__ (-__WCHAR_MAX__ - 1)
#define __WCHAR_TYPE__ int
#define __WINT_MAX__ 0xffffffffU
#define __WINT_MIN__ 0U
#define __WINT_TYPE__ unsigned int
#define __amd64 1
#define __amd64__ 1
#define __code_model_small__ 1
#define __gnu_linux__ 1
#define __has_include(STR) __has_include__(STR)
#define __has_include_next(STR) __has_include_next__(STR)
#define __k8 1
#define __k8__ 1
#define __linux 1
#define __linux__ 1
#define __pic__ 2
#define __pie__ 2
#define __unix 1
#define __unix__ 1
#define __x86_64 1
#define __x86_64__ 1
#define linux 1
#define unix 1
To generate a shared library you need first to compile your C code with the -fPIC
(position independent code) flag.
gcc -c -fPIC hello.c -o hello.o
This will generate an object file (.o), now you take it and create the .so file:
gcc hello.o -shared -o libhello.so
EDIT: Suggestions from the comments:
You can use
gcc -shared -o libhello.so -fPIC hello.c
to do it in one step. – Jonathan Leffler
I also suggest to add -Wall
to get all warnings, and -g
to get debugging information, to your gcc
commands. – Basile Starynkevitch
It turns out the compiler version I was using did not match the compiled version done with the coreset.o.
One was 32bit the other was 64bit. I'll leave this up in case anyone else runs into a similar problem.
Pedantic makes it so that the gcc compiler rejects all GNU C extensions not just the ones that make it ANSI compatible.
To invoke a dry run:
make -n
This will show what make
is attempting to do.
The only way to determine this is to try it. FWIW I have seen some really good improvements using Apple's LLVM gcc 4.2 compared to the regular gcc 4.2 (for x86-64 code with quite a lot of SSE), but YMMV for different code bases. Assuming you're working with x86/x86-64 and that you really do care about the last few percent then you ought to try Intel's ICC too, as this can often beat gcc - you can get a 30 day evaluation license from intel.com and try it.
I encountered this error when inheriting from an abstract class and not implementing all of the pure virtual methods in my subclass.
Rather than silencing the warnings, gcc style is usually to use either standard C constructs or the __attribute__
extension to tell the compiler more about your intention. For instance, the warning about assignment used as a condition is suppressed by putting the assignment in parentheses, i.e. if ((p=malloc(cnt)))
instead of if (p=malloc(cnt))
. Warnings about unused function arguments can be suppressed by some odd __attribute__
I can never remember, or by self-assignment, etc. But generally I prefer just globally disabling any warning option that generates warnings for things that will occur in correct code.
You can specify linker flags in target_link_libraries.
I was getting following error on a fedora 18 box:
1. /usr/include/gnu/stubs.h:7:27: fatal error: gnu/stubs-32.h: No such file or directory compilation terminated.
I Installed glibc.i686 and glibc-devel.i686, then compilation failed with following error:
2. /usr/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-redhat-linux/4.7.2/libgcc_s.so when searching for -lgcc_s /usr/bin/ld: cannot find -lgcc_s collect2: error: ld returned 1 exit status
Solution:
I installed (yum install) glibc.i686 glibc-devel.i386 and libgcc.i686 to get rid of the compilation issue.
Now compilation for 32 bit (-m32) works fine.
I think your question is, "why am I getting one more line than there is in the file?"
Imagine a file:
line 1
line 2
line 3
The file may be represented in ASCII like this:
line 1\nline 2\nline 3\n
(Where \n
is byte 0x10
.)
Now let's see what happens before and after each getline
call:
Before 1: line 1\nline 2\nline 3\n
Stream: ^
After 1: line 1\nline 2\nline 3\n
Stream: ^
Before 2: line 1\nline 2\nline 3\n
Stream: ^
After 2: line 1\nline 2\nline 3\n
Stream: ^
Before 2: line 1\nline 2\nline 3\n
Stream: ^
After 2: line 1\nline 2\nline 3\n
Stream: ^
Now, you'd think the stream would mark eof
to indicate the end of the file, right? Nope! This is because getline
sets eof
if the end-of-file marker is reached "during it's operation". Because getline
terminates when it reaches \n
, the end-of-file marker isn't read, and eof
isn't flagged. Thus, myfile.eof()
returns false, and the loop goes through another iteration:
Before 3: line 1\nline 2\nline 3\n
Stream: ^
After 3: line 1\nline 2\nline 3\n
Stream: ^ EOF
How do you fix this? Instead of checking for eof()
, see if .peek()
returns EOF
:
while(myfile.peek() != EOF){
getline ...
You can also check the return value of getline
(implicitly casting to bool):
while(getline(myfile,line)){
cout<< ...
According to the GNU make
manual:
CFLAGS: Extra flags to give to the C compiler.
CXXFLAGS: Extra flags to give to the C++ compiler.
CPPFLAGS: Extra flags to give to the C preprocessor and programs that use it (the C and Fortran compilers).
src: https://www.gnu.org/software/make/manual/make.html#index-CFLAGS
note: PP stands for PreProcessor (and not Plus Plus), i.e.
CPP: Program for running the C preprocessor, with results to standard output; default ‘$(CC) -E’.
These variables are used by the implicit rules of make
Compiling C programs
n.o is made automatically from n.c with a recipe of the form
‘$(CC) $(CPPFLAGS) $(CFLAGS) -c’.Compiling C++ programs
n.o is made automatically from n.cc, n.cpp, or n.C with a recipe of the form
‘$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c’.
We encourage you to use the suffix ‘.cc’ for C++ source files instead of ‘.C’.
src: https://www.gnu.org/software/make/manual/make.html#Catalogue-of-Rules
The macros defined in <inttypes.h>
are the most correct way to print values of types uint32_t
, uint16_t
, and so forth -- but they're not the only way.
Personally, I find those macros difficult to remember and awkward to use. (Given the syntax of a printf
format string, that's probably unavoidable; I'm not claiming I could have come up with a better system.)
An alternative is to cast the values to a predefined type and use the format for that type.
Types int
and unsigned int
are guaranteed by the language to be at least 16 bits wide, and therefore to be able to hold any converted value of type int16_t
or uint16_t
, respectively. Similarly, long
and unsigned long
are at least 32 bits wide, and long long
and unsigned long long
are at least 64 bits wide.
For example, I might write your program like this (with a few additional tweaks):
#include <stdio.h>
#include <stdint.h>
#include <netinet/in.h>
int main(void)
{
uint32_t a=12, a1;
uint16_t b=1, b1;
a1 = htonl(a);
printf("%lu---------%lu\n", (unsigned long)a, (unsigned long)a1);
b1 = htons(b);
printf("%u-----%u\n", (unsigned)b, (unsigned)b1);
return 0;
}
One advantage of this approach is that it can work even with pre-C99 implementations that don't support <inttypes.h>
. Such an implementation most likely wouldn't have <stdint.h>
either, but the technique is useful for other integer types.
Whevever you get a problem like this just go to the man page for the function in question and it will tell you what header you are missing, e.g.
$ man memset
MEMSET(3) BSD Library Functions Manual MEMSET(3)
NAME
memset -- fill a byte string with a byte value
LIBRARY
Standard C Library (libc, -lc)
SYNOPSIS
#include <string.h>
void *
memset(void *b, int c, size_t len);
Note that for C++ it's generally preferable to use the proper equivalent C++ headers, <cstring>
/<cstdio>
/<cstdlib>
/etc, rather than C's <string.h>
/<stdio.h>
/<stdlib.h>
/etc.
Follow these steps:
sudo xcodebuild --license
.Error 127
means one of two things:
$PATH
, or in this case, the relative path is correct -- remember that the current working directory for a random terminal might not be the same for the IDE you're using. it might be better to just use an absolute path instead.file -L
on /bin/sh
(to get your default/native format) and on the compiler itself (to see what format it is).if the problem is (2), then you can solve it in a few diff ways:
Here is yet another solution, because none of these solutions worked for me. For reference, I was trying to pip install
something on an Amazon Linux AMI base Docker image for Python 3.6.
Non-docker solution:
# Install python3-devel like everyone says
yum -y install python36-devel.x86_64
# Find the install directory of `Python.h`
rpm -ql python36-devel.x86_64 | grep -i "Python.h"
# Forcefully add it to your include path
C_INCLUDE_PATH='/usr/include/python3.6m'
export C_INCLUDE_PATH
Docker solution:
# Install python3-devel like everyone says
RUN yum -y install python36-devel.x86_64
# Find the install directory of `Python.h`, for me it was /usr/include/python3.6m
RUN rpm -ql python36-devel.x86_64 | grep -i "Python.h" && fake_command_so_docker_fails_and_shows_us_the_output
# Since the previous command contains a purposeful error, remove it before the next run
# Forcefully add it to your include path
ARG C_INCLUDE_PATH='/usr/include/python3.6m'
NOTE: If you're getting the error when compiling C++, use CPLUS_INCLUDE_PATH
.
All answers above are incomplete, the problem here lies in linker ld
rather than compiler collect2: ld returned 1 exit status
. When you are compiling your fib.c
to object:
$ gcc -c fib.c
$ nm fib.o
0000000000000028 T fibo
U floor
U _GLOBAL_OFFSET_TABLE_
0000000000000000 T main
U pow
U printf
Where nm
lists symbols from object file. You can see that this was compiled without an error, but pow
, floor
, and printf
functions have undefined references, now if I will try to link this to executable:
$ gcc fib.o
fib.o: In function `fibo':
fib.c:(.text+0x57): undefined reference to `pow'
fib.c:(.text+0x84): undefined reference to `floor'
collect2: error: ld returned 1 exit status
Im getting similar output you get. To solve that, I need to tell linker where to look for references to pow
, and floor
, for this purpose I will use linker -l
flag with m
which comes from libm.so
library.
$ gcc fib.o -lm
$ nm a.out
0000000000201010 B __bss_start
0000000000201010 b completed.7697
w __cxa_finalize@@GLIBC_2.2.5
0000000000201000 D __data_start
0000000000201000 W data_start
0000000000000620 t deregister_tm_clones
00000000000006b0 t __do_global_dtors_aux
0000000000200da0 t
__do_global_dtors_aux_fini_array_entry
0000000000201008 D __dso_handle
0000000000200da8 d _DYNAMIC
0000000000201010 D _edata
0000000000201018 B _end
0000000000000722 T fibo
0000000000000804 T _fini
U floor@@GLIBC_2.2.5
00000000000006f0 t frame_dummy
0000000000200d98 t __frame_dummy_init_array_entry
00000000000009a4 r __FRAME_END__
0000000000200fa8 d _GLOBAL_OFFSET_TABLE_
w __gmon_start__
000000000000083c r __GNU_EH_FRAME_HDR
0000000000000588 T _init
0000000000200da0 t __init_array_end
0000000000200d98 t __init_array_start
0000000000000810 R _IO_stdin_used
w _ITM_deregisterTMCloneTable
w _ITM_registerTMCloneTable
0000000000000800 T __libc_csu_fini
0000000000000790 T __libc_csu_init
U __libc_start_main@@GLIBC_2.2.5
00000000000006fa T main
U pow@@GLIBC_2.2.5
U printf@@GLIBC_2.2.5
0000000000000660 t register_tm_clones
00000000000005f0 T _start
0000000000201010 D __TMC_END__
You can now see, functions pow
, floor
are linked to GLIBC_2.2.5
.
Parameters order is important too, unless your system is configured to use shared librares by default, my system is not, so when I issue:
$ gcc -lm fib.o
fib.o: In function `fibo':
fib.c:(.text+0x57): undefined reference to `pow'
fib.c:(.text+0x84): undefined reference to `floor'
collect2: error: ld returned 1 exit status
Note -lm
flag before object file. So in conclusion, add -lm
flag after all other flags, and parameters, to be sure.
Did you 'export' in your .bashrc?
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:"/path/to/library"
If it doesn't show up in your package manager (i.e. apt-cache search texinfo
) and even apt-file search bin/makeinfo
is no help, you may have to enable non-free/restricted packages for your package manager.
For ubuntu, sudo $EDITOR /etc/apt/sources.list
and add restricted
.
deb http://archive.ubuntu.com/ubuntu bionic main restricted universe multiverse
deb http://archive.ubuntu.com/ubuntu bionic-security main
deb http://archive.ubuntu.com/ubuntu bionic-updates main
For debian, sudo $EDITOR /etc/apt/sources.list
and add non-free
. You can even have preferences on package level if you don't want to clutter the package db with non-free stuff.
After a sudo apt-get udpate
you should find the required package.
The standard tool for listing symbols is nm
, you can use it simply like this:
nm -gD yourLib.so
If you want to see symbols of a C++ library, add the "-C" option which demangle the symbols (it's far more readable demangled).
nm -gDC yourLib.so
If your .so file is in elf format, you have two options:
Either objdump
(-C
is also useful for demangling C++):
$ objdump -TC libz.so
libz.so: file format elf64-x86-64
DYNAMIC SYMBOL TABLE:
0000000000002010 l d .init 0000000000000000 .init
0000000000000000 DF *UND* 0000000000000000 GLIBC_2.2.5 free
0000000000000000 DF *UND* 0000000000000000 GLIBC_2.2.5 __errno_location
0000000000000000 w D *UND* 0000000000000000 _ITM_deregisterTMCloneTable
Or use readelf
:
$ readelf -Ws libz.so
Symbol table '.dynsym' contains 112 entries:
Num: Value Size Type Bind Vis Ndx Name
0: 0000000000000000 0 NOTYPE LOCAL DEFAULT UND
1: 0000000000002010 0 SECTION LOCAL DEFAULT 10
2: 0000000000000000 0 FUNC GLOBAL DEFAULT UND free@GLIBC_2.2.5 (14)
3: 0000000000000000 0 FUNC GLOBAL DEFAULT UND __errno_location@GLIBC_2.2.5 (14)
4: 0000000000000000 0 NOTYPE WEAK DEFAULT UND _ITM_deregisterTMCloneTable
I'm going to throw my two cents into this question and suggest a slightly more verbose extension of elias's answer. As of gcc 4.6, running of gcc -march=native -v -E - < /dev/null
emits an increasing amount of spam in the form of superfluous -mno-*
flags. The following will strip these:
gcc -march=native -v -E - < /dev/null 2>&1 | grep cc1 | perl -pe 's/ -mno-\S+//g; s/^.* - //g;'
However, I have only verified the correctness of this on two different CPUs (an Intel Core2 and AMD Phenom), so I suggest also running the following script to be sure that all of these -mno-*
flags can be safely stripped.
2021 EDIT: There are indeed machines where -march=native
uses a particular -march
value, but must disable some implied ISAs (Instruction Set Architecture) with -mno-*
.
#!/bin/bash
gcc_cmd="gcc"
# Optionally supply path to gcc as first argument
if (($#)); then
gcc_cmd="$1"
fi
with_mno=$(
"${gcc_cmd}" -march=native -mtune=native -v -E - < /dev/null 2>&1 |
grep cc1 |
perl -pe 's/^.* - //g;'
)
without_mno=$(echo "${with_mno}" | perl -pe 's/ -mno-\S+//g;')
"${gcc_cmd}" ${with_mno} -dM -E - < /dev/null > /tmp/gcctest.a.$$
"${gcc_cmd}" ${without_mno} -dM -E - < /dev/null > /tmp/gcctest.b.$$
if diff -u /tmp/gcctest.{a,b}.$$; then
echo "Safe to strip -mno-* options."
else
echo
echo "WARNING! Some -mno-* options are needed!"
exit 1
fi
rm /tmp/gcctest.{a,b}.$$
I haven't found a difference between gcc -march=native -v -E - < /dev/null
and gcc -march=native -### -E - < /dev/null
other than some parameters being quoted -- and parameters that contain no special characters, so I'm not sure under what circumstances this makes any real difference.
Finally, note that --march=native
was introduced in gcc 4.2, prior to which it is just an unrecognized argument.
.init
/.fini
isn't deprecated. It's still part of the the ELF standard and I'd dare say it will be forever. Code in .init
/.fini
is run by the loader/runtime-linker when code is loaded/unloaded. I.e. on each ELF load (for example a shared library) code in .init
will be run. It's still possible to use that mechanism to achieve about the same thing as with __attribute__((constructor))/((destructor))
. It's old-school but it has some benefits.
.ctors
/.dtors
mechanism for example require support by system-rtl/loader/linker-script. This is far from certain to be available on all systems, for example deeply embedded systems where code executes on bare metal. I.e. even if __attribute__((constructor))/((destructor))
is supported by GCC, it's not certain it will run as it's up to the linker to organize it and to the loader (or in some cases, boot-code) to run it. To use .init
/.fini
instead, the easiest way is to use linker flags: -init & -fini (i.e. from GCC command line, syntax would be -Wl -init my_init -fini my_fini
).
On system supporting both methods, one possible benefit is that code in .init
is run before .ctors
and code in .fini
after .dtors
. If order is relevant that's at least one crude but easy way to distinguish between init/exit functions.
A major drawback is that you can't easily have more than one _init
and one _fini
function per each loadable module and would probably have to fragment code in more .so
than motivated. Another is that when using the linker method described above, one replaces the original _init and _fini
default functions (provided by crti.o
). This is where all sorts of initialization usually occur (on Linux this is where global variable assignment is initialized). A way around that is described here
Notice in the link above that a cascading to the original _init()
is not needed as it's still in place. The call
in the inline assembly however is x86-mnemonic and calling a function from assembly would look completely different for many other architectures (like ARM for example). I.e. code is not transparent.
.init
/.fini
and .ctors
/.detors
mechanisms are similar, but not quite. Code in .init
/.fini
runs "as is". I.e. you can have several functions in .init
/.fini
, but it is AFAIK syntactically difficult to put them there fully transparently in pure C without breaking up code in many small .so
files.
.ctors
/.dtors
are differently organized than .init
/.fini
. .ctors
/.dtors
sections are both just tables with pointers to functions, and the "caller" is a system-provided loop that calls each function indirectly. I.e. the loop-caller can be architecture specific, but as it's part of the system (if it exists at all i.e.) it doesn't matter.
The following snippet adds new function pointers to the .ctors
function array, principally the same way as __attribute__((constructor))
does (method can coexist with __attribute__((constructor)))
.
#define SECTION( S ) __attribute__ ((section ( S )))
void test(void) {
printf("Hello\n");
}
void (*funcptr)(void) SECTION(".ctors") =test;
void (*funcptr2)(void) SECTION(".ctors") =test;
void (*funcptr3)(void) SECTION(".dtors") =test;
One can also add the function pointers to a completely different self-invented section. A modified linker script and an additional function mimicking the loader .ctors
/.dtors
loop is needed in such case. But with it one can achieve better control over execution order, add in-argument and return code handling e.t.a. (In a C++ project for example, it would be useful if in need of something running before or after global constructors).
I'd prefer __attribute__((constructor))/((destructor))
where possible, it's a simple and elegant solution even it feels like cheating. For bare-metal coders like myself, this is just not always an option.
Some good reference in the book Linkers & loaders.
Do what the compiler tells you to do, i.e. recompile with -fPIC
. To learn what does this flag do and why you need it in this case, see Code Generation Options of the GCC manual.
In brief, the term position independent code (PIC) refers to the generated machine code which is memory address agnostic, i.e. does not make any assumptions about where it was loaded into RAM. Only position independent code is supposed to be included into shared objects (SO) as they should have an ability to dynamically change their location in RAM.
Finally, you can read about it on Wikipedia too.
Try to update your compiler, I'm using GCC 4.7 on Windows 7 Starter x86 with MinGW and it compiles fine with the same options both in C99 and C11.
I have found on an arm hardfloat system where glibc binutils and gcc were crosscompiled, using gcc gives the same error.
It is solved by exporting-mfloat-abi=hard
to flags, then gcc compiles without errors.
When you start in Cygwin you are in the "/home/Administrator" zone, so put your a.exe file there.
Then at the prompt run:
cd a.exe
It will be read in by Cygwin and you will be asked to install it.
Following up on Mat's answer (use Cygwin), here are some detailed instructions for : installing gcc on Windows The packages you want are gcc, gdb and make. Cygwin installer lets you install additional packages if you need them.
The solution to solve this is to find out why you're getting the segmentation fault, and fix that.
try the following command:
which gcc-arm-linux-gnueabi
Its very likely the command is installed in /usr/bin
.
CUDA is after some header modifications compatible with gcc4.7 and maybe higher version: https://www.udacity.com/wiki/cs344/troubleshoot_gcc47
GCC 4.9 introduces a newer C++ ABI version than your system libstdc++ has, so you need to tell the loader to use this newer version of the library by adding that path to LD_LIBRARY_PATH
. Unfortunately, I cannot tell you straight off where the libstdc++ so for your GCC 4.9 installation is located, as this depends on how you configured GCC. So you need something in the style of:
export LD_LIBRARY_PATH=/home/user/lib/gcc-4.9.0/lib:/home/user/lib/boost_1_55_0/stage/lib:$LD_LIBRARY_PATH
Note the actual path may be different (there might be some subdirectory hidden under there, like `x86_64-unknown-linux-gnu/4.9.0´ or similar).
If you don't declare a function and it only appears after being called, it is automatically assumed to be int
, so in your case, you didn't declare
void my_print (char *);
void my_print2 (char *);
before you call it in main, so the compiler assume there are functions which their prototypes are int my_print2 (char *);
and int my_print2 (char *);
and you can't have two functions with the same prototype except of the return type, so you get the error of conflicting types
.
As Brian suggested, declare those two methods before main.
This is a quirk of the C grammar. A label (Cleanup:
) is not allowed to appear immediately before a declaration (such as char *str ...;
), only before a statement (printf(...);
). In C89 this was no great difficulty because declarations could only appear at the very beginning of a block, so you could always move the label down a bit and avoid the issue. In C99 you can mix declarations and code, but you still can't put a label immediately before a declaration.
You can put a semicolon immediately after the label's colon (as suggested by Renan) to make there be an empty statement there; this is what I would do in machine-generated code. Alternatively, hoist the declaration to the top of the function:
int main (void)
{
char *str;
printf("Hello ");
goto Cleanup;
Cleanup:
str = "World\n";
printf("%s\n", str);
return 0;
}
What is the difference between g++
and gcc
?
gcc
has evolved from a single language "GNU C Compiler" to be a multi-language "GNU Compiler Collection". The term "GNU C Compiler" is still used sometimes in the context of C programming.
The g++
is the C++ compiler for the GNU Compiler Collection. Like gnat
is the Ada compiler for gcc
. see Using the GNU Compiler Collection (GCC)
For example, the Ubuntu 16.04 and 18.04 man g++
command returns the GCC(1)
manual page.
The Ubuntu 16.04 and 18.04 man gcc
states that ...
g++
accepts mostly the same options asgcc
and that the default ...
... use of
gcc
does not add the C++ library.g++
is a program that calls GCC and automatically specifies linking against the C++ library. It treats .c, .h and .i files as C++ source files instead of C source files unless -x is used. This program is also useful when precompiling a C header file with a .h extension for use in C++ compilations.
Search the gcc
man pages for more details on the option variances between gcc
and g++
.
Which one should be used for general c++ development?
Technically, either gcc
or g++
can be used for general C++ development with applicable option settings. However, the g++
default behavior is naturally aligned to a C++ development.
The Ubuntu 18.04 'gcc' man page added, and Ubuntu 20.04 continues to have, the following paragraph:
The usual way to run GCC is to run the executable called
gcc
, ormachine-gcc
when cross-compiling, ormachine-gcc-version
to run a specific version of GCC. When you compile C++ programs, you should invoke GCC asg++
instead.
Use the -S
option to gcc (or g++).
gcc -S helloworld.c
This will run the preprocessor (cpp) over helloworld.c, perform the initial compilation and then stop before the assembler is run.
By default this will output a file helloworld.s
. The output file can be still be set by using the -o
option.
gcc -S -o my_asm_output.s helloworld.c
Of course this only works if you have the original source.
An alternative if you only have the resultant object file is to use objdump
, by setting the --disassemble
option (or -d
for the abbreviated form).
objdump -S --disassemble helloworld > helloworld.dump
This option works best if debugging option is enabled for the object file (-g
at compilation time) and the file hasn't been stripped.
Running file helloworld
will give you some indication as to the level of detail that you will get by using objdump.
Sure, find where -Werror
is set and remove that flag. Then warnings will be only warnings.
If you add -Wl,--start-group
to the linker flags it does not care which order they're in or if there are circular dependencies.
On Qt this means adding:
QMAKE_LFLAGS += -Wl,--start-group
Saves loads of time messing about and it doesn't seem to slow down linking much (which takes far less time than compilation anyway).
I was getting the error “gcc: error: x86_64-linux-gnu-gcc: No such file or directory” as I was trying to build a simple c-extension module to run in Python. I tried all the things above to no avail, and finally realized that I had an error in my module.c code! So I thought it would be helpful to add that, if you are getting this error message but you have python-dev and everything correctly installed, you should look for issues in your code.
That is because is does not exist, since it is bounded to Windows.
Use the standard functions from <stdio.h>
instead, such as getc
The suggested ncurses library is good if you want to write console-based GUIs, but I don't think it is what you want.
you can add the Path to coinhsl lib to LD_LIBRARY_PATH
variable. May be that will help.
export LD_LIBRARY_PATH=/xx/yy/zz:$LD_LIBRARY_PATH
where /xx/yy/zz
represent the path to coinhsl
lib.
Command where or frame can be used. where command will give more info with the function name
Seems like you posted a new question after you realized that you were dealing with a simpler problem related to size_t
. I am glad that you did.
Anyways, You have a .c
source file, and most of the code looks as per C standards, except that #include <iostream>
and using namespace std;
C equivalent for the built-in functions of C++ standard #include<iostream>
can be availed through #include<stdio.h>
#include <iostream>
with #include <stdio.h>
, delete using namespace std;
With #include <iostream>
taken off, you would need a C standard alternative for cout << endl;
, which can be done by printf("\n");
or putchar('\n');
Out of the two options, printf("\n");
works the faster as I observed.
When used printf("\n");
in the code above in place of cout<<endl;
$ time ./thread.exe
1 2 3 4 5 6 7 8 9 10
real 0m0.031s
user 0m0.030s
sys 0m0.030s
When used putchar('\n');
in the code above in place of cout<<endl;
$ time ./thread.exe
1 2 3 4 5 6 7 8 9 10
real 0m0.047s
user 0m0.030s
sys 0m0.030s
Compiled with Cygwin gcc (GCC) 4.8.3
version. results averaged over 10 samples. (Took me 15 mins)
Firstly, in general:
If these .h
files are indeed typical C-style header files (as opposed to being something completely different that just happens to be named with .h
extension), then no, there's no reason to "compile" these header files independently. Header files are intended to be included into implementation files, not fed to the compiler as independent translation units.
Since a typical header file usually contains only declarations that can be safely repeated in each translation unit, it is perfectly expected that "compiling" a header file will have no harmful consequences. But at the same time it will not achieve anything useful.
Basically, compiling hello.h
as a standalone translation unit equivalent to creating a degenerate dummy.c
file consisting only of #include "hello.h"
directive, and feeding that dummy.c
file to the compiler. It will compile, but it will serve no meaningful purpose.
Secondly, specifically for GCC:
Many compilers will treat files differently depending on the file name extension. GCC has special treatment for files with .h
extension when they are supplied to the compiler as command-line arguments. Instead of treating it as a regular translation unit, GCC creates a precompiled header file for that .h
file.
You can read about it here: http://gcc.gnu.org/onlinedocs/gcc/Precompiled-Headers.html
So, this is the reason you might see .h
files being fed directly to GCC.
GCC comes with a compiler runtime library (libgcc) which it uses for (among other things) providing a low-level OS abstraction for multithreading related functionality in the languages it supports. The most relevant example is libstdc++'s C++11 <thread>
, <mutex>
, and <future>
, which do not have a complete implementation when GCC is built with its internal Win32 threading model. MinGW-w64 provides a winpthreads (a pthreads implementation on top of the Win32 multithreading API) which GCC can then link in to enable all the fancy features.
I must stress this option does not forbid you to write any code you want (it has absolutely NO influence on what API you can call in your code). It only reflects what GCC's runtime libraries (libgcc/libstdc++/...) use for their functionality. The caveat quoted by @James has nothing to do with GCC's internal threading model, but rather with Microsoft's CRT implementation.
To summarize:
posix
: enable C++11/C11 multithreading features. Makes libgcc depend on libwinpthreads, so that even if you don't directly call pthreads API, you'll be distributing the winpthreads DLL. There's nothing wrong with distributing one more DLL with your application.win32
: No C++11 multithreading features.Neither have influence on any user code calling Win32 APIs or pthreads APIs. You can always use both.
In my case it was just because I had not Saved the source file and was trying to compile a empty file .
.a
files are created with the ar
utility, and they are libraries. To use it with gcc
, collect all .a files
in a lib/
folder and then link with -L lib/
and -l<name of specific library>
.
Collection of all .a files into lib/
is optional. Doing so makes for better looking directories with nice separation of code and libraries, IMHO.
I met some problems in Clion and finally, I solved them. Here is some experience.
I've gotten this error too.
for (int i=0;i<10;i++) { ..
is not valid in the C89/C90 standard. As OysterD says, you need to do:
int i;
for (i=0;i<10;i++) { ..
Your original code is allowed in C99 and later standards of the C language.
function("MyString");
is similar to
char *s = "MyString";
function(s);
"MyString"
is in both cases a string literal and in both cases the string is unmodifiable.
function("MyString");
passes the address of a string literal to function
as an argument.
Why don't you use the -Wno-deprecated
option to ignore deprecated warning messages?
Try setting C_INCLUDE_PATH
(for C header files) or CPLUS_INCLUDE_PATH
(for C++ header files).
As Ciro mentioned, CPATH
will set the path for both C and C++ (and any other language).
More details in GCC's documentation.
Are you mixing C and C++? One issue that can occur is that the declarations in the .h
file for a .c
file need to be surrounded by:
#if defined(__cplusplus)
extern "C" { // Make sure we have C-declarations in C++ programs
#endif
and:
#if defined(__cplusplus)
}
#endif
Note: if unable / unwilling to modify the .h
file(s) in question, you can surround their inclusion with extern "C"
:
extern "C" {
#include <abc.h>
} //extern
Use the -S (note: capital S) switch to GCC, and it will emit the assembly code to a file with a .s extension. For example, the following command:
gcc -O2 -S -c foo.c
Use uintptr_t
as your integer type.
try to put the path in the system variables instead of putting in user variables in environment variables.
-w
is the GCC-wide option to disable warning messages.
There are two ways to achieve that:
-rpath
linker option:gcc XXX.c -o xxx.out -L$HOME/.usr/lib -lXX -Wl,-rpath=/home/user/.usr/lib
Use LD_LIBRARY_PATH
environment variable - put this line in your ~/.bashrc
file:
export LD_LIBRARY_PATH=/home/user/.usr/lib
This will work even for a pre-generated binaries, so you can for example download some packages from the debian.org, unpack the binaries and shared libraries into your home directory, and launch them without recompiling.
For a quick test, you can also do (in bash at least):
LD_LIBRARY_PATH=/home/user/.usr/lib ./xxx.out
which has the advantage of not changing your library path for everything else.
g++ is the C++ compiler under linux. The code looks right. It is possible that you are missing a library reference which is used as such:
g++ -l{library name here (math fns use "m")} codefile.cpp
Late answer - I found the other answers useful - and wanted to add a bit extra.
How do I dump preprocessor macros coming from a particular header file?
echo "#include <sys/socket.h>" | gcc -E -dM -
or (thanks to @mymedia for the suggestion):
gcc -E -dM -include sys/socket.h - < /dev/null
In particular, I wanted to see what SOMAXCONN was defined to on my system. I know I could just open up the standard header file, but sometimes I have to search around a bit to find the header file locations. Instead I can just use this one-liner:
$ gcc -E -dM -include sys/socket.h - < /dev/null | grep SOMAXCONN
#define SOMAXCONN 128
$
Here a full makefile example:
makefile
TARGET = prog
$(TARGET): main.o lib.a
gcc $^ -o $@
main.o: main.c
gcc -c $< -o $@
lib.a: lib1.o lib2.o
ar rcs $@ $^
lib1.o: lib1.c lib1.h
gcc -c -o $@ $<
lib2.o: lib2.c lib2.h
gcc -c -o $@ $<
clean:
rm -f *.o *.a $(TARGET)
explaining the makefile:
target: prerequisites
- the rule head$@
- means the target$^
- means all prerequisites$<
- means just the first prerequisitear
- a Linux tool to create, modify, and extract from archives see the man pages for further information. The options in this case mean:
r
- replace files existing inside the archivec
- create a archive if not already existents
- create an object-file index into the archiveTo conclude: The static library under Linux is nothing more than a archive of object files.
main.c using the lib
#include <stdio.h>
#include "lib.h"
int main ( void )
{
fun1(10);
fun2(10);
return 0;
}
lib.h the libs main header
#ifndef LIB_H_INCLUDED
#define LIB_H_INCLUDED
#include "lib1.h"
#include "lib2.h"
#endif
lib1.c first lib source
#include "lib1.h"
#include <stdio.h>
void fun1 ( int x )
{
printf("%i\n",x);
}
lib1.h the corresponding header
#ifndef LIB1_H_INCLUDED
#define LIB1_H_INCLUDED
#ifdef __cplusplus
extern “C” {
#endif
void fun1 ( int x );
#ifdef __cplusplus
}
#endif
#endif /* LIB1_H_INCLUDED */
lib2.c second lib source
#include "lib2.h"
#include <stdio.h>
void fun2 ( int x )
{
printf("%i\n",2*x);
}
lib2.h the corresponding header
#ifndef LIB2_H_INCLUDED
#define LIB2_H_INCLUDED
#ifdef __cplusplus
extern “C” {
#endif
void fun2 ( int x );
#ifdef __cplusplus
}
#endif
#endif /* LIB2_H_INCLUDED */
Many different ways have already been described by the other answers. However, many of them either involved ShowDialog()
or that form1
stay open but hidden. The best and most intuitive way in my opinion is to simply close form1
and then create form2
from an outside location (i.e. not from within either of those forms). In the case where form1
was created in Main
, form2
can simply be created using Application.Run
just like form1
before. Here's an example scenario:
I need the user to enter their credentials in order for me to authenticate them somehow. Afterwards, if authentication was successful, I want to show the main application to the user. In order to accomplish this, I'm using two forms: LogingForm
and MainForm
. The LoginForm
has a flag that determines whether authentication was successful or not. This flag is then used to decide whether to create the MainForm
instance or not. Neither of these forms need to know about the other and both forms can be opened and closed gracefully. Here's the code for this:
class LoginForm : Form
{
public bool UserSuccessfullyAuthenticated { get; private set; }
void LoginButton_Click(object s, EventArgs e)
{
if(AuthenticateUser(/* ... */))
{
UserSuccessfullyAuthenticated = true;
Close();
}
}
}
static class Program
{
[STAThread]
static void Main()
{
LoginForm loginForm = new LoginForm();
Application.Run(loginForm);
if(loginForm.UserSuccessfullyAuthenticated)
{
// MainForm is defined elsewhere
Application.Run(new MainForm());
}
}
}
You could actually go with:
Map.Entry<String, String> en= Maps.immutableEntry(key, value);
require 'net/http'
result = Net::HTTP.get(URI.parse('http://www.example.com/about.html'))
# or
result = Net::HTTP.get(URI.parse('http://www.example.com'), '/about.html')
Create a <div>
element that contains your loading message, give the <div>
an ID, and then when your content has finished loading, hide the <div>
:
$("#myElement").css("display", "none");
...or in plain JavaScript:
document.getElementById("myElement").style.display = "none";
SELECT CONVERT(uniqueidentifier,STUFF(STUFF(STUFF(STUFF('B33D42A3AC5A4D4C81DD72F3D5C49025',9,0,'-'),14,0,'-'),19,0,'-'),24,0,'-'))
Comparison sorts (i.e. ones based on comparing elements) cannot possibly be faster than n log n
. It doesn't matter what the underlying data structure is. See Wikipedia.
Other kinds of sort that take advantage of there being lots of identical elements in the list (such as the counting sort), or some expected distribution of elements in the list, are faster, though I can't think of any that work particularly well on a linked list.
You're attempting to free something that isn't a pointer to a "freeable" memory address. Just because something is an address doesn't mean that you need to or should free it.
There are two main types of memory you seem to be confusing - stack memory and heap memory.
Stack memory lives in the live span of the function. It's temporary space for things that shouldn't grow too big. When you call the function main
, it sets aside some memory for your variables you've declared (p
,token
, and so on).
Heap memory lives from when you malloc
it to when you free
it. You can use much more heap memory than you can stack memory. You also need to keep track of it - it's not easy like stack memory!
You have a few errors:
You're trying to free memory that's not heap memory. Don't do that.
You're trying to free the inside of a block of memory. When you have in fact allocated a block of memory, you can only free it from the pointer returned by malloc
. That is to say, only from the beginning of the block. You can't free a portion of the block from the inside.
For your bit of code here, you probably want to find a way to copy relevant portion of memory to somewhere else...say another block of memory you've set aside. Or you can modify the original string if you want (hint: char value 0 is the null terminator and tells functions like printf to stop reading the string).
EDIT: The malloc function does allocate heap memory*.
"9.9.1 The malloc and free Functions
The C standard library provides an explicit allocator known as the malloc package. Programs allocate blocks from the heap by calling the malloc function."
~Computer Systems : A Programmer's Perspective, 2nd Edition, Bryant & O'Hallaron, 2011
EDIT 2: * The C standard does not, in fact, specify anything about the heap or the stack. However, for anyone learning on a relevant desktop/laptop machine, the distinction is probably unnecessary and confusing if anything, especially if you're learning about how your program is stored and executed. When you find yourself working on something like an AVR microcontroller as H2CO3 has, it is definitely worthwhile to note all the differences, which from my own experience with embedded systems, extend well past memory allocation.
Download the the repository key with:
curl -s https://deb.nodesource.com/gpgkey/nodesource.gpg.key | apt-key add -
Then setup the repository:
sudo sh -c "echo deb https://deb.nodesource.com/node_8.x cosmic main \
> /etc/apt/sources.list.d/nodesource.list"
sudo apt-get update
sudo apt-get install nodejs
AJAX is simply Asyncronous JSON or XML (in most newer situations JSON). Because we are doing an ASYNC task we will likely be providing our users with a more enjoyable UI experience. In this specific case we are doing a FORM submission using AJAX.
Really quickly there are 4 general web actions GET
, POST
, PUT
, and DELETE
; these directly correspond with SELECT/Retreiving DATA
, INSERTING DATA
, UPDATING/UPSERTING DATA
, and DELETING DATA
. A default HTML/ASP.Net webform/PHP/Python or any other form
action is to "submit" which is a POST action. Because of this the below will all describe doing a POST. Sometimes however with http you might want a different action and would likely want to utilitize .ajax
.
/* attach a submit handler to the form */
$("#formoid").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get the action attribute from the <form action=""> element */
var $form = $(this),
url = $form.attr('action');
/* Send the data using post with element id name and name2*/
var posting = $.post(url, {
name: $('#name').val(),
name2: $('#name2').val()
});
/* Alerts the results */
posting.done(function(data) {
$('#result').text('success');
});
posting.fail(function() {
$('#result').text('failed');
});
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="formoid" action="studentFormInsert.php" title="" method="post">
<div>
<label class="title">First Name</label>
<input type="text" id="name" name="name">
</div>
<div>
<label class="title">Last Name</label>
<input type="text" id="name2" name="name2">
</div>
<div>
<input type="submit" id="submitButton" name="submitButton" value="Submit">
</div>
</form>
<div id="result"></div>
_x000D_
From jQuery website $.post
documentation.
Example: Send form data using ajax requests
$.post("test.php", $("#testform").serialize());
Example: Post a form using ajax and put results in a div
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<form action="/" id="searchForm">
<input type="text" name="s" placeholder="Search..." />
<input type="submit" value="Search" />
</form>
<!-- the result of the search will be rendered inside this div -->
<div id="result"></div>
<script>
/* attach a submit handler to the form */
$("#searchForm").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $(this),
term = $form.find('input[name="s"]').val(),
url = $form.attr('action');
/* Send the data using post */
var posting = $.post(url, {
s: term
});
/* Put the results in a div */
posting.done(function(data) {
var content = $(data).find('#content');
$("#result").empty().append(content);
});
});
</script>
</body>
</html>
Without using OAuth or at minimum HTTPS (TLS/SSL) please don't use this method for secure data (credit card numbers, SSN, anything that is PCI, HIPAA, or login related)
(NOT on Windows!)
This made me tear my hair out for a week, so I hope this will help someone
I tried everything short of re-installing Anaconda and/or Jupyter.
Setup
./anaconda3/bin/python
)/usr/bin/python
and /usr/bin/python3
(but these were not being used as most of the work was done in Jupyter's terminal)Fix
In Jupyter's terminal:
cp /usr/lib64/libssl.so.10 ./anaconda3/lib/libssl.so.1.0.0
cp /usr/lib64/libcrypto.so.10 ./anaconda3/lib/libcrypto.so.1.0.0
What triggered this?
So, this was all working until I tried to do a conda install conda-forge
I'm not sure what happened, but conda must have updated openssl
on the box (I'm guessing) so after this, everything broke.
Basically, unknown to me, conda had updated openssl, but somehow deleted the old libraries and replaced it with libssl.so.1.1
and libcrypto.so.1.1
.
Python3, I guess, was compiled to look for libssl.so.1.0.0
In the end, the key to diagnosis was this:
python -c "import ssl; print (ssl.OPENSSL_VERSION)"
gave the clue library "libssl.so.1.0.0" not found
The huge assumption I made is that the yum
version of ssl is the same as the conda
version, so just renaming the shared object might work, and it did.
My other solution was to re-compile python, re-install anaconda, etc, but in the end I'm glad I didn't need to.
Hope this helps you guys out.
You can make the springboot application to write the PID into file and you can use the pid file to stop or restart or get the status using a bash script. To write the PID to a file, register a listener to SpringApplication using ApplicationPidFileWriter as shown below :
SpringApplication application = new SpringApplication(Application.class);
application.addListeners(new ApplicationPidFileWriter("./bin/app.pid"));
application.run();
Then write a bash script to run the spring boot application . Reference.
Now you can use the script to start,stop or restart.
SHA doesn't require anything but an input to be applied, while AES requires at least 3 things - what you're encrypting/decrypting, an encryption key, and the initialization vector.
This might help...
test_list = [5, 8]
test_list[0] = None
print test_list
#prints [None, 8]
Try the line below to convert editText to integer.
int intVal = Integer.parseInt(mEtValue.getText().toString());
To generate a shared library you need first to compile your C code with the -fPIC
(position independent code) flag.
gcc -c -fPIC hello.c -o hello.o
This will generate an object file (.o), now you take it and create the .so file:
gcc hello.o -shared -o libhello.so
EDIT: Suggestions from the comments:
You can use
gcc -shared -o libhello.so -fPIC hello.c
to do it in one step. – Jonathan Leffler
I also suggest to add -Wall
to get all warnings, and -g
to get debugging information, to your gcc
commands. – Basile Starynkevitch
This will work:
let item = tableView.cellForRowAtIndexPath(indexPath)!.textLabel!.text!
Looks like a regular expression is the way to go:
var isInt = /^\+?\d+$/.test('the string');
The correct solution for this problem is to use display: table-cell
Important: This solution doesn't need float
since table-cell
already turns the div
into an element that lines up with the others in the same container. That also means you don't have to worry about clearing floats, overflow, background shining through and all the other nasty surprises that the float
hack brings along to the party.
CSS:
.container {
display: table;
}
.column {
display: table-cell;
width: 100px;
}
HTML:
<div class="container">
<div class="column">Column 1.</div>
<div class="column">Column 2 is a bit longer.</div>
<div class="column">Column 3 is longer with lots of text in it.</div>
</div>
Related:
Could someone tell me what I'm doing wrong?"
"bold" has never been an HTML element ("b" is the closest match).
HTML should contain structured content; publisher CSS should suggest styles for that content. That way user agents can expose the structured content with useful styling and navigational controls to users who can't see your suggested bold styling (e.g. users of search engines, totally blind users using screen readers, poorly sighted users using their own colors and fonts, geeky users using text browsers, users of voice-controlled, speaking browsers like Opera for Windows). Thus the right way to make text bold depends on why you want to style it bold. For example:
Want to distinguish headings from other text? Use heading elements ("h1" to "h6") and suggest a bold style for them within your CSS ("h1, h2, h3, h4, h5, h6 {font-weight: bold;}".
Want to embolden labels for form fields? Use a "label" element, programmatically associate it with the the relevant "select", "input" or "textarea" element by giving it a "for" attribute matching an "id" attribute on the target, and suggest a bold style for it within your CSS ("label {font-weight: bold;"}).
Want to embolden a heading for a group of related fields in a form, such as a group of radio choices? Surround them with a "fieldset" element, give it a "legend" element, and suggest a bold style for it within your CSS ("legend {font-weight: bold;}").
Want to distinguish a table caption from the table it captions? Use a "caption" element and suggest a bold style for it within your CSS ("caption {font-weight: bold;}").
Want to distinguish table headings from table data cells? Use a "th" element and suggest a bold style for it within your CSS ("th {font-weight: bold;}").
Want to distinguish the title of a referenced film or album from surrounding text? Use a "cite" element with a class ("cite class="movie-title"), and suggest a bold style for it within your CSS (".movie-title {font-weight: bold;}").
Want to distinguish a defined keyword from the surrounding text defining or explaining it? Use a "dfn" element and suggest a bold style for it within your CSS ("dfn {font-weight: bold;}").
Want to distinguish some computer code from surrounding text? Use a "code" element and suggest a bold style for it within your CSS ("code {font-weight: bold;}").
Want to distinguish a variable name from surrounding text? Use a "var" element and suggest a bold style for it within your CSS ("var {font-weight: bold;}").
Want to indicate that some text has been added as an update? Use an "ins" element and suggest a bold style for it within your CSS ("ins {font-weight: bold;}").
Want to lightly stress some text ("I love kittens!")? Use an "em" element and suggest a bold style for it within your CSS (e.g. "em {font-weight: bold;}").
Want to heavily stress some text, perhaps for a warning ("Beware the dog!")? Use a "strong" element and suggest a bold style for it within your CSS (e.g. "strong {font-weight: bold;}").
… You get the idea (hopefully).
Can't find an HTML element with the right semantics to express /why/ you want to make this particular text bold? Wrap it in a generic "span" element, give it a meaningful class name that expresses your rationale for distinguishing that text ("<span class="lede">Let me begin this news article with a sentence that summarizes it.</span>), and suggest a bold style for it within your CSS (".lede {font-weight: bold;"}. Before making up your own class names, you might want to check if there's a microformat (microformats.org) or common convention for what you want to express.
For Windows 7 (Professional, 64-bit - can't speak for the others) I see that REG no longer spits out
! REG.EXE VERSION 3.0
as it does in XP. So the above needs to be modified to use
skip=2
instead of 4 - which makes things messy if you want your script to be portable. Although it's much more heavyweight and complex, a WMIC based solution may be better.
This selects all DIVs with an ID containing 'foo' and that are visible
$("div:visible[id*='foo']");
next
and break
seem to do the correct thing in this simplified example!
class Bar
def self.do_things
Foo.some_method(1..10) do |x|
next if x == 2
break if x == 9
print "#{x} "
end
end
end
class Foo
def self.some_method(targets, &block)
targets.each do |target|
begin
r = yield(target)
rescue => x
puts "rescue #{x}"
end
end
end
end
Bar.do_things
output: 1 3 4 5 6 7 8
The app router specified navigation to MyController
like so:
$routeProvider.when('/',
{ templateUrl: 'pages/home.html',
controller: MyController });
But I also had this in home.html
:
<div data-ng-controller="MyController">
This digested the controller twice. Removing the data-ng-controller
attribute from the HTML resolved the issue. Alternatively, the controller:
property could have been removed from the routing directive.
This problem also appears when using tabbed navigation. For example, app.js
might contain:
.state('tab.reports', {
url: '/reports',
views: {
'tab-reports': {
templateUrl: 'templates/tab-reports.html',
controller: 'ReportsCtrl'
}
}
})
The corresponding reports tab HTML might resemble:
<ion-view view-title="Reports">
<ion-content ng-controller="ReportsCtrl">
This will also result in running the controller twice.
As @samwize pointed out, the way of paginating is by using
setViewControllers:array
Here's the way I did it: I have my datasource and the delegate separate. You can call this method and only change the "next" view. Previously you have to apply the paging rules. That is, you have to check direction and the next controller. If you use that method with your custom datasource the array of controllers that you're displaying won't change (since you'll use a custom array on a NSObject subclass).
Using your own datasource the method just sets a new view (with specific direction). Since you will still controll the pages that will display when normally swiping.
you can also use flask_api for sending response
from flask_api import status
@app.route('/your-api/')
def empty_view(self):
content = {'your content here'}
return content, status.HTTP_201_CREATED
you can find reference here http://www.flaskapi.org/api-guide/status-codes/
You should be able to do this quite easily:
SELECT *
FROM WebPageContent
WHERE data.value('(/PageContent/Text)[1]', 'varchar(100)') LIKE 'XYZ%'
The .value
method gives you the actual value, and you can define that to be returned as a VARCHAR(), which you can then check with a LIKE statement.
Mind you, this isn't going to be awfully fast. So if you have certain fields in your XML that you need to inspect a lot, you could:
With this, you'd basically "extract" a certain portion of the XML into a computed field, make it persisted, and then you can search very efficiently on it (heck: you can even INDEX that field!).
Marc
I fixed this by running a clean of by gradle build (or delete the gradle build folder mannually)
This occurs if you move the main class to a new package and the old main class is still referenced in the claspath
When you override the init you have also to call the init of the parent class
super(Num2, self).__init__(num)
This is item A.1 in the RMI FAQ. You need to either fix your /etc/hosts file or set the java.rmi.server.hostname
property at the server.
You will want to have a look at setInterval() and setTimeout().
Here is a decent tutorial article.
A little late but this could help: http://webdesign.tutsplus.com/tutorials/how-to-make-responsive-scrollable-panels-with-flexbox--cms-23269
Basically you need to put html
,body
to height: 100%;
and wrap all your content into a <div class="wrap"> <!-- content --> </div>
CSS:
html, body {
height: 100%;
}
.wrap {
height: 100vh;
display: flex;
}
Worked for me. Hope it helps
You can use a closure for this:
func doif(b bool, f1, f2 func()) {
switch{
case b:
f1()
case !b:
f2()
}
}
func dothis() { fmt.Println("Condition is true") }
func dothat() { fmt.Println("Condition is false") }
func main () {
condition := true
doif(condition, func() { dothis() }, func() { dothat() })
}
The only gripe I have with the closure syntax in Go is there is no alias for the default zero parameter zero return function, then it would be much nicer (think like how you declare map, array and slice literals with just a type name).
Or even the shorter version, as a commenter just suggested:
func doif(b bool, f1, f2 func()) {
switch{
case b:
f1()
case !b:
f2()
}
}
func dothis() { fmt.Println("Condition is true") }
func dothat() { fmt.Println("Condition is false") }
func main () {
condition := true
doif(condition, dothis, dothat)
}
You would still need to use a closure if you needed to give parameters to the functions. This could be obviated in the case of passing methods rather than just functions I think, where the parameters are the struct associated with the methods.
You may use also
select * from pg_tables where schemaname = 'information_schema'
In generall pg* tables allow you to see everything in the db, not constrained to your permissions (if you have access to the tables of course).
I have found that using backticks to capture command output into a variable, adversly, yeilds one too many ps aux results, e.g. for a single running instance of abc.sh:
ps aux | grep -w "abc.sh" | grep -v grep | wc -l
returns "1". However,
count=`ps aux | grep -w "abc.sh" | grep -v grep | wc -l`
echo $count
returns "2"
Seems like using the backtick construction somehow temporarily creates another process. Could be the reason why the topicstarter could not make this work. Just need to decrement the $count var.
I don't think answer from Vincent Malgrat is correct. When NVARCHAR2
was introduced long time ago nobody was even talking about Unicode.
Initially Oracle provided VARCHAR2
and NVARCHAR2
to support localization. Common data (include PL/SQL) was hold in VARCHAR2
, most likely US7ASCII
these days. Then you could apply NLS_NCHAR_CHARACTERSET
individually (e.g. WE8ISO8859P1
) for each of your customer in any country without touching the common part of your application.
Nowadays character set AL32UTF8
is the default which fully supports Unicode. In my opinion today there is no reason anymore to use NLS_NCHAR_CHARACTERSET
, i.e. NVARCHAR2
, NCHAR2
, NCLOB
. Note, there are more and more Oracle native functions which do not support NVARCHAR2, so you should really avoid it. Maybe the only reason is when you have to support mainly Asian characters where AL16UTF16
consumes less storage compared to AL32UTF8
.
To stop the user from getting annoyed when the whole text gets selected every time they try to move the caret using their mouse, you should do this using the focus
event, not the click
event. The following will do the job and works around a problem in Chrome that prevents the simplest version (i.e. just calling the textarea's select()
method in a focus
event handler) from working.
jsFiddle: http://jsfiddle.net/NM62A/
Code:
<textarea id="foo">Some text</textarea>
<script type="text/javascript">
var textBox = document.getElementById("foo");
textBox.onfocus = function() {
textBox.select();
// Work around Chrome's little problem
textBox.onmouseup = function() {
// Prevent further mouseup intervention
textBox.onmouseup = null;
return false;
};
};
</script>
jQuery version:
$("#foo").focus(function() {
var $this = $(this);
$this.select();
// Work around Chrome's little problem
$this.mouseup(function() {
// Prevent further mouseup intervention
$this.unbind("mouseup");
return false;
});
});
Same thing but in ANSI way
SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME IN ( SELECT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME = 'CreateDate' )
This is what I did on windows.
openssl x509 -outform der -in yourPemFilename.pem -out certfileOutName.crt
openssl rsa -in yourPemFilename.pem -out keyfileOutName.key
$('#myLink').click(function(e) {
e.preventDefault();
//do other stuff when a click happens
});
That will prevent the default behaviour of a hyperlink, which is to visit the specified href.
From the jQuery tutorial:
For click and most other events, you can prevent the default behaviour - here, following the link to jquery.com - by calling event.preventDefault() in the event handler
If you want to preventDefault()
only if a certain condition is fulfilled (something is hidden for instance), you could test the visibility of your ul with the class expanded. If it is visible (i.e. not hidden) the link should fire as normal, as the if statement will not be entered, and thus the default behaviour will not be prevented:
$('ul li').click(function(e) {
if($('ul.expanded').is(':hidden')) {
e.preventDefault();
$('ul').addClass('expanded');
$('ul.expanded').fadeIn(300);
}
});
Command Should be hadoop fs -du -s -h \dirPath
-du [-s] [-h] ... : Show the amount of space, in bytes, used by the files that match the specified file pattern.
-s : Rather than showing the size of each individual file that matches the
pattern, shows the total (summary) size.
-h : Formats the sizes of files in a human-readable fashion rather than a number of bytes. (Ex MB/GB/TB etc)
Note that, even without the -s option, this only shows size summaries one level deep into a directory.
The output is in the form size name(full path)
Maybe you'd find Redux suiting your needs. It's no overkill and comes packed solely with bare features most of us would require. The dev and contributors were very strict on what code was contributed.
This is the official page
Something like this might work for you:
"UPDATE myTable SET ... ;
UPDATE myTable SET ... ;
UPDATE myTable SET ... ;
UPDATE myTable SET ... ;"
If any of the posX or posY values are the same, then they could be combined into one query
UPDATE myTable SET posX='39' WHERE id IN('2','3','40');
The ToString
function has many overloads - the method group would be the group consisting of all the different overloads for that function.
Assuming there is nothing else alongside the image, the best way is to use text-align: center
in the img
parent:
.row .span4 {
text-align: center;
}
Edit
As mentioned in the other answers, you can add the bootstrap CSS class .text-center
to the parent element. This does exactly the same thing and is available in both v2.3.3 and v3
For me the error was caused by wrong type hint of url string. I used:
export class TodoService {
apiUrl: String = 'https://jsonplaceholder.typicode.com/todos' // wrong uppercase String
constructor(private httpClient: HttpClient) { }
getTodos(): Observable<Todo[]> {
return this.httpClient.get<Todo[]>(this.apiUrl)
}
}
where I should have used
export class TodoService {
apiUrl: string = 'https://jsonplaceholder.typicode.com/todos' // lowercase string!
constructor(private httpClient: HttpClient) { }
getTodos(): Observable<Todo[]> {
return this.httpClient.get<Todo[]>(this.apiUrl)
}
}
this function will set the prompt location to script path, dealing with the differents way to get scriptpath between vscode, psise and pwd :
function Set-CurrentLocation
{
$currentPath = $PSScriptRoot # AzureDevOps, Powershell
if (!$currentPath) { $currentPath = Split-Path $pseditor.GetEditorContext().CurrentFile.Path -ErrorAction SilentlyContinue } # VSCode
if (!$currentPath) { $currentPath = Split-Path $psISE.CurrentFile.FullPath -ErrorAction SilentlyContinue } # PsISE
if ($currentPath) { Set-Location $currentPath }
}
I recently used the following in an application that is working well for my needs.
.htaccess
<IfModule mod_rewrite.c>
# enable rewrite engine
RewriteEngine On
# if requested url does not exist pass it as path info to index.php
RewriteRule ^$ index.php?/ [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) index.php?/$1 [QSA,L]
</IfModule>
index.php
foreach (explode ("/", $_SERVER['REQUEST_URI']) as $part)
{
// Figure out what you want to do with the URL parts.
}
@Vigril Disgr4ce
When it comes to multi field forms, it makes sense to use React's key feature: components.
In my projects, I create TextField components, that take a value prop at minimum, and it takes care of handling common behaviors of an input text field. This way you don't have to worry about keeping track of field names when updating the value state.
[...]
handleChange: function(event) {
this.setState({value: event.target.value});
},
render: function() {
var value = this.state.value;
return <input type="text" value={value} onChange={this.handleChange} />;
}
[...]
If it is giving you relay access denied when you are trying to send an email from outside your network to a domain that your server is not authoritative for then it means your receive connector does not grant you the permissions for sending/relaying. Most likely what you need to do is to authenticate to the server to be granted the permissions for relaying but that does depend upon the configuration of your receive connector. In Exchange 2007/2010/2013 you would need to enable ExchangeUsers permission group as well as an authentication mechanism such as Basic authentication.
Once you're sure your receive connector is configured make sure your email client is configured for authentication as well for the SMTP server. It depends upon your server setup but normally for Exchange you would configure the username by itself, no need for the domain to appended or prefixed to it.
To test things out with authentication via telnet you can go over my post here for directions: https://jefferyland.wordpress.com/2013/05/28/essential-exchange-troubleshooting-send-email-via-telnet/
Try:
var selectedVal;
for( i = 0; i < document.form_name.gender.length; i++ )
{
if(document.form_name.gender[i].checked)
selectedVal = document.form_name.gender[i].value; //male or female
break;
}
}
Factory
and Service
is a just wrapper of a provider
.
Factory
Factory
can return anything which can be a class(constructor function)
, instance of class
, string
, number
or boolean
. If you return a constructor
function, you can instantiate in your controller.
myApp.factory('myFactory', function () {
// any logic here..
// Return any thing. Here it is object
return {
name: 'Joe'
}
}
Service
Service does not need to return anything. But you have to assign everything in this
variable. Because service will create instance by default and use that as a base object.
myApp.service('myService', function () {
// any logic here..
this.name = 'Joe';
}
Actual angularjs code behind the service
function service(name, constructor) {
return factory(name, ['$injector', function($injector) {
return $injector.instantiate(constructor);
}]);
}
It just a wrapper around the factory
. If you return something from service
, then it will behave like Factory
.
IMPORTANT
: The return result from Factory and Service will be cache and same will be returned for all controllers.
When should i use them?
Factory
is mostly preferable in all cases. It can be used when you have constructor
function which needs to be instantiated in different controllers.
Service
is a kind of Singleton
Object. The Object return from Service will be same for all controller. It can be used when you want to have single object for entire application.
Eg: Authenticated user details.
For further understanding, read
http://iffycan.blogspot.in/2013/05/angular-service-or-factory.html
http://viralpatel.net/blogs/angularjs-service-factory-tutorial/
There are several ways to get the file name and extension. You can use the following one which is easy to use.
$url = 'http://www.nepaltraveldoor.com/images/trekking/nepal/annapurna-region/Annapurna-region-trekking.jpg';
$file = file_get_contents($url); // To get file
$name = basename($url); // To get file name
$ext = pathinfo($url, PATHINFO_EXTENSION); // To get extension
$name2 =pathinfo($url, PATHINFO_FILENAME); // File name without extension
Cookies:
Local Storage:
Even more meaningful :
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
// ...
verify(dependency, never()).someMethod();
The documentation of this feature is there §4 "Verifying exact number of invocations / at least x / never", and the never
javadoc is here.
run configuration -> arguments -> vm arguments
(can also be placed in the debug configuration under Debug Configuration->Arguments->VM Arguments)
location.href = "Pagename.html";
You can try using set operations: MINUS
and INTERSECT
See here for more details:
O'Reilly - Mastering Oracle SQL - Chapter 7 - Set Operations
The following statement appends the value to the element with the id of response
$('#response').append(total);
This makes it look like you are concatenating the strings, but you aren't, you're actually appending them to the element
change that to
$('#response').text(total);
You need to change the drop event so that it replaces the value of the element with the total, you also need to keep track of what the total is, I suggest something like the following
$(function() {
var data = [];
var total = 0;
$( "#draggable1" ).draggable();
$( "#draggable2" ).draggable();
$( "#draggable3" ).draggable();
$("#droppable_box").droppable({
drop: function(event, ui) {
var currentId = $(ui.draggable).attr('id');
data.push($(ui.draggable).attr('id'));
if(currentId == "draggable1"){
var myInt1 = parseFloat($('#MealplanCalsPerServing1').val());
}
if(currentId == "draggable2"){
var myInt2 = parseFloat($('#MealplanCalsPerServing2').val());
}
if(currentId == "draggable3"){
var myInt3 = parseFloat($('#MealplanCalsPerServing3').val());
}
if ( typeof myInt1 === 'undefined' || !myInt1 ) {
myInt1 = parseInt(0);
}
if ( typeof myInt2 === 'undefined' || !myInt2){
myInt2 = parseInt(0);
}
if ( typeof myInt3 === 'undefined' || !myInt3){
myInt3 = parseInt(0);
}
total += parseFloat(myInt1 + myInt2 + myInt3);
$('#response').text(total);
}
});
$('#myId').click(function(event) {
$.post("process.php", ({ id: data }), function(return_data, status) {
alert(data);
//alert(total);
});
});
});
I moved the var total = 0;
statement out of the drop event and changed the assignment statment from this
total = parseFloat(myInt1 + myInt2 + myInt3);
to this
total += parseFloat(myInt1 + myInt2 + myInt3);
Here is a working example http://jsfiddle.net/axrwkr/RCzGn/
1. Installing OpenCV 2.4.3
First, get OpenCV 2.4.3 from sourceforge.net. Its a self-extracting so just double click to start the installation. Install it in a directory, say C:\
.
Wait until all files get extracted. It will create a new directory C:\opencv
which
contains OpenCV header files, libraries, code samples, etc.
Now you need to add the directory C:\opencv\build\x86\vc10\bin
to your system PATH. This directory contains OpenCV DLLs required for running your code.
Open Control Panel → System → Advanced system settings → Advanced Tab → Environment variables...
On the System Variables section, select Path (1), Edit (2), and type C:\opencv\build\x86\vc10\bin;
(3), then click Ok.
On some computers, you may need to restart your computer for the system to recognize the environment path variables.
This will completes the OpenCV 2.4.3 installation on your computer.
2. Create a new project and set up Visual C++
Open Visual C++ and select File → New → Project... → Visual C++ → Empty Project. Give a name for your project (e.g: cvtest
) and set the project location (e.g: c:\projects
).
Click Ok. Visual C++ will create an empty project.
Make sure that "Debug" is selected in the solution configuration combobox. Right-click cvtest
and select Properties → VC++ Directories.
Select Include Directories to add a new entry and type C:\opencv\build\include
.
Click Ok to close the dialog.
Back to the Property dialog, select Library Directories to add a new entry and type C:\opencv\build\x86\vc10\lib
.
Click Ok to close the dialog.
Back to the property dialog, select Linker → Input → Additional Dependencies to add new entries. On the popup dialog, type the files below:
opencv_calib3d243d.lib
opencv_contrib243d.lib
opencv_core243d.lib
opencv_features2d243d.lib
opencv_flann243d.lib
opencv_gpu243d.lib
opencv_haartraining_engined.lib
opencv_highgui243d.lib
opencv_imgproc243d.lib
opencv_legacy243d.lib
opencv_ml243d.lib
opencv_nonfree243d.lib
opencv_objdetect243d.lib
opencv_photo243d.lib
opencv_stitching243d.lib
opencv_ts243d.lib
opencv_video243d.lib
opencv_videostab243d.lib
Note that the filenames end with "d" (for "debug"). Also note that if you have installed another version of OpenCV (say 2.4.9) these filenames will end with 249d instead of 243d (opencv_core249d.lib..etc).
Click Ok to close the dialog. Click Ok on the project properties dialog to save all settings.
NOTE:
These steps will configure Visual C++ for the "Debug" solution. For "Release" solution (optional), you need to repeat adding the OpenCV directories and in Additional Dependencies section, use:
opencv_core243.lib
opencv_imgproc243.lib
...
instead of:
opencv_core243d.lib
opencv_imgproc243d.lib
...
You've done setting up Visual C++, now is the time to write the real code. Right click your project and select Add → New Item... → Visual C++ → C++ File.
Name your file (e.g: loadimg.cpp
) and click Ok. Type the code below in the editor:
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
Mat im = imread("c:/full/path/to/lena.jpg");
if (im.empty())
{
cout << "Cannot load image!" << endl;
return -1;
}
imshow("Image", im);
waitKey(0);
}
The code above will load c:\full\path\to\lena.jpg
and display the image. You can
use any image you like, just make sure the path to the image is correct.
Type F5 to compile the code, and it will display the image in a nice window.
And that is your first OpenCV program!
3. Where to go from here?
Now that your OpenCV environment is ready, what's next?
c:\opencv\samples\cpp
.All special, nonprintable characters are displayed using ^ notation in less. However, line feed is actually printable (just make a new line), so not considered special, so you'll have problems replacing it. If you just want to see line endings, the easiest way might be
sed -e 's/$/$/' | less
The quickest fix is upgrate the pip. Did worked for me:
pip install --upgrade pip
The answers provided here only convert array to XML with nodes, you are not able to set attributes. I have written a php function that allows you to convert an array to php and also set attributes for particular nodes in the xml. The downside here is you have to construct an array in a particular way with few conventions (only if you want to use attributes)
The following example will allow you to set attributes in XML too.
The source can be found here: https://github.com/digitickets/lalit/blob/master/src/Array2XML.php
<?php
$books = array(
'@attributes' => array(
'type' => 'fiction'
),
'book' => array(
array(
'@attributes' => array(
'author' => 'George Orwell'
),
'title' => '1984'
),
array(
'@attributes' => array(
'author' => 'Isaac Asimov'
),
'title' => 'Foundation',
'price' => '$15.61'
),
array(
'@attributes' => array(
'author' => 'Robert A Heinlein'
),
'title' => 'Stranger in a Strange Land',
'price' => array(
'@attributes' => array(
'discount' => '10%'
),
'@value' => '$18.00'
)
)
)
);
/* creates
<books type="fiction">
<book author="George Orwell">
<title>1984</title>
</book>
<book author="Isaac Asimov">
<title>Foundation</title>
<price>$15.61</price>
</book>
<book author="Robert A Heinlein">
<title>Stranger in a Strange Land</title>
<price discount="10%">$18.00</price>
</book>
</books>
*/
?>
for( $i =0; $i < sizeof($allUsers); $i++)
{
$NEEDLE1='firstname';
$NEEDLE2='emailAddress';
$sterm='Tofind';
if(isset($allUsers[$i][$NEEDLE1]) && isset($allUsers[$i][$NEEDLE2])
{
$Fname= $allUsers[$i][$NEEDLE1];
$Lname= $allUsers[$i][$NEEDLE2];
$pos1 = stripos($Fname, $sterm);
$pos2=stripos($Lname, $sterm);//not case sensitive
if($pos1 !== false ||$pos2 !== false)
{$resultsMatched[] =$allUsers[$i];}
else
{ continue;}
}
}
Print_r($resultsMatched); //will give array for matched values even partially matched
With help of above code one can find any(partially matched) data from any column in 2D array so user id can be found as required in question.
On Mac 10.14, the header files don't seem to be installed in the correct place. Rather than changing paths like the other fixes, I was able to just run this:
open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg
Follow the instructions and it resolved this problem for me.
For a simple two- (or one) liner this code can be:
checkboxes = document.getElementsByName("NameOfCheckboxes");
selectedCboxes = Array.prototype.slice.call(checkboxes).filter(ch => ch.checked==true);
Here the Array.prototype.slice.call()
part converts the object NodeList of all the checkboxes holding that name ("NameOfCheckboxes") into a new array, on which you then use the filter method. You can then also, for example, extract the values of the checkboxes by adding a .map(ch => ch.value)
on the end of line 2.
The => is javascript's arrow function notation.
Hover over the nav items to see that they activate on hover. http://cameronspear.com/demos/twitter-bootstrap-hover-dropdown/#
There are several different ways to achieve this, as shown by the variety of answers on this question.
To actually assign the listener to the view, you use the same methods as you would in Java:
button.setOnClickListener()
However, Kotlin makes it easy to assign a lambda as a listener:
button.onSetClickListener {
// Listener code
}
Alternatively, if you want to use this listener for multiple views, consider a lambda expression (a lambda assigned to a variable/value for reference):
val buttonClickListener = View.OnClickListener { view ->
// Listener code
}
button.setOnClickListener(buttonClickListener)
another_button.setOnClickListener(buttonClickListener)
This particular error implies that one of the variables being used in the arithmetic on the line has a shape incompatible with another on the same line (i.e., both different and non-scalar). Since n
and the output of np.add.reduce()
are both scalars, this implies that the problem lies with xm
and ym
, the two of which are simply your x
and y
inputs minus their respective means.
Based on this, my guess is that your x
and y
inputs have different shapes from one another, making them incompatible for element-wise multiplication.
** Technically, it's not that variables on the same line have incompatible shapes. The only problem is when two variables being added, multiplied, etc., have incompatible shapes, whether the variables are temporary (e.g., function output) or not. Two variables with different shapes on the same line are fine as long as something else corrects the issue before the mathematical expression is evaluated.
Yes. In your login
module, just export a single function that takes the db
as its argument. For example:
module.exports = function(db) {
...
};
I would prefer to make a function that doesn't work with strings:
'---------------------------------------------------------------------------------------
' Procedure : RemoveTimeFromDate
' Author : berend.nieuwhof
' Date : 15-8-2013
' Purpose : removes the time part of a String and returns the date as a date
'---------------------------------------------------------------------------------------
'
Public Function RemoveTimeFromDate(DateTime As Date) As Date
Dim dblNumber As Double
RemoveTimeFromDate = CDate(Floor(CDbl(DateTime)))
End Function
Private Function Floor(ByVal x As Double, Optional ByVal Factor As Double = 1) As Double
Floor = Int(x / Factor) * Factor
End Function
\df <schema>.*
in psql
gives the necessary information.
To see the query that's used internally connect to a database with psql
and supply an extra "-E
" (or "--echo-hidden
") option and then execute the above command.
All the current answers assume that it is okay to pull the entire JSON into memory where the advantage of an InputStream is that you can read the input little by little. If you would like to avoid reading the entire Json file at once then I would suggest using the Jackson library (which is my personal favorite but I'm sure others like Gson have similar functions).
With Jackson you can use a JsonParser to read one section at a time. Below is an example of code I wrote that wraps the reading of an Array of JsonObjects in an Iterator. If you just want to see an example of Jackson, look at the initJsonParser, initFirstElement, and initNextObject methods.
public class JsonObjectIterator implements Iterator<Map<String, Object>>, Closeable {
private static final Logger LOG = LoggerFactory.getLogger(JsonObjectIterator.class);
private final InputStream inputStream;
private JsonParser jsonParser;
private boolean isInitialized;
private Map<String, Object> nextObject;
public JsonObjectIterator(final InputStream inputStream) {
this.inputStream = inputStream;
this.isInitialized = false;
this.nextObject = null;
}
private void init() {
this.initJsonParser();
this.initFirstElement();
this.isInitialized = true;
}
private void initJsonParser() {
final ObjectMapper objectMapper = new ObjectMapper();
final JsonFactory jsonFactory = objectMapper.getFactory();
try {
this.jsonParser = jsonFactory.createParser(inputStream);
} catch (final IOException e) {
LOG.error("There was a problem setting up the JsonParser: " + e.getMessage(), e);
throw new RuntimeException("There was a problem setting up the JsonParser: " + e.getMessage(), e);
}
}
private void initFirstElement() {
try {
// Check that the first element is the start of an array
final JsonToken arrayStartToken = this.jsonParser.nextToken();
if (arrayStartToken != JsonToken.START_ARRAY) {
throw new IllegalStateException("The first element of the Json structure was expected to be a start array token, but it was: " + arrayStartToken);
}
// Initialize the first object
this.initNextObject();
} catch (final Exception e) {
LOG.error("There was a problem initializing the first element of the Json Structure: " + e.getMessage(), e);
throw new RuntimeException("There was a problem initializing the first element of the Json Structure: " + e.getMessage(), e);
}
}
private void initNextObject() {
try {
final JsonToken nextToken = this.jsonParser.nextToken();
// Check for the end of the array which will mean we're done
if (nextToken == JsonToken.END_ARRAY) {
this.nextObject = null;
return;
}
// Make sure the next token is the start of an object
if (nextToken != JsonToken.START_OBJECT) {
throw new IllegalStateException("The next token of Json structure was expected to be a start object token, but it was: " + nextToken);
}
// Get the next product and make sure it's not null
this.nextObject = this.jsonParser.readValueAs(new TypeReference<Map<String, Object>>() { });
if (this.nextObject == null) {
throw new IllegalStateException("The next parsed object of the Json structure was null");
}
} catch (final Exception e) {
LOG.error("There was a problem initializing the next Object: " + e.getMessage(), e);
throw new RuntimeException("There was a problem initializing the next Object: " + e.getMessage(), e);
}
}
@Override
public boolean hasNext() {
if (!this.isInitialized) {
this.init();
}
return this.nextObject != null;
}
@Override
public Map<String, Object> next() {
// This method will return the current object and initialize the next object so hasNext will always have knowledge of the current state
// Makes sure we're initialized first
if (!this.isInitialized) {
this.init();
}
// Store the current next object for return
final Map<String, Object> currentNextObject = this.nextObject;
// Initialize the next object
this.initNextObject();
return currentNextObject;
}
@Override
public void close() throws IOException {
IOUtils.closeQuietly(this.jsonParser);
IOUtils.closeQuietly(this.inputStream);
}
}
If you don't care about memory usage, then it would certainly be easier to read the entire file and parse it as one big Json as mentioned in other answers.
After changing main port from 80 to 8080 you have to change the config in XAMPP control panel as I show in the images:
Then restart the service and that's it !
SELECT CONVERT(NVARCHAR(32),HashBytes('MD5', 'Hello World'),2)
Sharing a few functions which I created for dates:
Please note that I wanted to get time for a particular location (not just UTC time). If you want UTC time, just remove loc variable and .In(loc) function call.
func GetTimeStamp() string {
loc, _ := time.LoadLocation("America/Los_Angeles")
t := time.Now().In(loc)
return t.Format("20060102150405")
}
func GetTodaysDate() string {
loc, _ := time.LoadLocation("America/Los_Angeles")
current_time := time.Now().In(loc)
return current_time.Format("2006-01-02")
}
func GetTodaysDateTime() string {
loc, _ := time.LoadLocation("America/Los_Angeles")
current_time := time.Now().In(loc)
return current_time.Format("2006-01-02 15:04:05")
}
func GetTodaysDateTimeFormatted() string {
loc, _ := time.LoadLocation("America/Los_Angeles")
current_time := time.Now().In(loc)
return current_time.Format("Jan 2, 2006 at 3:04 PM")
}
func GetTimeStampFromDate(dtformat string) string {
form := "Jan 2, 2006 at 3:04 PM"
t2, _ := time.Parse(form, dtformat)
return t2.Format("20060102150405")
}
Found an elegant solution:
int pageCount = (records + recordsPerPage - 1) / recordsPerPage;
just like user hcpl said but if you want to not worry about the version of the library you can do this:
dependencies {
compile(name:'mylibrary', ext:'aar')
}
as its kind of annoying to have to update the version everytime. Also it makes the not worrying about the name space easier this way.
Change the port 80 to port 8080 and restart all services and access like localhost:8080/
It will work fine.
I think the correct syntax is:
cmd /k "cd c:\<folder name>"
The easiest way is probably to use xvfb-run:
DISPLAY=:1 xvfb-run java -jar selenium-server-standalone-2.0b3.jar
xvfb-run does the whole X authority dance for you, give it a try!
I had such problem with storage json-string in MySQL. Don't really know why, but using htmlspecialchars_decode berofe json_decode resolved problem.
I had/have this problem too. In my case, none of the explanations applied:
Until I found out that once I accessed the windows folder via another (linux) computer, git worked without complaints. It must have something to do with the git version I use from my normal debian buster computer: git 1.2.20 is giving me the 'unable to write new index' error, whereas from a ubuntu fuzzy virtualbox (git 1.2.2) adds the file without problems.
To ignore an entire directory in Git, the easiest way is to include a .gitignore file within the target directory which simply contains "*".
An illustrative example,
Example System
/root/
.gitignore
/dirA/
someFile1.txt
someFile2.txt
/dirB/
.gitignore
someFile3.txt
someFile4.txt
Goal
Top Level (/root/.gitignore)
Ignored Directory (/root/dirB/.gitignore)
Git watches for gitignore at every step of the file system so anytime you have ignore specifications to apply then toss it in, generating a new gitignore for that dir
dirB/.gitignore then just reads as “*” and all contents are ignored completely, itself and all files!
And it's that simple :)
Yes strings must be quoted and in some cases like in applescript, quotes must be escaped
do JavaScript "document.querySelector('span[" & attrName & "=\"" & attrValue & "\"]').click();"
I have another solution. I just want to test if executing a PowerShell script succeeds, because perhaps somebody might change the policy. As the argument, I just specify the path of the script to be executed.
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = @"powershell.exe";
startInfo.Arguments = @"& 'c:\Scripts\test.ps1'";
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
string output = process.StandardOutput.ReadToEnd();
Assert.IsTrue(output.Contains("StringToBeVerifiedInAUnitTest"));
string errors = process.StandardError.ReadToEnd();
Assert.IsTrue(string.IsNullOrEmpty(errors));
With the contents of the script being:
$someVariable = "StringToBeVerifiedInAUnitTest"
$someVariable
Heres a way to do it for dynamically deep objects in a object oriented way for the newer js versions. you might have to change the seperatortype after region.
private ConvertToCSV(objArray) {
let rows = typeof objArray !== "object" ? JSON.parse(objArray) : objArray;
let header = "";
Object.keys(rows[0]).map(pr => (header += pr + ";"));
let str = "";
rows.forEach(row => {
let line = "";
let columns =
typeof row !== "object" ? JSON.parse(row) : Object.values(row);
columns.forEach(column => {
if (line !== "") {
line += ";";
}
if (typeof column === "object") {
line += JSON.stringify(column);
} else {
line += column;
}
});
str += line + "\r\n";
});
return header + "\r\n" + str;
}
Sometimes you might add a state value from props in constructor or componentDidMount, you might need to call setState when the props changed but the component has already mounted so componentDidMount will not execute and neither will constructor; in this particular case, you can use componentDidUpdate since the props have changed, you can call setState in componentDidUpdate with new props.
#include"stdio.h"
#include"conio.h"
#include"time.h"
void main()
{
time_t t;
int i;
srand(time(&t));
for(i=1;i<=10;i++)
printf("%c\t",rand()%10);
getch();
}
Go to server explorer > Your Database > Right Click > properties > ConnectionString and copy the connection string and past the copied to connectiongstring code :)
Maybe it's gotten a little simpler, but below is what I've come up with now in 2017:
class obj {
constructor(in_shape, in_color){
this.shape = in_shape;
this.color = in_color;
}
getInfo(){
return this.shape + ' and ' + this.color;
}
setShape(in_shape){
this.shape = in_shape;
}
setColor(in_color){
this.color = in_color;
}
}
In using the class above, I have the following:
var newobj = new obj('square', 'blue');
//Here, we expect to see 'square and blue'
console.log(newobj.getInfo());
newobj.setColor('white');
newobj.setShape('sphere');
//Since we've set new color and shape, we expect the following: 'sphere and white'
console.log(newobj.getInfo());
As you can see, the constructor takes in two parameters, and we set the object's properties. We also alter the object's color and shape by using the setter
functions, and prove that its change remained upon calling getInfo()
after these changes.
A bit late, but I hope this helps. I've tested this with a mocha
unit-testing, and it's working well.
Example to recieve it through a request:
a) http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.historical
OR
b) http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes
As mentioned by others, Heap can do findMin
or findMax
in O(1) but not both in the same data structure. However I disagree that Heap is better in findMin/findMax. In fact, with a slight modification, the BST can do both findMin
and findMax
in O(1).
In this modified BST, you keep track of the the min node and max node everytime you do an operation that can potentially modify the data structure. For example in insert operation you can check if the min value is larger than the newly inserted value, then assign the min value to the newly added node. The same technique can be applied on the max value. Hence, this BST contain these information which you can retrieve them in O(1). (same as binary heap)
In this BST (Balanced BST), when you pop min
or pop max
, the next min value to be assigned is the successor of the min node, whereas the next max value to be assigned is the predecessor of the max node. Thus it perform in O(1). However we need to re-balance the tree, thus it will still run O(log n). (same as binary heap)
I would be interested to hear your thought in the comment below. Thanks :)
Cross reference to similar question Can we use binary search tree to simulate heap operation? for more discussion on simulating Heap using BST.
I know this is an old question, but I faced the same problem recently in Laravel 7 application.
To make renaming columns work I used a tip from this answer where instead of composer require doctrine/dbal
I have issued composer require doctrine/dbal:^2.12.1
because the latest version of doctrine/dbal still throws an error.
Just keep in mind that if you already use a higher version, this answer might not be appropriate for you.
No, the replacement is:
try:
v
except NameError:
v = 'bla bla'
However, wanting to use this construct is a sign of overly complicated code flow. Usually, you'd do the following:
try:
v = complicated()
except ComplicatedError: # complicated failed
v = 'fallback value'
and never be unsure whether v
is set or not. If it's one of many options that can either be set or not, use a dictionary and its get
method which allows a default value.
If you just need to print present working directory then you can follow this.
$ vim test
#!/bin/bash
pwd
:wq to save the test file.
Give execute permission:
chmod u+x test
Then execute the script by ./test
then you can see the present working directory.
Believing this performance evaluation, the switch case is faster.
This is the conclusion:
The results show that the switch statement is faster to execute than the if-else-if ladder. This is due to the compiler's ability to optimise the switch statement. In the case of the if-else-if ladder, the code must process each if statement in the order determined by the programmer. However, because each case within a switch statement does not rely on earlier cases, the compiler is able to re-order the testing in such a way as to provide the fastest execution.
Signed variables can be 0, positive or negative.
Unsigned variables can be 0 or positive.
Unsigned variables are used sometimes because more bits can be used to represent the actual value. Giving you a larger range. Also you can ensure that a negative value won't be passed to your function for example.
SQL Server databases use two files - an MDF file, known as the primary database file, which contains the schema and data, and a LDF file, which contains the logs. See wikipedia. A database may also use secondary database file, which normally uses a .ndf extension.
As John S. indicates, these file extensions are purely convention - you can use whatever you want, although I can't think of a good reason to do that.
More info on MSDN here and in Beginning SQL Server 2005 Administation (Google Books) here.
That query is failing and returning false
.
Put this after mysqli_query()
to see what's going on.
if (!$check1_res) {
printf("Error: %s\n", mysqli_error($con));
exit();
}
For more information:
To my knowledge, only ENV
allows that, as mentioned in "Environment replacement"
Environment variables (declared with the
ENV
statement) can also be used in certain instructions as variables to be interpreted by the Dockerfile.
They have to be environment variables in order to be redeclared in each new containers created for each line of the Dockerfile by docker build
.
In other words, those variables aren't interpreted directly in a Dockerfile, but in a container created for a Dockerfile line, hence the use of environment variable.
This day, I use both ARG
(docker 1.10+, and docker build --build-arg var=value
) and ENV
.
Using ARG
alone means your variable is visible at build time, not at runtime.
My Dockerfile usually has:
ARG var
ENV var=${var}
In your case, ARG
is enough: I use it typically for setting http_proxy variable, that docker build needs for accessing internet at build time.
This script does the trick! Just paste it into the top of your bat file. If you want to review the output of your script, add a "pause" command at the bottom of your batch file.
UPDATE: This script is now slightly edited to support command line arguments and a 64 bit OS.
Thank you Eneerge @ https://sites.google.com/site/eneerge/scripts/batchgotadmin
@echo off
:: BatchGotAdmin
:-------------------------------------
REM --> Check for permissions
IF "%PROCESSOR_ARCHITECTURE%" EQU "amd64" (
>nul 2>&1 "%SYSTEMROOT%\SysWOW64\cacls.exe" "%SYSTEMROOT%\SysWOW64\config\system"
) ELSE (
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
)
REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
echo Requesting administrative privileges...
goto UACPrompt
) else ( goto gotAdmin )
:UACPrompt
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
set params= %*
echo UAC.ShellExecute "cmd.exe", "/c ""%~s0"" %params:"=""%", "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
exit /B
:gotAdmin
pushd "%CD%"
CD /D "%~dp0"
:--------------------------------------
<YOUR BATCH SCRIPT HERE>
You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:
/**
* Used to stitch together functional operators into a chain.
* @method pipe
* @return {Observable} the Observable result of all of the operators having
* been called in the order they were passed in.
*
* @example
*
* import { map, filter, scan } from 'rxjs/operators';
*
* Rx.Observable.interval(1000)
* .pipe(
* filter(x => x % 2 === 0),
* map(x => x + x),
* scan((acc, x) => acc + x)
* )
* .subscribe(x => console.log(x))
*/
Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan()
, but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe()
to make a chain of those operators (see example above).
Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do()
. You can think of it as if observable was an array over time, then tap()
would be an equivalent to Array.forEach()
.
Try this:
body
{
background:url("images/plaid.jpg") no-repeat fixed center;
}
jsfiddle example: http://jsfiddle.net/Q9Zfa/
Try this since your are using jQuery UI probably (if not please comment)
$("#fModal" ).dialog({
open: function( event, ui ) {
if(//some hidden value check which stores the DB value==expected value for
checking the Checkbox)
$("div.row-form input[type='checkbox']").attr('checked','checked');
}
});
Sample code to differentiate OS's using python:
from sys import platform as _platform
if _platform == "linux" or _platform == "linux2":
# linux
elif _platform == "darwin":
# MAC OS X
elif _platform == "win32":
# Windows
elif _platform == "win64":
# Windows 64-bit
All you have to do is In your bLoanButton_Click , add a line to rebind the Grid to the SqlDataSource :
protected void bLoanButton_Click(object sender, EventArgs e)
{
//your same code
........
GridView1.DataBind();
}
regards
Maybe it's too late, but here it goes.
We can use the attribute EnumMember to manage Enum values.
public enum EUnitOfMeasure
{
[EnumMember(Value = "KM")]
Kilometer,
[EnumMember(Value = "MI")]
Miles
}
This way the result value for EUnitOfMeasure will be KM or MI. This also can be seen in Andrew Whitaker answer.
I created solution based on JSch
library:
import com.google.common.io.CharStreams
import com.jcraft.jsch.ChannelExec
import com.jcraft.jsch.JSch
import com.jcraft.jsch.JSchException
import com.jcraft.jsch.Session
import static java.util.Arrays.asList
class RunCommandViaSsh {
private static final String SSH_HOST = "test.domain.com"
private static final String SSH_LOGIN = "username"
private static final String SSH_PASSWORD = "password"
public static void main() {
System.out.println(runCommand("pwd"))
System.out.println(runCommand("ls -la"));
}
private static List<String> runCommand(String command) {
Session session = setupSshSession();
session.connect();
ChannelExec channel = (ChannelExec) session.openChannel("exec");
try {
channel.setCommand(command);
channel.setInputStream(null);
InputStream output = channel.getInputStream();
channel.connect();
String result = CharStreams.toString(new InputStreamReader(output));
return asList(result.split("\n"));
} catch (JSchException | IOException e) {
closeConnection(channel, session)
throw new RuntimeException(e)
} finally {
closeConnection(channel, session)
}
}
private static Session setupSshSession() {
Session session = new JSch().getSession(SSH_LOGIN, SSH_HOST, 22);
session.setPassword(SSH_PASSWORD);
session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
session.setConfig("StrictHostKeyChecking", "no"); // disable check for RSA key
return session;
}
private static void closeConnection(ChannelExec channel, Session session) {
try {
channel.disconnect()
} catch (Exception ignored) {
}
session.disconnect()
}
}
If you installed with pip, to upgrade you can just use:
pip install --upgrade docker-compose
or as Mariyo states with pip3 explicitly:
pip3 install --upgrade docker-compose
There are already many answers provided for deleting the .svn-directory. But I want to add, that you can avoid these directories from the beginning, if you do an export instead of a checkout:
svn export <url>
I cloned the simple_list_item_1
(Alt + Click) and placed the copy on my res/layout
folder, renamed it to list_white_text.xml
with this contents:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:gravity="center_vertical"
android:textColor="@color/abc_primary_text_material_dark"
android:minHeight="?android:attr/listPreferredItemHeightSmall" />
The android:textColor="@color/abc_primary_text_material_dark"
translates to white on my device.
then in the java
code:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_white_text, myList);
Do you have a bean declared in your context file that has an id of "articleService"? I believe that autowiring matches the id of a bean in your context files with the variable name that you are attempting to Autowire.
Yet another possibility, up to the last note of the OP, is to compare the hashes (SHA
or MD
) of the dicts dumped as JSON. The way hashes are constructed guarantee that if they are equal, the source strings are equal as well. This is very fast and mathematically sound.
import json
import hashlib
def hash_dict(d):
return hashlib.sha1(json.dumps(d, sort_keys=True)).hexdigest()
x = dict(a=1, b=2)
y = dict(a=2, b=2)
z = dict(a=1, b=2)
print(hash_dict(x) == hash_dict(y))
print(hash_dict(x) == hash_dict(z))
I have Had the same issue and the only Solution i found was open Package manager> Select Microsoft and .Net as Package Source and You will install it..
In CodeIgniter you can store your session value as single or also in array format as below:
If you want store any user’s data in session like userId, userName, userContact etc, then you should store in array:
<?php
$this->load->library('session');
$this->session->set_userdata(array(
'userId' => $user->userId,
'userName' => $user->userName,
'userContact ' => $user->userContact
));
?>
Get in details with Example Demo :
http://devgambit.com/how-to-store-and-get-session-value-in-codeigniter/
import subprocess
python_path = subprocess.check_output("which python", shell=True).strip()
python_path = python_path.decode('utf-8')
Do as below create class and call it like this
Check : Reset all Controls (Textbox, ComboBox, CheckBox, ListBox) in a Windows Form using C#
private void button1_Click(object sender, EventArgs e)
{
Utilities.ResetAllControls(this);
}
public class Utilities
{
public static void ResetAllControls(Control form)
{
foreach (Control control in form.Controls)
{
if (control is TextBox)
{
TextBox textBox = (TextBox)control;
textBox.Text = null;
}
if (control is ComboBox)
{
ComboBox comboBox = (ComboBox)control;
if (comboBox.Items.Count > 0)
comboBox.SelectedIndex = 0;
}
if (control is CheckBox)
{
CheckBox checkBox = (CheckBox)control;
checkBox.Checked = false;
}
if (control is ListBox)
{
ListBox listBox = (ListBox)control;
listBox.ClearSelected();
}
}
}
}
The RequestContext
is deprecated from Primefaces 6.2. From this version use the following:
if (componentID != null && PrimeFaces.current().isAjaxRequest()) {
PrimeFaces.current().ajax().update(componentID);
}
And to execute javascript from the backbean use this way:
PrimeFaces.current().executeScript(jsCommand);
I also had added on or extended additional columns into my AspNetUsers table. When I wanted to simply view this data I found many examples like the code above with "Extensions" etc... This really amazed me that you had to write all those lines of code just to get a couple values from the current users.
It turns out that you can query the AspNetUsers table like any other table:
ApplicationDbContext db = new ApplicationDbContext();
var user = db.Users.Where(x => x.UserName == User.Identity.Name).FirstOrDefault();
By default all class methods are public. To make them private you can use Module#private_class_method like @tjwallace wrote or define them differently, as you did:
class << self
private
def method_name
...
end
end
class << self
opens up self's singleton class, so that methods can be redefined for the current self object. This is used to define class/module ("static") method. Only there, defining private methods really gives you private class methods.
You must not use StreamReader
for binary files (like gifs or jpgs). StreamReader
is for text data. You will almost certainly lose data if you use it for arbitrary binary data. (If you use Encoding.GetEncoding(28591) you will probably be okay, but what's the point?)
Why do you need to use a StreamReader
at all? Why not just keep the binary data as binary data and write it back to disk (or SQL) as binary data?
EDIT: As this seems to be something people want to see... if you do just want to copy one stream to another (e.g. to a file) use something like this:
/// <summary>
/// Copies the contents of input to output. Doesn't close either stream.
/// </summary>
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[8 * 1024];
int len;
while ( (len = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, len);
}
}
To use it to dump a stream to a file, for example:
using (Stream file = File.Create(filename))
{
CopyStream(input, file);
}
Note that Stream.CopyTo
was introduced in .NET 4, serving basically the same purpose.
Instead of storing the data as pure JSON store it instead as a JavaScript Object Literal; E.g.
window.portalData = [_x000D_
{_x000D_
"kpi" : "NDAR",_x000D_
"data": [15,152,2,45,0,2,0,16,88,0,174,0,30,63,0,0,0,0,448,4,0,139,1,7,12,0,211,37,182,154]_x000D_
},_x000D_
{_x000D_
"kpi" : "NTI",_x000D_
"data" : [195,299,31,32,438,12,0,6,136,31,71,5,40,40,96,46,4,49,106,127,43,366,23,36,7,34,196,105,30,77]_x000D_
},_x000D_
{_x000D_
"kpi" : "BS",_x000D_
"data" : [745,2129,1775,1089,517,720,2269,334,1436,517,3219,1167,2286,266,1813,509,1409,988,1511,972,730,2039,1067,1102,1270,1629,845,1292,1107,1800]_x000D_
},_x000D_
{_x000D_
"kpi" : "SISS",_x000D_
"data" : [75,547,260,430,397,91,0,0,217,105,563,136,352,286,244,166,287,319,877,230,100,437,108,326,145,749,0,92,191,469]_x000D_
},_x000D_
{_x000D_
"kpi" : "MID",_x000D_
"data" : [6,17,14,8,13,7,4,6,8,5,72,15,6,3,1,13,17,32,9,3,25,21,7,49,23,10,13,18,36,9,12]_x000D_
}_x000D_
];
_x000D_
You can then do the following in your HTML
<script src="server_data.js"> </script>
function getServerData(kpiCode)
{
var elem = $(window.portalData).filter(function(idx){
return window.portalData[idx].kpi == kpiCode;
});
return elem[0].data;
};
var defData = getServerData('NDAR');
You might not believe it, but YAML can do multi-line keys too:
?
>
multi
line
key
:
value
This question might still be visited often enough that it's worth offering an addendum to Mr Kassies' answer. The dict
built-in class can be sub-classed so that a default is returned for 'missing' keys. This mechanism works well for pandas. But see below.
In this way it's possible to avoid key errors.
>>> import pandas as pd
>>> data = { 'ID': [ 101, 201, 301, 401 ] }
>>> df = pd.DataFrame(data)
>>> class SurnameMap(dict):
... def __missing__(self, key):
... return ''
...
>>> surnamemap = SurnameMap()
>>> surnamemap[101] = 'Mohanty'
>>> surnamemap[301] = 'Drake'
>>> df['Surname'] = df['ID'].apply(lambda x: surnamemap[x])
>>> df
ID Surname
0 101 Mohanty
1 201
2 301 Drake
3 401
The same thing can be done more simply in the following way. The use of the 'default' argument for the get
method of a dict object makes it unnecessary to subclass a dict.
>>> import pandas as pd
>>> data = { 'ID': [ 101, 201, 301, 401 ] }
>>> df = pd.DataFrame(data)
>>> surnamemap = {}
>>> surnamemap[101] = 'Mohanty'
>>> surnamemap[301] = 'Drake'
>>> df['Surname'] = df['ID'].apply(lambda x: surnamemap.get(x, ''))
>>> df
ID Surname
0 101 Mohanty
1 201
2 301 Drake
3 401
First I need to say that your code,
MyClass *myclass;
myclass->DoSomething();
will cause an undefined behavior. Because the pointer "myclass" isn't pointing to any "MyClass" type objects.
Here I have three suggestions for you:-
option 1:- You can simply declare and use a MyClass type object on the stack as below.
MyClass myclass; //allocates memory for the object "myclass", on the stack.
myclass.DoSomething();
option 2:- By using the new operator.
MyClass *myclass = new MyClass();
Three things will hapen here.
i) Allocates memory for the "MyClass" type object on the heap.
ii) Allocates memory for the "MyClass" type pointer "myclass" on the stack.
iii) pointer "myclass" points to the memory address of "MyClass" type object on the heap
Now you can use the pointer to access member functions of the object after dereferencing the pointer by "->"
myclass->DoSomething();
But you should free the memory allocated to "MyClass" type object on the heap, before returning from the scope unless you want it to exists. Otherwise it will cause a memory leak!
delete myclass; // free the memory pointed by the pointer "myclass"
option 3:- you can also do as below.
MyClass myclass; // allocates memory for the "MyClass" type object on the stack.
MyClass *myclassPtr; // allocates memory for the "MyClass" type pointer on the stack.
myclassPtr = &myclass; // "myclassPtr" pointer points to the momory address of myclass object.
Now, pointer and object both are on the stack. Now you can't return this pointer to the outside of the current scope because both allocated memory of the pointer and the object will be freed while stepping outside the scope.
So as a summary, option 1 and 3 will allocate an object on the stack while only the option 2 will do it on the heap.
May be you created a new xml file in Layout Directory that file name containing a Capital Letter which is not allowed in xml file under Layout Directory.
Hope this help.
Use a div #overlay
with your loading info / .gif that will cover all your page:
<div id="overlay">
<img src="loading.gif" alt="Loading" />
Loading...
</div>
jQuery:
$(window).load(function(){
// PAGE IS FULLY LOADED
// FADE OUT YOUR OVERLAYING DIV
$('#overlay').fadeOut();
});
Here's an example with a Loading bar:
<div id="overlay">
<div id="progstat"></div>
<div id="progress"></div>
</div>
<div id="container">
<img src="http://placehold.it/3000x3000/cf5">
</div>
CSS:
*{margin:0;}
body{ font: 200 16px/1 sans-serif; }
img{ width:32.2%; }
#overlay{
position:fixed;
z-index:99999;
top:0;
left:0;
bottom:0;
right:0;
background:rgba(0,0,0,0.9);
transition: 1s 0.4s;
}
#progress{
height:1px;
background:#fff;
position:absolute;
width:0; /* will be increased by JS */
top:50%;
}
#progstat{
font-size:0.7em;
letter-spacing: 3px;
position:absolute;
top:50%;
margin-top:-40px;
width:100%;
text-align:center;
color:#fff;
}
JavaScript:
;(function(){
function id(v){ return document.getElementById(v); }
function loadbar() {
var ovrl = id("overlay"),
prog = id("progress"),
stat = id("progstat"),
img = document.images,
c = 0,
tot = img.length;
if(tot == 0) return doneLoading();
function imgLoaded(){
c += 1;
var perc = ((100/tot*c) << 0) +"%";
prog.style.width = perc;
stat.innerHTML = "Loading "+ perc;
if(c===tot) return doneLoading();
}
function doneLoading(){
ovrl.style.opacity = 0;
setTimeout(function(){
ovrl.style.display = "none";
}, 1200);
}
for(var i=0; i<tot; i++) {
var tImg = new Image();
tImg.onload = imgLoaded;
tImg.onerror = imgLoaded;
tImg.src = img[i].src;
}
}
document.addEventListener('DOMContentLoaded', loadbar, false);
}());
The withColumn function in pyspark enables you to make a new variable with conditions, add in the when and otherwise functions and you have a properly working if then else structure. For all of this you would need to import the sparksql functions, as you will see that the following bit of code will not work without the col() function. In the first bit, we declare a new column -'new column', and then give the condition enclosed in when function (i.e. fruit1==fruit2) then give 1 if the condition is true, if untrue the control goes to the otherwise which then takes care of the second condition (fruit1 or fruit2 is Null) with the isNull() function and if true 3 is returned and if false, the otherwise is checked again giving 0 as the answer.
from pyspark.sql import functions as F
df=df.withColumn('new_column',
F.when(F.col('fruit1')==F.col('fruit2'), 1)
.otherwise(F.when((F.col('fruit1').isNull()) | (F.col('fruit2').isNull()), 3))
.otherwise(0))
They dont support it as in in they wont help you or be responsible for you hosing anything, but you can install custom extensions. To do so you need to first set up a local install of php 5, during that process you can compile in extensions you need or you can add them dynamically to the php.ini after the fact.
Joseph forgot to add the value in his example with withDefault
.
Here is the code I ended up using:
Map map = [:].withDefault { key -> return [] }
listOfObjects.each { map.get(it.myKey).add(it.myValue) }
Arrays themselves do not have that method. A List, however, does: indexOf
I came to this situation when I installed node js from the latest stable release.
curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -
It seems this version already comes with a prepackaged NPM. So when I tried to install NPM again, I got this error. If anyone is installing Nodejs in this manner then, it's not needed to install NPM separately.
The following packages have unmet dependencies:
npm : Depends: nodejs but it is not going to be installed
Depends: node-abbrev (>= 1.0.4) but it is not going to be installed
Depends: node-ansi (>= 0.3.0-2) but it is not going to be installed
Depends: node-ansi-color-table but it is not going to be installed
Depends: node-archy but it is not going to be installed
Depends: node-block-stream but it is not going to be installed
Depends: node-fstream (>= 0.1.22) but it is not going to be installed
Depends: node-fstream-ignore but it is not going to be installed
Depends: node-github-url-from-git but it is not going to be installed
Depends: node-glob (>= 3.1.21) but it is not going to be installed
Depends: node-graceful-fs (>= 2.0.0) but it is not going to be installed
Depends: node-inherits but it is not going to be installed
Depends: node-ini (>= 1.1.0) but it is not going to be installed
Depends: node-lockfile but it is not going to be installed
Depends: node-lru-cache (>= 2.3.0) but it is not going to be installed
Depends: node-minimatch (>= 0.2.11) but it is not going to be installed
Depends: node-mkdirp (>= 0.3.3) but it is not going to be installed
Depends: node-gyp (>= 0.10.9) but it is not going to be installed
Depends: node-nopt (>= 3.0.1) but it is not going to be installed
Depends: node-npmlog but it is not going to be installed
Depends: node-once but it is not going to be installed
Depends: node-osenv but it is not going to be installed
Depends: node-read but it is not going to be installed
Depends: node-read-package-json (>= 1.1.0) but it is not going to be installed
Depends: node-request (>= 2.25.0) but it is not going to be installed
Depends: node-retry but it is not going to be installed
Depends: node-rimraf (>= 2.2.2) but it is not going to be installed
Depends: node-semver (>= 2.1.0) but it is not going to be installed
Depends: node-sha but it is not going to be installed
Depends: node-slide but it is not going to be installed
Depends: node-tar (>= 0.1.18) but it is not going to be installed
Depends: node-underscore but it is not going to be installed
Depends: node-which but it is not going to be installed
E: Unable to correct problems, you have held broken packages.
Loops are also very useful to learn about, esp When using arrays,
int[] array = new int[10];
Random rand = new Random();
for (int i = 0; i < array.length; i++)
array[i] = rand.nextInt(100) + 1;
Arrays.sort(array);
System.out.println(Arrays.toString(array));
// in reverse order
for (int i = array.length - 1; i >= 0; i--)
System.out.print(array[i] + " ");
System.out.println();
I solve the problem by creating a folder named "src/test/resources" first, then i rename the folder to "src/test/java" ,finally create a "src/test/resources" folder again .It works .
First install the RJSONIO and RCurl package:
install.packages("RJSONIO")_x000D_
install.packages("(RCurl")
_x000D_
Try below code using RJSONIO in console
library(RJSONIO)_x000D_
library(RCurl)_x000D_
json_file = getURL("https://raw.githubusercontent.com/isrini/SI_IS607/master/books.json")_x000D_
json_file2 = RJSONIO::fromJSON(json_file)_x000D_
head(json_file2)
_x000D_
The Javascript to change font size for an input control is:
input.style.fontSize = "16px";
See the following methods:
~ : Changes the case of current character
guu : Change current line from upper to lower.
gUU : Change current LINE from lower to upper.
guw : Change to end of current WORD from upper to lower.
guaw : Change all of current WORD to lower.
gUw : Change to end of current WORD from lower to upper.
gUaw : Change all of current WORD to upper.
g~~ : Invert case to entire line
g~w : Invert case to current WORD
guG : Change to lowercase until the end of document.
The URI "file:///android_asset/"
points to YourProject/app/src/main/assets/
.
Note: android_asset/
uses the singular (asset) and src/main/assets
uses the plural (assets).
Suppose you have a file YourProject/app/src/main/assets/web_thing.html
that you would like to display in a WebView. You can refer to it like this:
WebView webViewer = (WebView) findViewById(R.id.webViewer);
webView.loadUrl("file:///android_asset/web_thing.html");
The snippet above could be located in your Activity class, possibly in the onCreate
method.
Here is a guide to the overall directory structure of an android project, that helped me figure out this answer.
Recursively create directory path:
function makedirs($dirpath, $mode=0777) {
return is_dir($dirpath) || mkdir($dirpath, $mode, true);
}
Inspired by Python's os.makedirs()
use a css3 class "spinner". It's more beautiful and you don't need .gif
.spinner {
position: absolute;
left: 50%;
top: 50%;
height:60px;
width:60px;
margin:0px auto;
-webkit-animation: rotation .6s infinite linear;
-moz-animation: rotation .6s infinite linear;
-o-animation: rotation .6s infinite linear;
animation: rotation .6s infinite linear;
border-left:6px solid rgba(0,174,239,.15);
border-right:6px solid rgba(0,174,239,.15);
border-bottom:6px solid rgba(0,174,239,.15);
border-top:6px solid rgba(0,174,239,.8);
border-radius:100%;
}
@-webkit-keyframes rotation {
from {-webkit-transform: rotate(0deg);}
to {-webkit-transform: rotate(359deg);}
}
@-moz-keyframes rotation {
from {-moz-transform: rotate(0deg);}
to {-moz-transform: rotate(359deg);}
}
@-o-keyframes rotation {
from {-o-transform: rotate(0deg);}
to {-o-transform: rotate(359deg);}
}
@keyframes rotation {
from {transform: rotate(0deg);}
to {transform: rotate(359deg);}
}
Exemple of what is looks like : http://jsbin.com/roqakuxebo/1/edit
You can find a lot of css spinners like this here : http://cssload.net/en/spinners/
correct syntax at command line should be
echo -n "compute sha1" | openssl sha1
otherwise you'll hash the trailing newline character as well.
Might want to try instance_values
. That worked for me.
I don't believe the currently accepted answer is correct. For example, I have the following .htaccess
file in the root of a virtual server (apache 2.4):
<Files "reminder.php">
require all denied
require host localhost
require ip 127.0.0.1
require ip xxx.yyy.zzz.aaa
</Files>
This prevents external access to reminder.php
which is in a subdirectory.
I have a similar .htaccess
file on my Apache 2.2 server with the same effect:
<Files "reminder.php">
Order Deny,Allow
Deny from all
Allow from localhost
Allow from 127.0.0.1
Allow from xxx.yyy.zzz.aaa
</Files>
I don't know for sure but I suspect it's the attempt to define the subdirectory specifically in the .htaccess
file, viz <Files ./inscription/log.txt>
which is causing it to fail. It would be simpler to put the .htaccess
file in the same directory as log.txt
i.e. in the inscription
directory and it will work there.
The code you posted starts three different processes each with it's own command. To open a command prompt and then run a command try the following (never tried it myself):
try {
// Execute command
String command = "cmd /c start cmd.exe";
Process child = Runtime.getRuntime().exec(command);
// Get output stream to write from it
OutputStream out = child.getOutputStream();
out.write("cd C:/ /r/n".getBytes());
out.flush();
out.write("dir /r/n".getBytes());
out.close();
} catch (IOException e) {
}
First, add the dependency of FFmpeg library
implementation 'com.writingminds:FFmpegAndroid:0.3.2'
Then load in activity
FFmpeg ffmpeg;
private void trimVideo(ProgressDialog progressDialog) {
outputAudioMux = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES).getAbsolutePath()
+ "/VidEffectsFilter" + "/" + new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date())
+ "filter_apply.mp4";
if (startTrim.equals("")) {
startTrim = "00:00:00";
}
if (endTrim.equals("")) {
endTrim = timeTrim(player.getDuration());
}
String[] cmd = new String[]{"-ss", startTrim + ".00", "-t", endTrim + ".00", "-noaccurate_seek", "-i", videoPath, "-codec", "copy", "-avoid_negative_ts", "1", outputAudioMux};
execFFmpegBinary1(cmd, progressDialog);
}
private void execFFmpegBinary1(final String[] command, ProgressDialog prpg) {
ProgressDialog progressDialog = prpg;
try {
ffmpeg.execute(command, new ExecuteBinaryResponseHandler() {
@Override
public void onFailure(String s) {
progressDialog.dismiss();
Toast.makeText(PlayerTestActivity.this, "Fail to generate video", Toast.LENGTH_SHORT).show();
Log.d(TAG, "FAILED with output : " + s);
}
@Override
public void onSuccess(String s) {
Log.d(TAG, "SUCCESS wgith output : " + s);
// pathVideo = outputAudioMux;
String finalPath = outputAudioMux;
videoPath = outputAudioMux;
Toast.makeText(PlayerTestActivity.this, "Storage Path =" + finalPath, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(PlayerTestActivity.this, ShareVideoActivity.class);
intent.putExtra("pathGPU", finalPath);
startActivity(intent);
finish();
MediaScannerConnection.scanFile(PlayerTestActivity.this, new String[]{finalPath}, new String[]{"mp4"}, null);
}
@Override
public void onProgress(String s) {
Log.d(TAG, "Started gcommand : ffmpeg " + command);
progressDialog.setMessage("Please Wait video triming...");
}
@Override
public void onStart() {
Log.d(TAG, "Startedf command : ffmpeg " + command);
}
@Override
public void onFinish() {
Log.d(TAG, "Finished f command : ffmpeg " + command);
progressDialog.dismiss();
}
});
} catch (FFmpegCommandAlreadyRunningException e) {
// do nothing for now
}
}
private void loadFFMpegBinary() {
try {
if (ffmpeg == null) {
ffmpeg = FFmpeg.getInstance(this);
}
ffmpeg.loadBinary(new LoadBinaryResponseHandler() {
@Override
public void onFailure() {
showUnsupportedExceptionDialog();
}
@Override
public void onSuccess() {
Log.d("dd", "ffmpeg : correct Loaded");
}
});
} catch (FFmpegNotSupportedException e) {
showUnsupportedExceptionDialog();
} catch (Exception e) {
Log.d("dd", "EXception no controlada : " + e);
}
}
private void showUnsupportedExceptionDialog() {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Not Supported")
.setMessage("Device Not Supported")
.setCancelable(false)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.create()
.show();
}
public String timeTrim(long milliseconds) {
String finalTimerString = "";
String minutString = "";
String secondsString = "";
// Convert total duration into time
int hours = (int) (milliseconds / (1000 * 60 * 60));
int minutes = (int) (milliseconds % (1000 * 60 * 60)) / (1000 * 60);
int seconds = (int) ((milliseconds % (1000 * 60 * 60)) % (1000 * 60) / 1000);
// Add hours if there
if (hours < 10) {
finalTimerString = "0" + hours + ":";
} else {
finalTimerString = hours + ":";
}
if (minutes < 10) {
minutString = "0" + minutes;
} else {
minutString = "" + minutes;
}
// Prepending 0 to seconds if it is one digit
if (seconds < 10) {
secondsString = "0" + seconds;
} else {
secondsString = "" + seconds;
}
finalTimerString = finalTimerString + minutString + ":" + secondsString;
// return timer string
return finalTimerString;
}
Also use another feature by FFmpeg
===> merge audio to video
String[] cmd = new String[]{"-i", yourRealPath, "-i", arrayList.get(posmusic).getPath(), "-map", "1:a", "-map", "0:v", "-codec", "copy", "-shortest", outputcrop};
===> Flip vertical :
String[] cm = new String[]{"-i", yourRealPath, "-vf", "vflip", "-codec:v", "libx264", "-preset", "ultrafast", "-codec:a", "copy", outputcrop1};
===> Flip horizontally :
String[] cm = new String[]{"-i", yourRealPath, "-vf", "hflip", "-codec:v", "libx264", "-preset", "ultrafast", "-codec:a", "copy", outputcrop1};
===> Rotate 90 degrees clockwise:
String[] cm=new String[]{"-i", yourRealPath, "-c", "copy", "-metadata:s:v:0", "rotate=90", outputcrop1};
===> Compress Video
String[] complexCommand = {"-y", "-i", yourRealPath, "-strict", "experimental", "-vcodec", "libx264", "-preset", "ultrafast", "-crf", "24", "-acodec", "aac", "-ar", "22050", "-ac", "2", "-b", "360k", "-s", "1280x720", outputcrop1};
===> Speed up down video
String[] complexCommand = {"-y", "-i", yourRealPath, "-filter_complex", "[0:v]setpts=2.0*PTS[v];[0:a]atempo=0.5[a]", "-map", "[v]", "-map", "[a]", "-b:v", "2097k", "-r", "60", "-vcodec", "mpeg4", outputcrop1};
String[] complexCommand = {"-y", "-i", yourRealPath, "-filter_complex", "[0:v]setpts=1.0*PTS[v];[0:a]atempo=1.0[a]", "-map", "[v]", "-map", "[a]", "-b:v", "2097k", "-r", "60", "-vcodec", "mpeg4", outputcrop1};
String[] complexCommand = {"-y", "-i", yourRealPath, "-filter_complex", "[0:v]setpts=0.75*PTS[v];[0:a]atempo=1.5[a]", "-map", "[v]", "-map", "[a]", "-b:v", "2097k", "-r", "60", "-vcodec", "mpeg4", outputcrop1};
String[] complexCommand = {"-y", "-i", yourRealPath, "-filter_complex", "[0:v]setpts=0.5*PTS[v];[0:a]atempo=2.0[a]", "-map", "[v]", "-map", "[a]", "-b:v", "2097k", "-r", "60", "-vcodec", "mpeg4", outputcrop1};
===> Add two mp3 files
StringBuilder sb = new StringBuilder();
sb.append("-i ");
sb.append(textSngname);
sb.append(" -i ");
sb.append(mAudioFilename);
sb.append(" -filter_complex [0:0][1:0]concat=n=2:v=0:a=1[out] -map [out] ");
sb.append(finalfile);
---> ffmpeg.execute(sb.toString().split(" "), new ExecuteBinaryResponseHandler()
===> Add three mp3 files
StringBuilder sb = new StringBuilder();
sb.append("-i ");
sb.append(firstSngname);
sb.append(" -i ");
sb.append(textSngname);
sb.append(" -i ");
sb.append(mAudioFilename);
sb.append(" -filter_complex [0:0][1:0][2:0]concat=n=3:v=0:a=1[out] -map [out] ");
sb.append(finalfile);
---> ffmpeg.execute(sb.toString().split(" "), new ExecuteBinaryResponseHandler()
Well, probably the simplest way is just parse the XML into dictionaries and then serialize that with simplejson.
if anybody wants to clear out only a particular form control one can use
formSubmit(){
this.formName.patchValue({
formControlName:''
//or if one wants to change formControl to a different value on submit
formControlName:'form value after submission'
});
}
You can use python garbage collector:
import gc
gc.collect()
Try the following, note that when user refreshes the page, the value is "Male" again, data should be stored on database.
<p id="pTest">Male</p>
<button>change</button>
<script>
$('button').click(function(){
$('#pTest').text('test')
})
</script>
I had this problem too but it looks like it depends on the Kubernetes offering and how everything was installed. In Azure, if you are using acs-engine install, you can find the shell script that is actually being run to provision it at:
/opt/azure/containers/provision.sh
To get a more fine-grained understanding, just read through it and run the commands that it specifies. For me, I had to run as root:
systemctl enable kubectl
systemctl restart kubectl
I don't know if the enable is necessary and I can't say if these will work with your particular installation, but it definitely worked for me.
Knuth's multiplicative method:
hash(i)=i*2654435761 mod 2^32
In general, you should pick a multiplier that is in the order of your hash size (2^32
in the example) and has no common factors with it. This way the hash function covers all your hash space uniformly.
Edit: The biggest disadvantage of this hash function is that it preserves divisibility, so if your integers are all divisible by 2 or by 4 (which is not uncommon), their hashes will be too. This is a problem in hash tables - you can end up with only 1/2 or 1/4 of the buckets being used.
Try to simply use break statement.
Also you can use the following code as an example:
a = [[0,1,0], [1,0,0], [1,1,1]]
b = [[0,0,0], [0,0,0], [0,0,0]]
def check_matr(matr, expVal):
for row in matr:
if len(set(row)) > 1 or set(row).pop() != expVal:
print 'Wrong'
break# or return
else:
print 'ok'
else:
print 'empty'
check_matr(a, 0)
check_matr(b, 0)
The syntax is wrong in this clause (and similar ones)
CASE lkey WHEN lkey > 5 THEN
lkey + 2
ELSE
lkey
END
It's either
CASE WHEN [condition] THEN [expression] ELSE [expression] END
or
CASE [expression] WHEN [value] THEN [expression] ELSE [expression] END
So in your case it would read:
CASE WHEN lkey > 5 THEN
lkey + 2
ELSE
lkey
END
Check out the documentation (The CASE expression):
If you are using jQuery then:
HTML:
<a id="openMap" href="/map/">link</a>
JS:
$(document).ready(function() {
$("#openMap").click(function(){
popup('/map/', 300, 300, 'map');
return false;
});
});
This has the benefit of still working without JS, or if the user middle clicks the link.
It also means that I could handle generic popups by rewriting again to:
HTML:
<a class="popup" href="/map/">link</a>
JS:
$(document).ready(function() {
$(".popup").click(function(){
popup($(this).attr("href"), 300, 300, 'map');
return false;
});
});
This would let you add a popup to any link by just giving it the popup class.
This idea could be extended even further like so:
HTML:
<a class="popup" data-width="300" data-height="300" href="/map/">link</a>
JS:
$(document).ready(function() {
$(".popup").click(function(){
popup($(this).attr("href"), $(this).data('width'), $(this).data('height'), 'map');
return false;
});
});
I can now use the same bit of code for lots of popups on my whole site without having to write loads of onclick stuff! Yay for reusability!
It also means that if later on I decide that popups are bad practice, (which they are!) and that I want to replace them with a lightbox style modal window, I can change:
popup($(this).attr("href"), $(this).data('width'), $(this).data('height'), 'map');
to
myAmazingModalWindow($(this).attr("href"), $(this).data('width'), $(this).data('height'), 'map');
and all my popups on my whole site are now working totally differently. I could even do feature detection to decide what to do on a popup, or store a users preference to allow them or not. With the inline onclick, this requires a huge copy and pasting effort.
I'd recommend using a regular expressions instead of string operations for this:
Set fso = CreateObject("Scripting.FileSystemObject")
filename = "C:\VBS\filediprova.txt"
newtext = vbLf & "<tr><td><a href=""..."">Beginning_of_DD_TC5</a></td></tr>"
Set re = New RegExp
re.Pattern = "(\n.*?Test Case \d)"
re.Global = False
re.IgnoreCase = True
text = f.OpenTextFile(filename).ReadAll
f.OpenTextFile(filename, 2).Write re.Replace(text, newText & "$1")
The regular expression will match a line feed (\n
) followed by a line containing the string Test Case
followed by a number (\d
), and the replacement will prepend that with the text you want to insert (variable newtext
). Setting re.Global = False
makes the replacement stop after the first match.
If the line breaks in your text file are encoded as CR-LF
(carriage return + line feed) you'll have to change \n
into \r\n
and vbLf
into vbCrLf
.
If you have to modify several text files, you could do it in a loop like this:
For Each f In fso.GetFolder("C:\VBS").Files
If LCase(fso.GetExtensionName(f.Name)) = "txt" Then
text = f.OpenAsTextStream.ReadAll
f.OpenAsTextStream(2).Write re.Replace(text, newText & "$1")
End If
Next
There are two problems. As in the question, select-string needs to operate on the output string, which can be had from "out-string". Also, select-string doesn't operate linewise on strings that are piped to it. Here is a generic solution
(alias|out-string) -split "`n" | select-string Write
As suggested you can use JAD to decompile it and view the files. To make it easier to read you can use the JADclipse plugin for eclipse to integrate JAD directly to eclipse or use DJ Java Decompiler which is much easier to use than command line JAD
Checkbox click and checking for the value in the same event loop is the problem.
Try this:
$('#checkbox1').click(function() {
var self = this;
setTimeout(function() {
if (!self.checked) {
var ans = confirm("Are you sure?");
self.checked = ans;
$('#textbox1').val(ans.toString());
}
}, 0);
});
Here is how to build a function that returns a result set that can be queried as if it were a table:
SQL> create type emp_obj is object (empno number, ename varchar2(10));
2 /
Type created.
SQL> create type emp_tab is table of emp_obj;
2 /
Type created.
SQL> create or replace function all_emps return emp_tab
2 is
3 l_emp_tab emp_tab := emp_tab();
4 n integer := 0;
5 begin
6 for r in (select empno, ename from emp)
7 loop
8 l_emp_tab.extend;
9 n := n + 1;
10 l_emp_tab(n) := emp_obj(r.empno, r.ename);
11 end loop;
12 return l_emp_tab;
13 end;
14 /
Function created.
SQL> select * from table (all_emps);
EMPNO ENAME
---------- ----------
7369 SMITH
7499 ALLEN
7521 WARD
7566 JONES
7654 MARTIN
7698 BLAKE
7782 CLARK
7788 SCOTT
7839 KING
7844 TURNER
7902 FORD
7934 MILLER
I got this error message but was a really basic mistake, I had copy/pasted another Component as a template, removed everything from render() then imported it and added it to the parent JSX but hadn't yet renamed the component class. So then the error looked like it was coming from another component which I spent a while trying to debug it before working out it wasn't actually that Component throwing the error! Would have been helpful to have the filename as part of the error message. Hope this helps someone.
Oh a side note note I'm not sure anyone mentioned that returning undefined
will throw the error:
render() {
return this.foo // Where foo is undefined.
}
You can use ElementRef as shown below,
DEMO : https://plnkr.co/edit/XZwXEh9PZEEVJpe0BlYq?p=preview check browser's console.
import { Directive,Input,Outpu,ElementRef,Renderer} from '@angular/core';
@Directive({
selector:"[move]",
host:{
'(click)':"show()"
}
})
export class GetEleDirective{
constructor(private el:ElementRef){
}
show(){
console.log(this.el.nativeElement);
console.log('height---' + this.el.nativeElement.offsetHeight); //<<<===here
console.log('width---' + this.el.nativeElement.offsetWidth); //<<<===here
}
}
Same way you can use it within component itself wherever you need it.
I think you want
listb.pop()[0]
The expression listb.pop
is a valid python expression which results in a reference to the pop
method, but doesn't actually call that method. You need to add the open and close parentheses to call the method.
Access your list elements directly by i. Then you can append to your list:
for i in xrange(len(myarr)):
if somecond(a[i]):
myarr.append(newObj())
You could create a new array containing that array, so:
<?php
$array = array();
$array['name'] = $oldArray;
?>
It should be pretty obvious from your question that you're actually just asking about the difference between git merge
and git rebase
.
So let's suppose you're in the common case - you've done some work on your master branch, and you pull from origin's, which also has done some work. After the fetch, things look like this:
- o - o - o - H - A - B - C (master)
\
P - Q - R (origin/master)
If you merge at this point (the default behavior of git pull), assuming there aren't any conflicts, you end up with this:
- o - o - o - H - A - B - C - X (master)
\ /
P - Q - R --- (origin/master)
If on the other hand you did the appropriate rebase, you'd end up with this:
- o - o - o - H - P - Q - R - A' - B' - C' (master)
|
(origin/master)
The content of your work tree should end up the same in both cases; you've just created a different history leading up to it. The rebase rewrites your history, making it look as if you had committed on top of origin's new master branch (R
), instead of where you originally committed (H
). You should never use the rebase approach if someone else has already pulled from your master branch.
Finally, note that you can actually set up git pull
for a given branch to use rebase instead of merge by setting the config parameter branch.<name>.rebase
to true. You can also do this for a single pull using git pull --rebase
.
It only works till 4000 byte, What if the clob is bigger than 4000 bytes then we use this
declare
v_clob_size clob;
begin
v_clob_size:= (DBMS_LOB.getlength(v_clob)) / 1024 / 1024;
DBMS_OUTPUT.put_line('CLOB Size ' || v_clob_size);
end;
or
select (DBMS_LOB.getlength(your_column_name))/1024/1024 from your_table
Reason for error:
The query from p in dc.BlogPosts where p.BlogPostID == ID select p
returns a sequence.
Single()
tries to retrieve an element from the sequence returned in step1.
As per the exception - The sequence returned in step1 contains no elements.
Single() tries to retrieve an element from the sequence returned in step1 which contains no elements.
Since Single()
is not able to fetch a single element from the sequence returned in step1, it throws an error.
Fix:
Make sure the query (from p in dc.BlogPosts where p.BlogPostID == ID select p)
returns a sequence with at least one element.
Find below code if you want to download the contents of the specified URL also want to saves it to a file.
<?php
$ch = curl_init();
/**
* Set the URL of the page or file to download.
*/
curl_setopt($ch, CURLOPT_URL,'http://news.google.com/news?hl=en&topic=t&output=rss');
$fp = fopen('rss.xml', 'w+');
/**
* Ask cURL to write the contents to a file
*/
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_exec ($ch);
curl_close ($ch);
fclose($fp);
?>
If you want to downloads file from the FTP server you can use php FTP extension. Please find below code:
<?php
$SERVER_ADDRESS="";
$SERVER_USERNAME="";
$SERVER_PASSWORD="";
$conn_id = ftp_connect($SERVER_ADDRESS);
// login with username and password
$login_result = ftp_login($conn_id, $SERVER_USERNAME, $SERVER_PASSWORD);
$server_file="test.pdf" //FTP server file path
$local_file = "new.pdf"; //Local server file path
##----- DOWNLOAD $SERVER_FILE AND SAVE TO $LOCAL_FILE--------##
if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) {
echo "Successfully written to $local_file\n";
} else {
echo "There was a problem\n";
}
ftp_close($conn_id);
?>
Its very easy just do the following:
add the following line in your manifest.json
"content_security_policy": "script-src 'self' https://ajax.googleapis.com; object-src 'self'",
Now you are free to load jQuery directly from url
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
Source: google doc
String sc1="0.0";
Double s1=Double.parseDouble(sc1.toString());
Anyone here looking for Knockout JS integration.
Given the following HTML (Standard Bootstrap dropdown button):
<div class="dropdown">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
Select an item
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li>
<a href="javascript:;" data-bind="click: clickTest">Click 1</a>
</li>
<li>
<a href="javascript:;" data-bind="click: clickTest">Click 2</a>
</li>
<li>
<a href="javascript:;" data-bind="click: clickTest">Click 3</a>
</li>
</ul>
</div>
Use the following JS:
var viewModel = function(){
var self = this;
self.clickTest = function(){
alert("I've been clicked!");
}
};
For those looking to generate dropdown options based on knockout observable array, the code would look something like:
var viewModel = function(){
var self = this;
self.dropdownOptions = ko.observableArray([
{ id: 1, label: "Click 1" },
{ id: 2, label: "Click 2" },
{ id: 3, label: "Click 3" }
])
self.clickTest = function(item){
alert("Item with id:" + item.id + " was clicked!");
}
};
<!-- REST OF DD CODE -->
<ul class="dropdown-menu" role="menu">
<!-- ko foreach: { data: dropdownOptions, as: 'option' } -->
<li>
<a href="javascript:;" data-bind="click: $parent.clickTest, text: option.clickTest"></a>
</li>
<!-- /ko -->
</ul>
<!-- REST OF DD CODE -->
Note, that the observable array item is implicitly passed into the click function handler for use in the view model code.
I was running into the same issue. I discovered the following solution, which has only been tested in Chrome v31:
table {
table-layout: fixed;
}
tbody {
display: block;
overflow: scroll;
}
sounds like you're looking for setInterval. It's as easy as this:
function FetchData() {
// do something
}
setInterval(FetchData, 60000);
if you only want to call something once, theres setTimeout.
2018 Update
Font Awesome 5 now features light, regular and solid variants. The icon featured in this question has the following style under the different variants:
A modern answer to this question would be that different variants of the icon can be used to make the icon appear bolder or lighter. The only downside is that if you're already using solid you will have to fall back to the original answers here to make those bolder, and likewise if you're using light you'd have to do the same to make those lighter.
Font Awesome's How To Use documentation walks through how to use these variants.
Original Answer
Font Awesome makes use of the Private Use region of Unicode. For example, this .icon-remove
you're using is added in using the ::before
pseudo-selector, setting its content to \f00d (
):
.icon-remove:before {
content: "\f00d";
}
Font Awesome does only come with one font-weight variant, however browsers will render this as they would render any font with only one variant. If you look closely, the normal
font-weight isn't as bold as the bold
font-weight. Unfortunately a normal font weight isn't what you're after.
What you can do however is change its colour to something less dark and reduce its font size to make it stand out a bit less. From your image, the "tags" text appears much lighter than the icon, so I'd suggest using something like:
.tag .icon-remove {
color:#888;
font-size:14px;
}
Here's a JSFiddle example, and here is further proof that this is definitely a font.
In version 3, they changed "export" to "unload". It still functions more or less the same.
This download fixed my VB6 EXE and Access 2016 (using ACEDAO.DLL) run-time error 429. Took me 2 long days to get it resolved because there are so many causes of 429.
http://www.microsoft.com/en-ca/download/details.aspx?id=13255
QUOTE from link: "This download will install a set of components that can be used to facilitate transfer of data between 2010 Microsoft Office System files and non-Microsoft Office applications"
You might find this article of interest which is available at codeplex.com.
The article presents a new way of expressing queries that span multiple tables in the form of declarative graph shapes.
Moreover, the article contains a thorough performance comparison of this new approach with EF queries. This analysis shows that GBQ quickly outperforms EF queries.
If it is not defined in the web service or application or server (apache or IIS) that is hosting the web service consumable then you could create infinite connections until failure
I find it easiest to understand move semantics with example code. Let's start with a very simple string class which only holds a pointer to a heap-allocated block of memory:
#include <cstring>
#include <algorithm>
class string
{
char* data;
public:
string(const char* p)
{
size_t size = std::strlen(p) + 1;
data = new char[size];
std::memcpy(data, p, size);
}
Since we chose to manage the memory ourselves, we need to follow the rule of three. I am going to defer writing the assignment operator and only implement the destructor and the copy constructor for now:
~string()
{
delete[] data;
}
string(const string& that)
{
size_t size = std::strlen(that.data) + 1;
data = new char[size];
std::memcpy(data, that.data, size);
}
The copy constructor defines what it means to copy string objects. The parameter const string& that
binds to all expressions of type string which allows you to make copies in the following examples:
string a(x); // Line 1
string b(x + y); // Line 2
string c(some_function_returning_a_string()); // Line 3
Now comes the key insight into move semantics. Note that only in the first line where we copy x
is this deep copy really necessary, because we might want to inspect x
later and would be very surprised if x
had changed somehow. Did you notice how I just said x
three times (four times if you include this sentence) and meant the exact same object every time? We call expressions such as x
"lvalues".
The arguments in lines 2 and 3 are not lvalues, but rvalues, because the underlying string objects have no names, so the client has no way to inspect them again at a later point in time.
rvalues denote temporary objects which are destroyed at the next semicolon (to be more precise: at the end of the full-expression that lexically contains the rvalue). This is important because during the initialization of b
and c
, we could do whatever we wanted with the source string, and the client couldn't tell a difference!
C++0x introduces a new mechanism called "rvalue reference" which, among other things, allows us to detect rvalue arguments via function overloading. All we have to do is write a constructor with an rvalue reference parameter. Inside that constructor we can do anything we want with the source, as long as we leave it in some valid state:
string(string&& that) // string&& is an rvalue reference to a string
{
data = that.data;
that.data = nullptr;
}
What have we done here? Instead of deeply copying the heap data, we have just copied the pointer and then set the original pointer to null (to prevent 'delete[]' from source object's destructor from releasing our 'just stolen data'). In effect, we have "stolen" the data that originally belonged to the source string. Again, the key insight is that under no circumstance could the client detect that the source had been modified. Since we don't really do a copy here, we call this constructor a "move constructor". Its job is to move resources from one object to another instead of copying them.
Congratulations, you now understand the basics of move semantics! Let's continue by implementing the assignment operator. If you're unfamiliar with the copy and swap idiom, learn it and come back, because it's an awesome C++ idiom related to exception safety.
string& operator=(string that)
{
std::swap(data, that.data);
return *this;
}
};
Huh, that's it? "Where's the rvalue reference?" you might ask. "We don't need it here!" is my answer :)
Note that we pass the parameter that
by value, so that
has to be initialized just like any other string object. Exactly how is that
going to be initialized? In the olden days of C++98, the answer would have been "by the copy constructor". In C++0x, the compiler chooses between the copy constructor and the move constructor based on whether the argument to the assignment operator is an lvalue or an rvalue.
So if you say a = b
, the copy constructor will initialize that
(because the expression b
is an lvalue), and the assignment operator swaps the contents with a freshly created, deep copy. That is the very definition of the copy and swap idiom -- make a copy, swap the contents with the copy, and then get rid of the copy by leaving the scope. Nothing new here.
But if you say a = x + y
, the move constructor will initialize that
(because the expression x + y
is an rvalue), so there is no deep copy involved, only an efficient move.
that
is still an independent object from the argument, but its construction was trivial,
since the heap data didn't have to be copied, just moved. It wasn't necessary to copy it because x + y
is an rvalue, and again, it is okay to move from string objects denoted by rvalues.
To summarize, the copy constructor makes a deep copy, because the source must remain untouched. The move constructor, on the other hand, can just copy the pointer and then set the pointer in the source to null. It is okay to "nullify" the source object in this manner, because the client has no way of inspecting the object again.
I hope this example got the main point across. There is a lot more to rvalue references and move semantics which I intentionally left out to keep it simple. If you want more details please see my supplementary answer.
I had similar issue with the index.html being cached by the browser or more tricky by middle cdn/proxies (F5 will not help you).
I looked for a solution which verifies 100% that the client has the latest index.html version, luckily I found this solution by Henrik Peinar:
https://blog.nodeswat.com/automagic-reload-for-clients-after-deploy-with-angular-4-8440c9fdd96c
The solution solve also the case where the client stays with the browser open for days, the client checks for updates on intervals and reload if newer version deployd.
The solution is a bit tricky but works like a charm:
ng cli -- prod
produces hashed files with one of them called main.[hash].jsSince Henrik Peinar solution was for angular 4, there were minor changes, I place also the fixed scripts here:
VersionCheckService :
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class VersionCheckService {
// this will be replaced by actual hash post-build.js
private currentHash = '{{POST_BUILD_ENTERS_HASH_HERE}}';
constructor(private http: HttpClient) {}
/**
* Checks in every set frequency the version of frontend application
* @param url
* @param {number} frequency - in milliseconds, defaults to 30 minutes
*/
public initVersionCheck(url, frequency = 1000 * 60 * 30) {
//check for first time
this.checkVersion(url);
setInterval(() => {
this.checkVersion(url);
}, frequency);
}
/**
* Will do the call and check if the hash has changed or not
* @param url
*/
private checkVersion(url) {
// timestamp these requests to invalidate caches
this.http.get(url + '?t=' + new Date().getTime())
.subscribe(
(response: any) => {
const hash = response.hash;
const hashChanged = this.hasHashChanged(this.currentHash, hash);
// If new version, do something
if (hashChanged) {
// ENTER YOUR CODE TO DO SOMETHING UPON VERSION CHANGE
// for an example: location.reload();
// or to ensure cdn miss: window.location.replace(window.location.href + '?rand=' + Math.random());
}
// store the new hash so we wouldn't trigger versionChange again
// only necessary in case you did not force refresh
this.currentHash = hash;
},
(err) => {
console.error(err, 'Could not get version');
}
);
}
/**
* Checks if hash has changed.
* This file has the JS hash, if it is a different one than in the version.json
* we are dealing with version change
* @param currentHash
* @param newHash
* @returns {boolean}
*/
private hasHashChanged(currentHash, newHash) {
if (!currentHash || currentHash === '{{POST_BUILD_ENTERS_HASH_HERE}}') {
return false;
}
return currentHash !== newHash;
}
}
change to main AppComponent:
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(private versionCheckService: VersionCheckService) {
}
ngOnInit() {
console.log('AppComponent.ngOnInit() environment.versionCheckUrl=' + environment.versionCheckUrl);
if (environment.versionCheckUrl) {
this.versionCheckService.initVersionCheck(environment.versionCheckUrl);
}
}
}
The post-build script that makes the magic, post-build.js:
const path = require('path');
const fs = require('fs');
const util = require('util');
// get application version from package.json
const appVersion = require('../package.json').version;
// promisify core API's
const readDir = util.promisify(fs.readdir);
const writeFile = util.promisify(fs.writeFile);
const readFile = util.promisify(fs.readFile);
console.log('\nRunning post-build tasks');
// our version.json will be in the dist folder
const versionFilePath = path.join(__dirname + '/../dist/version.json');
let mainHash = '';
let mainBundleFile = '';
// RegExp to find main.bundle.js, even if it doesn't include a hash in it's name (dev build)
let mainBundleRegexp = /^main.?([a-z0-9]*)?.js$/;
// read the dist folder files and find the one we're looking for
readDir(path.join(__dirname, '../dist/'))
.then(files => {
mainBundleFile = files.find(f => mainBundleRegexp.test(f));
if (mainBundleFile) {
let matchHash = mainBundleFile.match(mainBundleRegexp);
// if it has a hash in it's name, mark it down
if (matchHash.length > 1 && !!matchHash[1]) {
mainHash = matchHash[1];
}
}
console.log(`Writing version and hash to ${versionFilePath}`);
// write current version and hash into the version.json file
const src = `{"version": "${appVersion}", "hash": "${mainHash}"}`;
return writeFile(versionFilePath, src);
}).then(() => {
// main bundle file not found, dev build?
if (!mainBundleFile) {
return;
}
console.log(`Replacing hash in the ${mainBundleFile}`);
// replace hash placeholder in our main.js file so the code knows it's current hash
const mainFilepath = path.join(__dirname, '../dist/', mainBundleFile);
return readFile(mainFilepath, 'utf8')
.then(mainFileData => {
const replacedFile = mainFileData.replace('{{POST_BUILD_ENTERS_HASH_HERE}}', mainHash);
return writeFile(mainFilepath, replacedFile);
});
}).catch(err => {
console.log('Error with post build:', err);
});
simply place the script in (new) build folder run the script using node ./build/post-build.js
after building dist folder using ng build --prod
Add
android:clickable="true"
android:focusable="true"
For Ripple Effect
android:background="?attr/selectableItemBackgroundBorderless"
For Selectable Effect
android:background="?android:attr/selectableItemBackground"
For Button effect
android:adjustViewBounds="true" style="?android:attr/borderlessButtonStyle"
You could define a mapping of air pressure to servo angle, for example:
def calc_angle(pressure, min_p=1000, max_p=1200): return 360 * ((pressure - min_p) / float(max_p - min_p)) angle = calc_angle(pressure)
This will linearly convert pressure
values between min_p
and max_p
to angles between 0 and 360 (you could include min_a
and max_a
to constrain the angle, too).
To pick a data structure, I wouldn't use a list but you could look up values in a dictionary:
d = {1000:0, 1001: 1.8, ...} angle = d[pressure]
but this would be rather time-consuming to type out!
I've tried to support the -ve values for @Ivan Stin excellent 2nd method. (Major credit goes to @Ivan Stin for his method)
public static float round(float value, int scale) {
int pow = 10;
for (int i = 1; i < scale; i++) {
pow *= 10;
}
float tmp = value * pow;
float tmpSub = tmp - (int) tmp;
return ( (float) ( (int) (
value >= 0
? (tmpSub >= 0.5f ? tmp + 1 : tmp)
: (tmpSub >= -0.5f ? tmp : tmp - 1)
) ) ) / pow;
// Below will only handles +ve values
// return ( (float) ( (int) ((tmp - (int) tmp) >= 0.5f ? tmp + 1 : tmp) ) ) / pow;
}
Below are the tests cases I've tried. Please let me know if this is not addressing any other cases.
@Test
public void testFloatRound() {
// +ve values
Assert.assertEquals(0F, NumberUtils.round(0F), 0);
Assert.assertEquals(1F, NumberUtils.round(1F), 0);
Assert.assertEquals(23.46F, NumberUtils.round(23.4567F), 0);
Assert.assertEquals(23.45F, NumberUtils.round(23.4547F), 0D);
Assert.assertEquals(1.00F, NumberUtils.round(0.49999999999999994F + 0.5F), 0);
Assert.assertEquals(123.12F, NumberUtils.round(123.123F), 0);
Assert.assertEquals(0.12F, NumberUtils.round(0.123F), 0);
Assert.assertEquals(0.55F, NumberUtils.round(0.55F), 0);
Assert.assertEquals(0.55F, NumberUtils.round(0.554F), 0);
Assert.assertEquals(0.56F, NumberUtils.round(0.556F), 0);
Assert.assertEquals(123.13F, NumberUtils.round(123.126F), 0);
Assert.assertEquals(123.15F, NumberUtils.round(123.15F), 0);
Assert.assertEquals(123.17F, NumberUtils.round(123.1666F), 0);
Assert.assertEquals(123.46F, NumberUtils.round(123.4567F), 0);
Assert.assertEquals(123.87F, NumberUtils.round(123.8711F), 0);
Assert.assertEquals(123.15F, NumberUtils.round(123.15123F), 0);
Assert.assertEquals(123.89F, NumberUtils.round(123.8909F), 0);
Assert.assertEquals(124.00F, NumberUtils.round(123.9999F), 0);
Assert.assertEquals(123.70F, NumberUtils.round(123.7F), 0);
Assert.assertEquals(123.56F, NumberUtils.round(123.555F), 0);
Assert.assertEquals(123.00F, NumberUtils.round(123.00F), 0);
Assert.assertEquals(123.50F, NumberUtils.round(123.50F), 0);
Assert.assertEquals(123.93F, NumberUtils.round(123.93F), 0);
Assert.assertEquals(123.93F, NumberUtils.round(123.9312F), 0);
Assert.assertEquals(123.94F, NumberUtils.round(123.9351F), 0);
Assert.assertEquals(123.94F, NumberUtils.round(123.9350F), 0);
Assert.assertEquals(123.94F, NumberUtils.round(123.93501F), 0);
Assert.assertEquals(99.99F, NumberUtils.round(99.99F), 0);
Assert.assertEquals(100.00F, NumberUtils.round(99.999F), 0);
Assert.assertEquals(100.00F, NumberUtils.round(99.9999F), 0);
// -ve values
Assert.assertEquals(-123.94F, NumberUtils.round(-123.93501F), 0);
Assert.assertEquals(-123.00F, NumberUtils.round(-123.001F), 0);
Assert.assertEquals(-0.94F, NumberUtils.round(-0.93501F), 0);
Assert.assertEquals(-1F, NumberUtils.round(-1F), 0);
Assert.assertEquals(-0.50F, NumberUtils.round(-0.50F), 0);
Assert.assertEquals(-0.55F, NumberUtils.round(-0.55F), 0);
Assert.assertEquals(-0.55F, NumberUtils.round(-0.554F), 0);
Assert.assertEquals(-0.56F, NumberUtils.round(-0.556F), 0);
Assert.assertEquals(-0.12F, NumberUtils.round(-0.1234F), 0);
Assert.assertEquals(-0.12F, NumberUtils.round(-0.123456789F), 0);
Assert.assertEquals(-0.13F, NumberUtils.round(-0.129F), 0);
Assert.assertEquals(-99.99F, NumberUtils.round(-99.99F), 0);
Assert.assertEquals(-100.00F, NumberUtils.round(-99.999F), 0);
Assert.assertEquals(-100.00F, NumberUtils.round(-99.9999F), 0);
}
You have a few options here:
Context
as an argument to FeedAdapter and keep it as class fieldContext
when you need it. I strongly suggest reading about it. There is a great tool for that -- Dagger by SquareGet it from any View
object. In your case this might work for you:
holder.pub_image.getContext()
As pub_image
is a ImageView
.
In addition to using pure threads or the Celery queue (note that flask-celery is no longer required), you could also have a look at flask-apscheduler:
https://github.com/viniciuschiele/flask-apscheduler
A simple example copied from https://github.com/viniciuschiele/flask-apscheduler/blob/master/examples/jobs.py:
from flask import Flask
from flask_apscheduler import APScheduler
class Config(object):
JOBS = [
{
'id': 'job1',
'func': 'jobs:job1',
'args': (1, 2),
'trigger': 'interval',
'seconds': 10
}
]
SCHEDULER_API_ENABLED = True
def job1(a, b):
print(str(a) + ' ' + str(b))
if __name__ == '__main__':
app = Flask(__name__)
app.config.from_object(Config())
scheduler = APScheduler()
# it is also possible to enable the API directly
# scheduler.api_enabled = True
scheduler.init_app(app)
scheduler.start()
app.run()
c = a + b
str(c)
Actually, in this last line you are not changing the type of the variable c. If you do
c_str=str(c)
print "a + b as integers: " + c_str
it should work.
I struggled with this recently with and older project.
I managed to track down the problem after checking what version of the dll that actually was in the bin folder.
I had a post-build script that copied dependent assemblies from a dll library folder to the bin folder. A common setup from the days before nuget.
So every time I built the post-build script replaced the correct version of Json.net with the older one
Try this:
/etc/nginx/sites-available/default
listen 80; ## listen for ipv4; this line is default and implied
listen [::]:80 default_server ipv6only=on; ## listen for ipv6
server_name
alone# Make site accessible (...)
server_name localhost;
index.php
to the index
lineroot /usr/share/nginx/www;
index index.php index.html index.htm;
location ~ \.php$ {}
# pass the PHP scripts to FastCGI server listening on (...)
#
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
# NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
# With php5-cgi alone:
#fastcgi_pass 127.0.0.1:9000;
# With php5-fpm:
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
/etc/php5/fpm/php.ini
and make sure cgi.fix_pathinfo
is set to 0
sudo service nginx restart && sudo service php5-fpm restart
I have just started using Linux a week ago, so I really hope to help you on this. I am using nano text editor to edit the files. run apt-get install nano if you don't have it. Google on it to know more.
Most likely JDK configuration is not valid, try to remove and add the JDK again as I've described in the related question here.
You may already have this working, but the I created a test project with the classes below allowing you to retrieve the data into an entity, projection or dto.
Projection - this will return the code column twice, once named code and also named text (for example only). As you say above, you don't need the @Projection annotation
import org.springframework.beans.factory.annotation.Value;
public interface DeadlineTypeProjection {
String getId();
// can get code and or change name of getter below
String getCode();
// Points to the code attribute of entity class
@Value(value = "#{target.code}")
String getText();
}
DTO class - not sure why this was inheriting from your base class and then redefining the attributes. JsonProperty just an example of how you'd change the name of the field passed back to a REST end point
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class DeadlineType {
String id;
// Use this annotation if you need to change the name of the property that is passed back from controller
// Needs to be called code to be used in Repository
@JsonProperty(value = "text")
String code;
}
Entity class
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Data
@Entity
@Table(name = "deadline_type")
public class ABDeadlineType {
@Id
private String id;
private String code;
}
Repository - your repository extends JpaRepository<ABDeadlineType, Long> but the Id is a String, so updated below to JpaRepository<ABDeadlineType, String>
import com.example.demo.entity.ABDeadlineType;
import com.example.demo.projection.DeadlineTypeProjection;
import com.example.demo.transfer.DeadlineType;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface ABDeadlineTypeRepository extends JpaRepository<ABDeadlineType, String> {
List<ABDeadlineType> findAll();
List<DeadlineType> findAllDtoBy();
List<DeadlineTypeProjection> findAllProjectionBy();
}
Example Controller - accesses the repository directly to simplify code
@RequestMapping(value = "deadlinetype")
@RestController
public class DeadlineTypeController {
private final ABDeadlineTypeRepository abDeadlineTypeRepository;
@Autowired
public DeadlineTypeController(ABDeadlineTypeRepository abDeadlineTypeRepository) {
this.abDeadlineTypeRepository = abDeadlineTypeRepository;
}
@GetMapping(value = "/list")
public ResponseEntity<List<ABDeadlineType>> list() {
List<ABDeadlineType> types = abDeadlineTypeRepository.findAll();
return ResponseEntity.ok(types);
}
@GetMapping(value = "/listdto")
public ResponseEntity<List<DeadlineType>> listDto() {
List<DeadlineType> types = abDeadlineTypeRepository.findAllDtoBy();
return ResponseEntity.ok(types);
}
@GetMapping(value = "/listprojection")
public ResponseEntity<List<DeadlineTypeProjection>> listProjection() {
List<DeadlineTypeProjection> types = abDeadlineTypeRepository.findAllProjectionBy();
return ResponseEntity.ok(types);
}
}
Hope that helps
Les
Yes, here you can use LIMIT
.
You can try it by the below query:
SELECT * FROM employee_list SORT BY salary DESC LIMIT 2
Yes. Problem is in wrong notation. Use:
$this->sendRequest($uri)
Instead. Or
self::staticMethod()
for static methods. Also read this for getting idea of OOP - http://www.php.net/manual/en/language.oop5.basic.php
Adding/changing style of the elements in code is a bad practice. Today you want to change the background color and tomorrow you would like to change background image and after tomorrow you decided that it would be also nice to change the border.
Editing the code every-time only because the design requirements changes is a pain. Also, if your project will grow, changing js files will be even more pain. More code, more pain.
Try to eliminate use of hard coded styles, this will save you time and, if you do it right, you could ask to do the "change-color" task to someone else.
So, instead of changing direct properties of style, you can add/remove CSS classes on nodes. In your specific case, you only need to do this for parent node - "div" and then, style the subnodes through CSS. So no need to apply specific style property to DIV and to H2.
One more recommendation point. Try not to connect nodes hardcoded, but use some semantic to do that. For example: "To add events to all nodes which have class 'content'.
In conclusion, here is the code which I would use for such tasks:
//for adding a css class
function onOver(node){
node.className = node.className + ' Hover';
}
//for removing a css class
function onOut(node){
node.className = node.className.replace('Hover','');
}
function connect(node,event,fnc){
if(node.addEventListener){
node.addEventListener(event.substring(2,event.length),function(){
fnc(node);
},false);
}else if(node.attachEvent){
node.attachEvent(event,function(){
fnc(node);
});
}
}
// run this one when window is loaded
var divs = document.getElementsByTagName("div");
for(var i=0,div;div =divs[i];i++){
if(div.className.match('content')){
connect(div,'onmouseover',onOver);
connect(div,'onmouseout',onOut);
}
}
And you CSS whould be like this:
.content {
background-color: blue;
}
.content.Hover{
background-color: red;
}
.content.Hover h2{
background-color : yellow;
}
First you need to get the current date
var currentDate = new Date();
Then you need to place it in the arguments of datepicker like given below
$("#datepicker").datepicker("setDate", currentDate);
Check the following jsfiddle.
Have you try $ sudo ./catalina.sh stop
? It worked in my case.
A comparison between the different Visual Studio Express editions can be found at Visual Studio Express (archive.org link). The difference between Windows and Windows Desktop is that with the Windows edition you can build Windows Store Apps (using .NET, WPF/XAML) while the Windows Desktop edition allows you to write classic Windows Desktop applications. It is possible to install both products on the same machine.
Visual Studio Express 2010 allows you to build Windows Desktop applications. Writing Windows Store applications is not possible with this product.
For learning I would suggest Notepad and the command line. While an IDE provides significant productivity enhancements to professionals, it can be intimidating to a beginner. If you want to use an IDE nevertheless I would recommend Visual Studio Express 2013 for Windows Desktop.