Programs & Examples On #Shared libraries

Shared libraries are libraries that are loaded by programs when they start. A single shared copy of each library is loaded into physical memory and may be used by multiple processes at the same time. This reduces memory use and improves system performance. This tag should never be used alone.

Why can't Python find shared objects that are in directories in sys.path?

You can also set LD_RUN_PATH to /usr/local/lib in your user environment when you compile pycurl in the first place. This will embed /usr/local/lib in the RPATH attribute of the C extension module .so so that it automatically knows where to find the library at run time without having to have LD_LIBRARY_PATH set at run time.

ld cannot find an existing library

Installing libgl1-mesa-dev from the Ubuntu repo resolved this problem for me.

Importing from a relative path in Python

Approch used by me is similar to Gary Beardsley mentioned above with small change.

Filename: Server.py

import os, sys
script_path = os.path.realpath(os.path.dirname(__name__))
os.chdir(script_path)
sys.path.append("..")
# above mentioned steps will make 1 level up module available for import
# here Client, Server and Common all 3 can be imported.

# below mentioned import will be relative to root project
from Common import Common
from Client import Client

What is a file with extension .a?

.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.

How do I find out what all symbols are exported from a shared object?

see man nm

GNU nm lists the symbols from object files objfile.... If no object files are listed as arguments, nm assumes the file a.out.

error while loading shared libraries: libncurses.so.5:

In Fedora 28 use:

sudo dnf install ncurses-compat-libs

Build .so file from .c file using gcc command line

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

Why do I have to define LD_LIBRARY_PATH with an export every time I run my application?

You could add in your code a call system with the new definition:

sprintf(newdef,"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:%s:%s",ld1,ld2);
system(newdef);

But, I don't know it that is the rigth solution but it works.

Regards

How to specify non-default shared-library path in GCC Linux? Getting "error while loading shared libraries" when running

There are two ways to achieve that:

  • Use -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.

Difference between static and shared libraries?

Shared libraries are .so (or in Windows .dll, or in OS X .dylib) files. All the code relating to the library is in this file, and it is referenced by programs using it at run-time. A program using a shared library only makes reference to the code that it uses in the shared library.

Static libraries are .a (or in Windows .lib) files. All the code relating to the library is in this file, and it is directly linked into the program at compile time. A program using a static library takes copies of the code that it uses from the static library and makes it part of the program. [Windows also has .lib files which are used to reference .dll files, but they act the same way as the first one].

There are advantages and disadvantages in each method:

  • Shared libraries reduce the amount of code that is duplicated in each program that makes use of the library, keeping the binaries small. It also allows you to replace the shared object with one that is functionally equivalent, but may have added performance benefits without needing to recompile the program that makes use of it. Shared libraries will, however have a small additional cost for the execution of the functions as well as a run-time loading cost as all the symbols in the library need to be connected to the things they use. Additionally, shared libraries can be loaded into an application at run-time, which is the general mechanism for implementing binary plug-in systems.

  • Static libraries increase the overall size of the binary, but it means that you don't need to carry along a copy of the library that is being used. As the code is connected at compile time there are not any additional run-time loading costs. The code is simply there.

Personally, I prefer shared libraries, but use static libraries when needing to ensure that the binary does not have many external dependencies that may be difficult to meet, such as specific versions of the C++ standard library or specific versions of the Boost C++ library.

"relocation R_X86_64_32S against " linking Error

I've got a similar error when installing FCL that needs CCD lib(libccd) like this:

/usr/bin/ld: /usr/local/lib/libccd.a(ccd.o): relocation R_X86_64_32S against `a local symbol' can not be used when making a shared object; recompile with -fPIC

I find that there is two different files named "libccd.a" :

  1. /usr/local/lib/libccd.a
  2. /usr/local/lib/x86_64-linux-gnu/libccd.a

I solved the problem by removing the first file.

How do you find what version of libstdc++ library is installed on your linux machine?

To find which library is being used you could run

 $ /sbin/ldconfig -p | grep stdc++
    libstdc++.so.6 (libc6) => /usr/lib/libstdc++.so.6

The list of compatible versions for libstdc++ version 3.4.0 and above is provided by

 $ strings /usr/lib/libstdc++.so.6 | grep LIBCXX
 GLIBCXX_3.4
 GLIBCXX_3.4.1
 GLIBCXX_3.4.2
 ...

For earlier versions the symbol GLIBCPP is defined.

The date stamp of the library is defined in a macro __GLIBCXX__ or __GLIBCPP__ depending on the version:

// libdatestamp.cxx
#include <cstdio>

int main(int argc, char* argv[]){
#ifdef __GLIBCPP__
    std::printf("GLIBCPP: %d\n",__GLIBCPP__);
#endif
#ifdef __GLIBCXX__
    std::printf("GLIBCXX: %d\n",__GLIBCXX__);
#endif
   return 0;
}

$ g++ libdatestamp.cxx -o libdatestamp
$ ./libdatestamp
GLIBCXX: 20101208

The table of datestamps of libstdc++ versions is listed in the documentation:

When to use dynamic vs. static libraries

Ulrich Drepper's paper on "How to Write Shared Libraries" is also good resource that details how best to take advantage of shared libraries, or what he refers to as "Dynamic Shared Objects" (DSOs). It focuses more on shared libraries in the ELF binary format, but some discussions are suitable for Windows DLLs as well.

What are .a and .so files?

.a are static libraries. If you use code stored inside them, it's taken from them and embedded into your own binary. In Visual Studio, these would be .lib files.

.so are dynamic libraries. If you use code stored inside them, it's not taken and embedded into your own binary. Instead it's just referenced, so the binary will depend on them and the code from the so file is added/loaded at runtime. In Visual Studio/Windows these would be .dll files (with small .lib files containing linking information).

/usr/bin/ld: cannot find

When you make the call to gcc it should say

g++ -Wall -I/home/alwin/Development/Calculator/ -L/opt/lib main.cpp -lcalc -o calculator

not -libcalc.so 

I have a similar problem with auto-generated makes.

You can create a soft link from your compile directory to the library directory. Then the library becomes "local".

cd /compile/directory

ln -s  /path/to/libcalc.so libcalc.so

How to install the Six module in Python2.7

here's what six is:

pip search six
six                       - Python 2 and 3 compatibility utilities

to install:

pip install six

though if you did install python-dateutil from pip six should have been set as a dependency.

N.B.: to install pip run easy_install pip from command line.

What's the difference between .so, .la and .a library files?

.so files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.

.a files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar command -- a predecessor of tar that's now just used for making libraries) of the original .o object files.

.la files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?

Static and dynamic libraries each have pros and cons.

Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.

Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.

Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.

Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.

Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.

Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.

Dynamic libraries are especially useful for system libraries, like libc. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.

How do I view the list of functions a Linux shared library is exporting?

On a MAC, you need to use nm *.o | c++filt, as there is no -C option in nm.

ld cannot find -l<library>

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.

C++ Dynamic Shared Library on Linux

myclass.h

#ifndef __MYCLASS_H__
#define __MYCLASS_H__

class MyClass
{
public:
  MyClass();

  /* use virtual otherwise linker will try to perform static linkage */
  virtual void DoSomething();

private:
  int x;
};

#endif

myclass.cc

#include "myclass.h"
#include <iostream>

using namespace std;

extern "C" MyClass* create_object()
{
  return new MyClass;
}

extern "C" void destroy_object( MyClass* object )
{
  delete object;
}

MyClass::MyClass()
{
  x = 20;
}

void MyClass::DoSomething()
{
  cout<<x<<endl;
}

class_user.cc

#include <dlfcn.h>
#include <iostream>
#include "myclass.h"

using namespace std;

int main(int argc, char **argv)
{
  /* on Linux, use "./myclass.so" */
  void* handle = dlopen("myclass.so", RTLD_LAZY);

  MyClass* (*create)();
  void (*destroy)(MyClass*);

  create = (MyClass* (*)())dlsym(handle, "create_object");
  destroy = (void (*)(MyClass*))dlsym(handle, "destroy_object");

  MyClass* myClass = (MyClass*)create();
  myClass->DoSomething();
  destroy( myClass );
}

On Mac OS X, compile with:

g++ -dynamiclib -flat_namespace myclass.cc -o myclass.so
g++ class_user.cc -o class_user

On Linux, compile with:

g++ -fPIC -shared myclass.cc -o myclass.so
g++ class_user.cc -ldl -o class_user

If this were for a plugin system, you would use MyClass as a base class and define all the required functions virtual. The plugin author would then derive from MyClass, override the virtuals and implement create_object and destroy_object. Your main application would not need to be changed in any way.

How to create a shared library with cmake?

First, this is the directory layout that I am using:

.
+-- include
¦   +-- class1.hpp
¦   +-- ...
¦   +-- class2.hpp
+-- src
    +-- class1.cpp
    +-- ...
    +-- class2.cpp

After a couple of days taking a look into this, this is my favourite way of doing this thanks to modern CMake:

cmake_minimum_required(VERSION 3.5)
project(mylib VERSION 1.0.0 LANGUAGES CXX)

set(DEFAULT_BUILD_TYPE "Release")

if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
  message(STATUS "Setting build type to '${DEFAULT_BUILD_TYPE}' as none was specified.")
  set(CMAKE_BUILD_TYPE "${DEFAULT_BUILD_TYPE}" CACHE STRING "Choose the type of build." FORCE)
  # Set the possible values of build type for cmake-gui
  set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release" "MinSizeRel" "RelWithDebInfo")
endif()

include(GNUInstallDirs)

set(SOURCE_FILES src/class1.cpp src/class2.cpp)

add_library(${PROJECT_NAME} ...)

target_include_directories(${PROJECT_NAME} PUBLIC
    $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
    $<INSTALL_INTERFACE:include>
    PRIVATE src)

set_target_properties(${PROJECT_NAME} PROPERTIES
    VERSION ${PROJECT_VERSION}
    SOVERSION 1)

install(TARGETS ${PROJECT_NAME} EXPORT MyLibConfig
    ARCHIVE  DESTINATION ${CMAKE_INSTALL_LIBDIR}
    LIBRARY  DESTINATION ${CMAKE_INSTALL_LIBDIR}
    RUNTIME  DESTINATION ${CMAKE_INSTALL_BINDIR})
install(DIRECTORY include/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME})

install(EXPORT MyLibConfig DESTINATION share/MyLib/cmake)

export(TARGETS ${PROJECT_NAME} FILE MyLibConfig.cmake)

After running CMake and installing the library, there is no need to use Find***.cmake files, it can be used like this:

find_package(MyLib REQUIRED)

#No need to perform include_directories(...)
target_link_libraries(${TARGET} mylib)

That's it, if it has been installed in a standard directory it will be found and there is no need to do anything else. If it has been installed in a non-standard path, it is also easy, just tell CMake where to find MyLibConfig.cmake using:

cmake -DMyLib_DIR=/non/standard/install/path ..

I hope this helps everybody as much as it has helped me. Old ways of doing this were quite cumbersome.

Linux error while loading shared libraries: cannot open shared object file: No such file or directory

I use Ubuntu 18.04

Installing the corresponding "-dev" package worked for me,

sudo apt install libgconf2-dev

I was getting the below error till I installed the above package,

turtl: error while loading shared libraries: libgconf-2.so.4: cannot open shared object file: No such file or directory

Compilation fails with "relocation R_X86_64_32 against `.rodata.str1.8' can not be used when making a shared object"

Fixed it with -no-pie option in linker stage:

g++-8 -L"/home/pedro/workspace/project/lib" -no-pie ...

INSTALL_FAILED_MISSING_SHARED_LIBRARY error in Android

  1. Open eclipse
  2. Goto:

    project>Properties>Android> select: google APIs Android 4.0.3

  3. Click Icon:

    Android Virtual Device Manager>Edit> Slect box in Tabget>Google APIs APIsLevel15
    and select Built-in: is WQVGA400 > Edit AVD > Start

How to add additional libraries to Visual Studio project?

Add #pragma comment(lib, "Your library name here") to your source.

How to show all shared libraries used by executables in Linux?

  1. Use ldd to list shared libraries for each executable.
  2. Cleanup the output
  3. Sort, compute counts, sort by count

To find the answer for all executables in the "/bin" directory:

find /bin -type f -perm /a+x -exec ldd {} \; \
| grep so \
| sed -e '/^[^\t]/ d' \
| sed -e 's/\t//' \
| sed -e 's/.*=..//' \
| sed -e 's/ (0.*)//' \
| sort \
| uniq -c \
| sort -n

Change "/bin" above to "/" to search all directories.

Output (for just the /bin directory) will look something like this:

  1 /lib64/libexpat.so.0
  1 /lib64/libgcc_s.so.1
  1 /lib64/libnsl.so.1
  1 /lib64/libpcre.so.0
  1 /lib64/libproc-3.2.7.so
  1 /usr/lib64/libbeecrypt.so.6
  1 /usr/lib64/libbz2.so.1
  1 /usr/lib64/libelf.so.1
  1 /usr/lib64/libpopt.so.0
  1 /usr/lib64/librpm-4.4.so
  1 /usr/lib64/librpmdb-4.4.so
  1 /usr/lib64/librpmio-4.4.so
  1 /usr/lib64/libsqlite3.so.0
  1 /usr/lib64/libstdc++.so.6
  1 /usr/lib64/libz.so.1
  2 /lib64/libasound.so.2
  2 /lib64/libblkid.so.1
  2 /lib64/libdevmapper.so.1.02
  2 /lib64/libpam_misc.so.0
  2 /lib64/libpam.so.0
  2 /lib64/libuuid.so.1
  3 /lib64/libaudit.so.0
  3 /lib64/libcrypt.so.1
  3 /lib64/libdbus-1.so.3
  4 /lib64/libresolv.so.2
  4 /lib64/libtermcap.so.2
  5 /lib64/libacl.so.1
  5 /lib64/libattr.so.1
  5 /lib64/libcap.so.1
  6 /lib64/librt.so.1
  7 /lib64/libm.so.6
  9 /lib64/libpthread.so.0
 13 /lib64/libselinux.so.1
 13 /lib64/libsepol.so.1
 22 /lib64/libdl.so.2
 83 /lib64/ld-linux-x86-64.so.2
 83 /lib64/libc.so.6

Edit - Removed "grep -P"

How to initialize a variable of date type in java?

To initialize to current date, you could do something like:

Date firstDate = new Date();

To get it from String, you could use SimpleDateFormat like:

String dateInString = "10-Jan-2016";
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
try {
    Date date = formatter.parse(dateInString);
    System.out.println(date);
    System.out.println(formatter.format(date));
} catch (ParseException e) {
    //handle exception if date is not in "dd-MMM-yyyy" format
}

ObservableCollection not noticing when Item in it changes (even with INotifyPropertyChanged)

I know that I'm too late for this party, but maybe - it will help to someone..

Here you can find my implementation of ObservableCollectionEx. It has some features:

  • it supports everything from ObservableCollection
  • it's thread safe
  • it supports ItemPropertyChanged event (it raises each time when Item.PropertyChanged item is fired)
  • it supports filters (so, you could create ObservableCollectionEx, pass another collection as Source to it, and Filter with simple predicate. Very useful in WPF, I use this feature a lot in my applications). Even more - filter tracks changes of items via INotifyPropertyChanged interface.

Of course, any comments are appreciated ;)

Select values from XML field in SQL Server 2008

This post was helpful to solve my problem which has a little different XML format... my XML contains a list of keys like the following example and I store the XML in the SourceKeys column in a table named DeleteBatch:

<k>1</k>
<k>2</k>
<k>3</k>

Create the table and populate it with some data:

CREATE TABLE dbo.DeleteBatch (
    ExecutionKey INT PRIMARY KEY,
    SourceKeys XML)

INSERT INTO dbo.DeleteBatch ( ExecutionKey, SourceKeys )
SELECT 1, 
    (CAST('<k>1</k><k>2</k><k>3</k>' AS XML))

INSERT INTO dbo.DeleteBatch ( ExecutionKey, SourceKeys )
SELECT 2, 
    (CAST('<k>100</k><k>101</k>' AS XML))

Here's my SQL to select the keys from the XML:

SELECT ExecutionKey, p.value('.', 'int') AS [Key]
FROM dbo.DeleteBatch
    CROSS APPLY SourceKeys.nodes('/k') t(p)

Here's the query results...

ExecutionKey    Key
1   1
1   2
1   3
2   100
2   101

JavaScript require() on client side

You can create elements to the DOM, which loads items.

Like such:

var myScript = document.createElement('script'); // Create new script element
myScript.type = 'text/javascript'; // Set appropriate type
myScript.src = './js/myclass.js'; // Load javascript file

PowerShell on Windows 7: Set-ExecutionPolicy for regular users

This should solve your problem, you should try to run the following below:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser 

How do I make an HTTP request in Swift?

Details

  • Xcode 9.2, Swift 4
  • Xcode 10.2.1 (10E1001), Swift 5

Info.plist

NSAppTransportSecurity

Add to the info plist:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

Alamofire Sample

Alamofire

import Alamofire

class AlamofireDataManager {
    fileprivate let queue: DispatchQueue
    init(queue: DispatchQueue) { self.queue = queue }

    private func createError(message: String, code: Int) -> Error {
        return NSError(domain: "dataManager", code: code, userInfo: ["message": message ])
    }

    private func make(session: URLSession = URLSession.shared, request: URLRequest, closure: ((Result<[String: Any]>) -> Void)?) {
        Alamofire.request(request).responseJSON { response in
            let complete: (Result<[String: Any]>) ->() = { result in DispatchQueue.main.async { closure?(result) } }
            switch response.result {
                case .success(let value): complete(.success(value as! [String: Any]))
                case .failure(let error): complete(.failure(error))
            }
        }
    }

    func searchRequest(term: String, closure: ((Result<[String: Any]>) -> Void)?) {
        guard let url = URL(string: "https://itunes.apple.com/search?term=\(term.replacingOccurrences(of: " ", with: "+"))") else { return }
        let request = URLRequest(url: url)
        make(request: request) { response in closure?(response) }
    }
}

Usage of Alamofire sample

private lazy var alamofireDataManager = AlamofireDataManager(queue: DispatchQueue(label: "DataManager.queue", qos: .utility))
//.........

alamofireDataManager.searchRequest(term: "jack johnson") { result in
      print(result.value ?? "no data")
      print(result.error ?? "no error")
}

URLSession Sample

import Foundation

class DataManager {

    fileprivate let queue: DispatchQueue
        init(queue: DispatchQueue) { self.queue = queue }

    private func createError(message: String, code: Int) -> Error {
        return NSError(domain: "dataManager", code: code, userInfo: ["message": message ])
    }

    private func make(session: URLSession = URLSession.shared, request: URLRequest, closure: ((_ json: [String: Any]?, _ error: Error?)->Void)?) {
        let task = session.dataTask(with: request) { [weak self] data, response, error in
            self?.queue.async {
                let complete: (_ json: [String: Any]?, _ error: Error?) ->() = { json, error in DispatchQueue.main.async { closure?(json, error) } }

                guard let self = self, error == nil else { complete(nil, error); return }
                guard let data = data else { complete(nil, self.createError(message: "No data", code: 999)); return }

                do {
                    if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                        complete(json, nil)
                    }
                } catch let error { complete(nil, error); return }
            }
        }

        task.resume()
    }

    func searchRequest(term: String, closure: ((_ json: [String: Any]?, _ error: Error?)->Void)?) {
        let url = URL(string: "https://itunes.apple.com/search?term=\(term.replacingOccurrences(of: " ", with: "+"))")
        let request = URLRequest(url: url!)
        make(request: request) { json, error in closure?(json, error) }
    }
}

Usage of URLSession sample

private lazy var dataManager = DataManager(queue: DispatchQueue(label: "DataManager.queue", qos: .utility))
// .......
dataManager.searchRequest(term: "jack johnson") { json, error  in
      print(error ?? "nil")
      print(json ?? "nil")
      print("Update views")
}

Results

enter image description here

CRC32 C or C++ implementation

I am the author of the source code at the specified link. While the intention of the source code license is not clear (it will be later today), the code is in fact open and free for use in your free or commercial applications with no strings attached.

Is HTML considered a programming language?

I think not exactly a programming language, but exactly what its name says: a markup language. We cannot program using just pure, HTML. But just annotate how to present content.

But if you consider programming the act of tell the computer how to present contents, it is a programming language.

git remove merge commit from history

To Just Remove a Merge Commit

If all you want to do is to remove a merge commit (2) so that it is like it never happened, the command is simply as follows

git rebase --onto <sha of 1> <sha of 2> <blue branch>

And now the purple branch isn't in the commit log of blue at all and you have two separate branches again. You can then squash the purple independently and do whatever other manipulations you want without the merge commit in the way.

Clear android application user data

This command worked for me:

adb shell pm clear packageName

Ansible - Use default if a variable is not defined

If you are assigning default value for boolean fact then ensure that no quotes is used inside default().

- name: create bool default
  set_fact:
    name: "{{ my_bool | default(true) }}"

For other variables used the same method given in verified answer.

- name: Create user
  user:
    name: "{{ my_variable | default('default_value') }}"

How to find GCD, LCM on a set of numbers

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int n0 = input.nextInt(); // number of intended input.
        int [] MyList = new int [n0];

        for (int i = 0; i < n0; i++)
            MyList[i] = input.nextInt();
            //input values stored in an array
        int i = 0;
        int count = 0;
            int gcd = 1; // Initial gcd is 1
            int k = 2; // Possible gcd
            while (k <= MyList[i] && k <= MyList[i]) {
                if (MyList[i] % k == 0 && MyList[i] % k == 0)
                    gcd = k; // Update gcd
                k++;
                count++; //checking array for gcd
            }
           // int i = 0;
            MyList [i] = gcd;
            for (int e: MyList) {
                System.out.println(e);

            }

            }

        }

Show/hide 'div' using JavaScript

How to show or hide an element:

In order to show or hide an element, manipulate the element's style property. In most cases, you probably just want to change the element's display property:

element.style.display = 'none';           // Hide
element.style.display = 'block';          // Show
element.style.display = 'inline';         // Show
element.style.display = 'inline-block';   // Show

Alternatively, if you would still like the element to occupy space (like if you were to hide a table cell), you could change the element's visibility property instead:

element.style.visibility = 'hidden';      // Hide
element.style.visibility = 'visible';     // Show

Hiding a collection of elements:

If you want to hide a collection of elements, just iterate over each element and change the element's display to none:

function hide (elements) {
  elements = elements.length ? elements : [elements];
  for (var index = 0; index < elements.length; index++) {
    elements[index].style.display = 'none';
  }
}
// Usage:
hide(document.querySelectorAll('.target'));
hide(document.querySelector('.target'));
hide(document.getElementById('target'));

_x000D_
_x000D_
hide(document.querySelectorAll('.target'));_x000D_
_x000D_
function hide (elements) {_x000D_
  elements = elements.length ? elements : [elements];_x000D_
  for (var index = 0; index < elements.length; index++) {_x000D_
    elements[index].style.display = 'none';_x000D_
  }_x000D_
}
_x000D_
<div class="target">This div will be hidden.</div>_x000D_
_x000D_
<span class="target">This span will be hidden as well.</span>
_x000D_
_x000D_
_x000D_

Showing a collection of elements:

Most of the time, you will probably just be toggling between display: none and display: block, which means that the following may be sufficient when showing a collection of elements.

You can optionally specify the desired display as the second argument if you don't want it to default to block.

function show (elements, specifiedDisplay) {
  elements = elements.length ? elements : [elements];
  for (var index = 0; index < elements.length; index++) {
    elements[index].style.display = specifiedDisplay || 'block';
  }
}
// Usage:
var elements = document.querySelectorAll('.target');
show(elements);

show(elements, 'inline-block'); // The second param allows you to specify a display value

_x000D_
_x000D_
var elements = document.querySelectorAll('.target');_x000D_
_x000D_
show(elements, 'inline-block'); // The second param allows you to specify a display value_x000D_
_x000D_
show(document.getElementById('hidden-input'));_x000D_
_x000D_
function show (elements, specifiedDisplay) {_x000D_
  elements = elements.length ? elements : [elements];_x000D_
  for (var index = 0; index < elements.length; index++) {_x000D_
    elements[index].style.display = specifiedDisplay || 'block';_x000D_
  }_x000D_
}
_x000D_
<div class="target" style="display: none">This hidden div should have a display of 'inline-block' when it is shown.</div>_x000D_
_x000D_
<span>Inline span..</span>_x000D_
_x000D_
<input id="hidden-input" />
_x000D_
_x000D_
_x000D_

Alternatively, a better approach for showing the element(s) would be to merely remove the inline display styling in order to revert it back to its initial state. Then check the computed display style of the element in order to determine whether it is being hidden by a cascaded rule. If so, then show the element.

function show (elements, specifiedDisplay) {
  var computedDisplay, element, index;

  elements = elements.length ? elements : [elements];
  for (index = 0; index < elements.length; index++) {
    element = elements[index];

    // Remove the element's inline display styling
    element.style.display = '';
    computedDisplay = window.getComputedStyle(element, null).getPropertyValue('display');

    if (computedDisplay === 'none') {
        element.style.display = specifiedDisplay || 'block';
    }
  }
}

_x000D_
_x000D_
show(document.querySelectorAll('.target'));_x000D_
_x000D_
function show (elements, specifiedDisplay) {_x000D_
  var computedDisplay, element, index;_x000D_
_x000D_
  elements = elements.length ? elements : [elements];_x000D_
  for (index = 0; index < elements.length; index++) {_x000D_
    element = elements[index];_x000D_
_x000D_
    // Remove the element's inline display styling_x000D_
    element.style.display = '';_x000D_
    computedDisplay = window.getComputedStyle(element, null).getPropertyValue('display');_x000D_
_x000D_
    if (computedDisplay === 'none') {_x000D_
        element.style.display = specifiedDisplay || 'block';_x000D_
    }_x000D_
  }_x000D_
}
_x000D_
<span class="target" style="display: none">Should revert back to being inline.</span>_x000D_
_x000D_
<span class="target" style="display: none">Inline as well.</span>_x000D_
_x000D_
<div class="target" style="display: none">Should revert back to being block level.</div>_x000D_
_x000D_
<span class="target" style="display: none">Should revert back to being inline.</span>
_x000D_
_x000D_
_x000D_

(If you want to take it a step further, you could even mimic what jQuery does and determine the element's default browser styling by appending the element to a blank iframe (without a conflicting stylesheet) and then retrieve the computed styling. In doing so, you will know the true initial display property value of the element and you won't have to hardcode a value in order to get the desired results.)

Toggling the display:

Similarly, if you would like to toggle the display of an element or collection of elements, you could simply iterate over each element and determine whether it is visible by checking the computed value of the display property. If it's visible, set the display to none, otherwise remove the inline display styling, and if it's still hidden, set the display to the specified value or the hardcoded default, block.

function toggle (elements, specifiedDisplay) {
  var element, index;

  elements = elements.length ? elements : [elements];
  for (index = 0; index < elements.length; index++) {
    element = elements[index];

    if (isElementHidden(element)) {
      element.style.display = '';

      // If the element is still hidden after removing the inline display
      if (isElementHidden(element)) {
        element.style.display = specifiedDisplay || 'block';
      }
    } else {
      element.style.display = 'none';
    }
  }
  function isElementHidden (element) {
    return window.getComputedStyle(element, null).getPropertyValue('display') === 'none';
  }
}
// Usage:
document.getElementById('toggle-button').addEventListener('click', function () {
  toggle(document.querySelectorAll('.target'));
});

_x000D_
_x000D_
document.getElementById('toggle-button').addEventListener('click', function () {_x000D_
    toggle(document.querySelectorAll('.target'));_x000D_
});_x000D_
_x000D_
function toggle (elements, specifiedDisplay) {_x000D_
  var element, index;_x000D_
_x000D_
  elements = elements.length ? elements : [elements];_x000D_
  for (index = 0; index < elements.length; index++) {_x000D_
    element = elements[index];_x000D_
_x000D_
    if (isElementHidden(element)) {_x000D_
      element.style.display = '';_x000D_
_x000D_
      // If the element is still hidden after removing the inline display_x000D_
      if (isElementHidden(element)) {_x000D_
        element.style.display = specifiedDisplay || 'block';_x000D_
      }_x000D_
    } else {_x000D_
      element.style.display = 'none';_x000D_
    }_x000D_
  }_x000D_
  function isElementHidden (element) {_x000D_
    return window.getComputedStyle(element, null).getPropertyValue('display') === 'none';_x000D_
  }_x000D_
}
_x000D_
.target { display: none; }
_x000D_
<button id="toggle-button">Toggle display</button>_x000D_
_x000D_
<span class="target">Toggle the span.</span>_x000D_
_x000D_
<div class="target">Toggle the div.</div>
_x000D_
_x000D_
_x000D_

What is the use of GO in SQL Server Management Studio & Transact SQL?

The GO command isn't a Transact-SQL statement, but a special command recognized by several MS utilities including SQL Server Management Studio code editor.

The GO command is used to group SQL commands into batches which are sent to the server together. The commands included in the batch, that is, the set of commands since the last GO command or the start of the session, must be logically consistent. For example, you can't define a variable in one batch and then use it in another since the scope of the variable is limited to the batch in which it's defined.

For more information, see http://msdn.microsoft.com/en-us/library/ms188037.aspx.

How to create multiple page app using react

(Make sure to install react-router using npm!)

To use react-router, you do the following:

  1. Create a file with routes defined using Route, IndexRoute components

  2. Inject the Router (with 'r'!) component as the top-level component for your app, passing the routes defined in the routes file and a type of history (hashHistory, browserHistory)

  3. Add {this.props.children} to make sure new pages will be rendered there
  4. Use the Link component to change pages

Step 1 routes.js

import React from 'react';
import { Route, IndexRoute } from 'react-router';

/**
 * Import all page components here
 */
import App from './components/App';
import MainPage from './components/MainPage';
import SomePage from './components/SomePage';
import SomeOtherPage from './components/SomeOtherPage';

/**
 * All routes go here.
 * Don't forget to import the components above after adding new route.
 */
export default (
  <Route path="/" component={App}>
    <IndexRoute component={MainPage} />
    <Route path="/some/where" component={SomePage} />
    <Route path="/some/otherpage" component={SomeOtherPage} />
  </Route>
);

Step 2 entry point (where you do your DOM injection)

// You can choose your kind of history here (e.g. browserHistory)
import { Router, hashHistory as history } from 'react-router';
// Your routes.js file
import routes from './routes';

ReactDOM.render(
  <Router routes={routes} history={history} />,
  document.getElementById('your-app')
);

Step 3 The App component (props.children)

In the render for your App component, add {this.props.children}:

render() {
  return (
    <div>
      <header>
        This is my website!
      </header>

      <main>
        {this.props.children}
      </main>

      <footer>
        Your copyright message
      </footer>
    </div>
  );
}

Step 4 Use Link for navigation

Anywhere in your component render function's return JSX value, use the Link component:

import { Link } from 'react-router';
(...)
<Link to="/some/where">Click me</Link>

How to use JavaScript source maps (.map files)?

The .map files are for js and css (and now ts too) files that have been minified. They are called SourceMaps. When you minify a file, like the angular.js file, it takes thousands of lines of pretty code and turns it into only a few lines of ugly code. Hopefully, when you are shipping your code to production, you are using the minified code instead of the full, unminified version. When your app is in production, and has an error, the sourcemap will help take your ugly file, and will allow you to see the original version of the code. If you didn't have the sourcemap, then any error would seem cryptic at best.

Same for CSS files. Once you take a SASS or LESS file and compile it to CSS, it looks nothing like its original form. If you enable sourcemaps, then you can see the original state of the file, instead of the modified state.

So, to answer you questions in order:

  • What is it for? To de-reference uglified code
  • How can a developer use it? You use it for debugging a production app. In development mode you can use the full version of Angular. In production, you would use the minified version.
  • Should I care about creating a js.map file? If you care about being able to debug production code easier, then yes, you should do it.
  • How does it get created? It is created at build time. There are build tools that can build your .map file for you as it does other files. https://github.com/gruntjs/grunt-contrib-uglify/issues/71

I hope this makes sense.

Trying to check if username already exists in MySQL database using PHP

$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$email = $_POST["email"];
$pass = $_POST["password"];

$check_email = mysqli_query($conn, "SELECT Email FROM crud where Email = '$email' ");
if(mysqli_num_rows($check_email) > 0){
    echo('Email Already exists');
}
else{
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $result = mysqli_query($conn, "INSERT INTO crud (Firstname, Lastname, Email, Password) VALUES ('$firstname', '$lastname', '$email', '$pass')");
}
    echo('Record Entered Successfully');
}

Getting a machine's external IP address with Python

I prefer this Amazon AWS endpoint:

import requests
ip = requests.get('https://checkip.amazonaws.com').text.strip()

how to append a css class to an element by javascript?

classList is a convenient alternative to accessing an element's list of classes.. see http://developer.mozilla.org/en-US/docs/Web/API/Element.classList.

Not supported in IE < 10

JavaScript - cannot set property of undefined

The object stored at d[a] has not been set to anything. Thus, d[a] evaluates to undefined. You can't assign a property to undefined :). You need to assign an object or array to d[a]:

d[a] = [];
d[a]["greeting"] = b;

console.debug(d);

JDK on OSX 10.7 Lion

You can download jdk6 here http://support.apple.com/kb/DL1573

Wish it helps

How can I change Mac OS's default Java VM returned from /usr/libexec/java_home

I think JAVA_HOME is the best you can do. The command-line tools like java and javac will respect that environment variable, you can use /usr/libexec/java_home -v '1.7*' to give you a suitable value to put into JAVA_HOME in order to make command line tools use Java 7.

export JAVA_HOME="`/usr/libexec/java_home -v '1.7*'`"

But standard double-clickable application bundles don't use JDKs installed under /Library/Java at all. Old-style .app bundles using Apple's JavaApplicationStub will use Apple Java 6 from /System/Library/Frameworks, and new-style ones built with AppBundler without a bundled JRE will use the "public" JRE in /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home - that's hard-coded in the stub code and can't be changed, and you can't have two different public JREs installed at the same time.


Edit: I've had a look at VisualVM specifically, assuming you're using the "application bundle" version from the download page, and this particular app is not an AppBundler application, instead its main executable is a shell script that calls a number of other shell scripts and reads various configuration files. It defaults to picking the newest JDK from /Library/Java as long as that is 7u10 or later, or uses Java 6 if your Java 7 installation is update 9 or earlier. But unravelling the logic in the shell scripts it looks to me like you can specify a particular JDK using a configuration file.

Create a text file ~/Library/Application Support/VisualVM/1.3.6/etc/visualvm.conf (replace 1.3.6 with whatever version of VisualVM you're using) containing the line

visualvm_jdkhome="`/usr/libexec/java_home -v '1.7*'`"

and this will force it to choose Java 7 instead of 8.

Want to move a particular div to right

For me, I used margin-left: auto; which is more responsive with horizontal resizing.

Get a list of resources from classpath directory

With Spring it's easy. Be it a file, or folder, or even multiple files, there are chances, you can do it via injection.

This example demonstrates the injection of multiple files located in x/y/z folder.

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

@Service
public class StackoverflowService {
    @Value("classpath:x/y/z/*")
    private Resource[] resources;

    public List<String> getResourceNames() {
        return Arrays.stream(resources)
                .map(Resource::getFilename)
                .collect(Collectors.toList());
    }
}

It does work for resources in the filesystem as well as in JARs.

What is the difference between XML and XSD?

XML versus XSD

XML defines the syntax of elements and attributes for structuring data in a well-formed document.

XSD (aka XML Schema), like DTD before, powers the eXtensibility in XML by enabling the user to define the vocabulary and grammar of the elements and attributes in a valid XML document.

How to parse a string in JavaScript?

Use split on string:

var array = coolVar.split(/-/);

disable horizontal scroll on mobile web

Try this code,overflow will help to remove scrollbar.You can use it also for any div which is scrolling.

html, body {
   overflow-x: hidden;
 }
body {
   width:100%;
 }

Does Ruby have a string.startswith("abc") built in method?

Your question title and your question body are different. Ruby does not have a starts_with? method. Rails, which is a Ruby framework, however, does, as sepp2k states. See his comment on his answer for the link to the documentation for it.

You could always use a regular expression though:

if SomeString.match(/^abc/) 
   # SomeString starts with abc

^ means "start of string" in regular expressions

git push rejected: error: failed to push some refs

'remote: error: denying non-fast-forward refs/heads/master (you should pull first)'

That message suggests that there is a hook on the server that is rejecting fast forward pushes. Yes, it is usually not recommended and is a good guard, but since you are the only person using it and you want to do the force push, contact the administrator of the repo to allow to do the non-fastforward push by temporarily removing the hook or giving you the permission in the hook to do so.

Is there a method to generate a UUID with go language

The go-uuid library is NOT RFC4122 compliant. The variant bits are not set correctly. There have been several attempts by community members to have this fixed but pull requests for the fix are not being accepted.

You can generate UUIDs using the Go uuid library I rewrote based on the go-uuid library. There are several fixes and improvements. This can be installed with:

go get github.com/twinj/uuid

You can generate random (version 4) UUIDs with:

import "github.com/twinj/uuid"

u := uuid.NewV4()

The returned UUID type is an interface and the underlying type is an array.

The library also generates v1 UUIDs and correctly generates v3 and 5 UUIDs. There are several new methods to help with printing and formatting and also new general methods to create UUIDs based off of existing data.

Remove Item from ArrayList

 public void DeleteUserIMP(UserIMP useriamp) {
       synchronized (ListUserIMP) {
            if (ListUserIMP.isEmpty()) {
            System.out.println("user is empty");
        }  else {
            Iterator<UserIMP> it = ListUserIMP.iterator();
            while (it.hasNext()) {
                UserIMP user = it.next();
                if (useriamp.getMoblieNumber().equals(user.getMoblieNumber())) {
                    it.remove();
                    System.out.println("remove it");
                }
            }
            // ListUserIMP.remove(useriamp);

            System.out.println(" this user removed");
        }
        Constants.RESULT_FOR_REGISTRATION = Constants.MESSAGE_OK;
        // System.out.println("This user Deleted " + Constants.MESSAGE_OK);

    }
}

Running a Python script from PHP

In my case I needed to create a new folder in the www directory called scripts. Within scripts I added a new file called test.py.

I then used sudo chown www-data:root scripts and sudo chown www-data:root test.py.

Then I went to the new scripts directory and used sudo chmod +x test.py.

My test.py file it looks like this. Note the different Python version:

#!/usr/bin/env python3.5
print("Hello World!")

From php I now do this:

$message = exec("/var/www/scripts/test.py 2>&1");
print_r($message);

And you should see: Hello World!

How to get html table td cell value by JavaScript?

This is my solution

var cells = Array.prototype.slice.call(document.getElementById("tableI").getElementsByTagName("td"));
for(var i in cells){
    console.log("My contents is \"" + cells[i].innerHTML + "\"");
}

how to implement Interfaces in C++?

C++ has no built-in concepts of interfaces. You can implement it using abstract classes which contains only pure virtual functions. Since it allows multiple inheritance, you can inherit this class to create another class which will then contain this interface (I mean, object interface :) ) in it.

An example would be something like this -

class Interface
{
public:
    Interface(){}
    virtual ~Interface(){}
    virtual void method1() = 0;    // "= 0" part makes this method pure virtual, and
                                   // also makes this class abstract.
    virtual void method2() = 0;
};

class Concrete : public Interface
{
private:
    int myMember;

public:
    Concrete(){}
    ~Concrete(){}
    void method1();
    void method2();
};

// Provide implementation for the first method
void Concrete::method1()
{
    // Your implementation
}

// Provide implementation for the second method
void Concrete::method2()
{
    // Your implementation
}

int main(void)
{
    Interface *f = new Concrete();

    f->method1();
    f->method2();

    delete f;

    return 0;
}

How to check if input is numeric in C++

If you already have the string, you can use this function:

bool isNumber( const string& s )
{
  bool hitDecimal=0;
  for( char c : s )
  {
    if( c=='.' && !hitDecimal ) // 2 '.' in string mean invalid
      hitDecimal=1; // first hit here, we forgive and skip
    else if( !isdigit( c ) ) 
      return 0 ; // not ., not 
  }
  return 1 ;
}

Print the data in ResultSet along with column names

Have a look at the documentation. You made the following mistakes. Firstly, ps.executeQuery() doesn't have any parameters. Instead you passed the SQL query into it.

Secondly, regarding the prepared statement, you have to use the ? symbol if want to pass any parameters. And later bind it using

setXXX(index, value) 

Here xxx stands for the data type.

How to set a parameter in a HttpServletRequest?

As mentioned in the previous posts, using an HttpServletReqiestWrapper is the way to go, however the missed part in those posts was that apart from overriding the method getParameter(), you should also override other parameter related methods to produce a consistent response. e.g. the value of a param added by the custom request wrapper should also be included in the parameters map returned by the method getParameterMap(). Here is an example:

   public class AddableHttpRequest extends HttpServletRequestWrapper {

    /** A map containing additional request params this wrapper adds to the wrapped request */
    private final Map<String, String> params = new HashMap<>();

    /**
     * Constructs a request object wrapping the given request.
     * @throws java.lang.IllegalArgumentException if the request is null
     */
    AddableHttpRequest(final HttpServletRequest request) {
        super(request)
    }

    @Override
    public String getParameter(final String name) {
        // if we added one with the given name, return that one
        if ( params.get( name ) != null ) {
            return params.get( name );
        } else {
            // otherwise return what's in the original request
            return super.getParameter(name);
        }
    }


    /**
     * *** OVERRIDE THE METHODS BELOW TO REFLECT PARAMETERS ADDED BY THIS WRAPPER ****
     */

    @Override
    public Map<String, String> getParameterMap() {
        // defaulf impl, should be overridden for an approprivate map of request params
        return super.getParameterMap();
    }

    @Override
    public Enumeration<String> getParameterNames() {
        // defaulf impl, should be overridden for an approprivate map of request params names
        return super.getParameterNames();
    }

    @Override
    public String[] getParameterValues(final String name) {
        // defaulf impl, should be overridden for an approprivate map of request params values
        return super.getParameterValues(name);
    }
}

pip install returning invalid syntax

The OS is not recognizing 'python' command. So try 'py'

Use 'py -m pip'

Get the first item from an iterable that matches a condition

The itertools module contains a filter function for iterators. The first element of the filtered iterator can be obtained by calling next() on it:

from itertools import ifilter

print ifilter((lambda i: i > 3), range(10)).next()

Best way to represent a Grid or Table in AngularJS with Bootstrap 3?

For anyone reading this post: Do yourself a favor and stay away of ng-grid. Is full of bugs (really..almost every part of the lib is broken somehow), the devs has abandoned the support of 2.0.x branch in order to work in 3.0 which is very far of being ready. Fixing the problems by yourself is not an easy task, ng-grid code is not small and is not simple, unless you have a lot of time and a deep knowledge of angular and js in general, its going to be a hard task.

Bottom Line: is full of bugs, and the last stable version has been abandoned.

The github is full of PRs, but they are being ignored. And if you report a bug in the 2.x branch, it's get closed.

I know is an open source proyect and the complains may sound a little bit out of place, but from the perspective of a developer looking for a library, that's my opinion. I spent many hours working with ng-grid in a large proyect and the headcaches are never ending

Hashcode and Equals for Hashset

according jdk source code from javasourcecode.org, HashSet use HashMap as its inside implementation, the code about put method of HashSet is below :

public V put(K key, V value) {
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key.hashCode());
        int i = indexFor(hash, table.length);
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }

        modCount++;
        addEntry(hash, key, value, i);
        return null;
    }

The rule is firstly check the hash, then check the reference and then call equals method of the object will be putted in.

Accessing bash command line args $@ vs $*

This example let may highlight the differ between "at" and "asterix" while we using them. I declared two arrays "fruits" and "vegetables"

fruits=(apple pear plumm peach melon)            
vegetables=(carrot tomato cucumber potatoe onion)

printf "Fruits:\t%s\n" "${fruits[*]}"            
printf "Fruits:\t%s\n" "${fruits[@]}"            
echo + --------------------------------------------- +      
printf "Vegetables:\t%s\n" "${vegetables[*]}"    
printf "Vegetables:\t%s\n" "${vegetables[@]}"    

See the following result the code above:

Fruits: apple pear plumm peach melon
Fruits: apple
Fruits: pear
Fruits: plumm
Fruits: peach
Fruits: melon
+ --------------------------------------------- +
Vegetables: carrot tomato cucumber potatoe onion
Vegetables: carrot
Vegetables: tomato
Vegetables: cucumber
Vegetables: potatoe
Vegetables: onion

PHP Fatal error: Class 'PDO' not found

you can just find-out loaded config file by executing below command,

 php -i | grep 'php.ini'

Then add below lines to correct php.ini file

extension=pdo.so
extension=pdo_sqlite.so
extension=pdo_mysql.so
extension=sqlite.so

Then restart web server,

service httpd restart

#define in Java

Java doesn't have a general purpose define preprocessor directive.

In the case of constants, it is recommended to declare them as static finals, like in

private static final int PROTEINS = 100;

Such declarations would be inlined by the compilers (if the value is a compile-time constant).

Please note also that public static final constant fields are part of the public interface and their values shouldn't change (as the compiler inlines them). If you do change the value, you would need to recompile all the sources that referenced that constant field.

How to convert a String into an ArrayList?

If you want to convert a string into a ArrayList try this:

public ArrayList<Character> convertStringToArraylist(String str) {
    ArrayList<Character> charList = new ArrayList<Character>();      
    for(int i = 0; i<str.length();i++){
        charList.add(str.charAt(i));
    }
    return charList;
}

But i see a string array in your example, so if you wanted to convert a string array into ArrayList use this:

public static ArrayList<String> convertStringArrayToArraylist(String[] strArr){
    ArrayList<String> stringList = new ArrayList<String>();
    for (String s : strArr) {
        stringList.add(s);
    }
    return stringList;
}

Curl setting Content-Type incorrectly

I think you want to specify

-H "Content-Type:text/xml"

with a colon, not an equals.

jQuery vs document.querySelectorAll

To understand why jQuery is so popular, it's important to understand where we're coming from!

About a decade ago, top browsers were IE6, Netscape 8 and Firefox 1.5. Back in those days, there were little cross-browser ways to select an element from the DOM besides Document.getElementById().

So, when jQuery was released back in 2006, it was pretty revolutionary. Back then, jQuery set the standard for how to easily select / change HTML elements and trigger events, because its flexibility and browser support were unprecedented.

Now, more than a decade later, a lot of features that made jQuery so popular have become included in the javaScript standard:

These weren't generally available back in 2005. The fact that they are today obviously begs the question of why we should use jQuery at all. And indeed, people are increasingly wondering whether we should use jQuery at all.

So, if you think you understand JavaScript well enough to do without jQuery, please do! Don't feel forced to use jQuery, just because so many others are doing it!

Can't concatenate 2 arrays in PHP

+ is called the Union operator, which differs from a Concatenation operator (PHP doesn't have one for arrays). The description clearly says:

The + operator appends elements of remaining keys from the right handed array to the left handed, whereas duplicated keys are NOT overwritten.

With the example:

$a = array("a" => "apple", "b" => "banana");
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");
$c = $a + $b;

array(3) {
  ["a"]=>
  string(5) "apple"
  ["b"]=>
  string(6) "banana"
  ["c"]=>
  string(6) "cherry"
}

Since both your arrays have one entry with the key 0, the result is expected.

To concatenate, use array_merge.

Difference between window.location.href=window.location.href and window.location.reload()

If you add the boolean true to the reload window.location.reload(true) it will load from server.

It is not clear how supported this boolean is, W3Org mentions that NS used to support it

There MIGHT be a difference between the content of window.location.href and document.URL - there at least used to be a difference between location.href and the non-standard and deprecated document.location that had to do with redirection, but that is really last millennium.

For documentation purposes I would use window.location.reload() because that is what you want to do.

Submit form and stay on same page?

Use XMLHttpRequest

var xhr = new XMLHttpRequest();
xhr.open("POST", '/server', true);

//Send the proper header information along with the request
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

xhr.onreadystatechange = function() { // Call a function when the state changes.
    if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
        // Request finished. Do processing here.
    }
}
xhr.send("foo=bar&lorem=ipsum");
// xhr.send(new Int8Array()); 
// xhr.send(document);

Git: Create a branch from unstaged/uncommitted changes on master

If you are using the GitHub Windows client (as I am) and you are in the situation of having made uncommitted changes that you wish to move to a new branch, you can simply "Crate a new branch" via the GitHub client. It will switch to the newly created branch and preserve your changes.

enter image description here

A warning - comparison between signed and unsigned integer expressions

The important difference between signed and unsigned ints is the interpretation of the last bit. The last bit in signed types represent the sign of the number, meaning: e.g:

0001 is 1 signed and unsigned 1001 is -1 signed and 9 unsigned

(I avoided the whole complement issue for clarity of explanation! This is not exactly how ints are represented in memory!)

You can imagine that it makes a difference to know if you compare with -1 or with +9. In many cases, programmers are just too lazy to declare counting ints as unsigned (bloating the for loop head f.i.) It is usually not an issue because with ints you have to count to 2^31 until your sign bit bites you. That's why it is only a warning. Because we are too lazy to write 'unsigned' instead of 'int'.

How to find the size of a table in SQL?

SQL Server provides a built-in stored procedure that you can run to easily show the size of a table, including the size of the indexes… which might surprise you.

Syntax:

 sp_spaceused 'Tablename'

see in :

http://www.howtogeek.com/howto/database/determine-size-of-a-table-in-sql-server/

Facebook Access Token for Pages

The documentation for this is good if not a little difficult to find.

Facebook Graph API - Page Tokens

After initializing node's fbgraph, you can run:

var facebookAccountID = yourAccountIdHere 

graph
.setOptions(options)
.get(facebookAccountId + "/accounts", function(err, res) {
  console.log(res); 
});

and receive a JSON response with the token you want to grab, located at:

res.data[0].access_token

How to debug ORA-01775: looping chain of synonyms?

I had a function defined in the wrong schema and without a public synonym. I.e. my proc was in schema "Dogs" and the function was in schema "Cats". The function didn't have a public synonym on it to allow Dogs to access the cats' function.

Object creation on the stack/heap?

A)

Object* o;
o = new Object();

`` B)

Object* o = new Object();

I think A and B has no difference. In both the cases o is a pointer to class Object. statement new Object() creates an object of class Object from heap memory. Assignment statement assigns the address of allocated memory to pointer o.

One thing I would like to mention that size of allocated memory from heap is always the sizeof(Object) not sizeof(Object) + sizeof(void *).

How can I combine hashes in Perl?

Quick Answer (TL;DR)


    %hash1 = (%hash1, %hash2)

    ## or else ...

    @hash1{keys %hash2} = values %hash2;

    ## or with references ...

    $hash_ref1 = { %$hash_ref1, %$hash_ref2 };

Overview

  • Context: Perl 5.x
  • Problem: The user wishes to merge two hashes1 into a single variable

Solution

  • use the syntax above for simple variables
  • use Hash::Merge for complex nested variables

Pitfalls

See also


Footnotes

1 * (aka associative-array, aka dictionary)

What does -save-dev mean in npm install grunt --save-dev

There are (at least) two types of package dependencies you can indicate in your package.json files:

  1. Those packages that are required in order to use your module are listed under the "dependencies" property. Using npm you can add those dependencies to your package.json file this way:

    npm install --save packageName
    
  2. Those packages required in order to help develop your module are listed under the "devDependencies" property. These packages are not necessary for others to use the module, but if they want to help develop the module, these packages will be needed. Using npm you can add those devDependencies to your package.json file this way:

    npm install --save-dev packageName
    

How to scanf only integer?

Use fgets and strtol,

A pointer to the first character following the integer representation in s is stored in the object pointed by p, if *p is different to \n then you have a bad input.

#include <stdio.h>
#include <stdlib.h>

int main(void) 
{
    char *p, s[100];
    long n;

    while (fgets(s, sizeof(s), stdin)) {
        n = strtol(s, &p, 10);
        if (p == s || *p != '\n') {
            printf("Please enter an integer: ");
        } else break;
    }
    printf("You entered: %ld\n", n);
    return 0;
}

Convert a String to Modified Camel Case in Java or Title Case as is otherwise called

You can easily write the method to do that :

  public static String toCamelCase(final String init) {
    if (init == null)
        return null;

    final StringBuilder ret = new StringBuilder(init.length());

    for (final String word : init.split(" ")) {
        if (!word.isEmpty()) {
            ret.append(Character.toUpperCase(word.charAt(0)));
            ret.append(word.substring(1).toLowerCase());
        }
        if (!(ret.length() == init.length()))
            ret.append(" ");
    }

    return ret.toString();
}

Jquery Ajax Call, doesn't call Success or Error

change your code to:

function ChangePurpose(Vid, PurId) {
    var Success = false;
    $.ajax({
        type: "POST",
        url: "CHService.asmx/SavePurpose",
        dataType: "text",
        async: false,
        data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            Success = true;
        },
        error: function (textStatus, errorThrown) {
            Success = false;
        }
    });
    //done after here
    return Success;
} 

You can only return the values from a synchronous function. Otherwise you will have to make a callback.

So I just added async:false, to your ajax call

Update:

jquery ajax calls are asynchronous by default. So success & error functions will be called when the ajax load is complete. But your return statement will be executed just after the ajax call is started.

A better approach will be:

     // callbackfn is the pointer to any function that needs to be called
     function ChangePurpose(Vid, PurId, callbackfn) {
        var Success = false;
        $.ajax({
            type: "POST",
            url: "CHService.asmx/SavePurpose",
            dataType: "text",
            data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                callbackfn(data)
            },
            error: function (textStatus, errorThrown) {
                callbackfn("Error getting the data")
            }
        });
     } 

     function Callback(data)
     {
        alert(data);
     }

and call the ajax as:

 // Callback is the callback-function that needs to be called when asynchronous call is complete
 ChangePurpose(Vid, PurId, Callback);

Trim whitespace from a String

I think that substr() throws an exception if str only contains the whitespace.

I would modify it to the following code:

string trim(string& str)
{
    size_t first = str.find_first_not_of(' ');
    if (first == std::string::npos)
        return "";
    size_t last = str.find_last_not_of(' ');
    return str.substr(first, (last-first+1));
}

Error: Selection does not contain a main type

When you save your file, make sure it has the extension .java. If it does not, Eclipse won't know to read it as a java file.

How do I expire a PHP session after 30 minutes?

if (isSet($_SESSION['started'])){
    if((mktime() - $_SESSION['started'] - 60*30) > 0){
        //Logout, destroy session, etc.
    }
}
else {
    $_SESSION['started'] = mktime();
}

What is the difference between Sublime text and Github's Atom

Atom has been created by Github and it includes "git awareness". That is a feature I like quite a lot:

enter image description here

Also it highlights the files in the git tree that have changed with different colours depending on their commit status:

enter image description here

Finding Android SDK on Mac and adding to PATH

If Android Studio shows you the path /Users/<name>/Library/Android/sdk but you can not find it in your folder, just right-click and select "Show View Option". There you will be able to select "Show Library Folder"; select it and you can access the SDK.

SonarQube Exclude a directory

If you're an Azure DevOps user looking for both where and how to exclude files and folders, here ya go:

  1. Edit your pipeline
  2. Make sure you have the "Prepare analysis on SonarQube" task added. You'll need to look elsewhere if you need help configuring this. Suggestion: Use the UI pipeline editor vs the yaml editor if you are missing the manage link. At present, there is no way to convert to UI from yaml. Just recreate the pipeline. If using git, you can delete the yaml from the root of your repo.
  3. Under the 'Advanced' section of the "Prepare analysis on SonarQube" task, you can add exclusions. See advice given by others for specific exclusion formats.

Example:

# Additional properties that will be passed to the scanner, 
# Put one key=value per line, example:
# sonar.exclusions=**/*.bin
sonar.exclusions=MyProjectName/MyWebContentFolder/**

Note: If you're not sure on the path, you can go into sonarqube, view your project, look at all or new 'Code Smells' and the path you need is listed above each grouping of issues. You can grab the full path to a file or use wilds like these examples:

  • MyProjectName/MyCodeFile.cs
  • MyProjectName/**

If you don't have the 'Run Code Analysis' task added, do that and place it somewhere after the 'Build solution **/*.sln' task.

Save and Queue and then check out your sonarqube server to see if the exclusions worked.

cannot make a static reference to the non-static field

You are trying to access non static field directly from static method which is not legal in java. balance is a non static field, so either access it using object reference or make it static.

Initialise numpy array of unknown length

a = np.empty(0)
for x in y:
    a = np.append(a, x)

Why do we use Base64?

Why/ How do we use Base64 encoding?

Base64 is one of the binary-to-text encoding scheme having 75% efficiency. It is used so that typical binary data (such as images) may be safely sent over legacy "not 8-bit clean" channels. In earlier email networks (till early 1990s), most email messages were plain text in the 7-bit US-ASCII character set. So many early comm protocol standards were designed to work over "7-bit" comm links "not 8-bit clean". Scheme efficiency is the ratio between number of bits in the input and the number of bits in the encoded output. Hexadecimal (Base16) is also one of the binary-to-text encoding scheme with 50% efficiency.

Base64 Encoding Steps (Simplified):

  1. Binary data is arranged in continuous chunks of 24 bits (3 bytes) each.
  2. Each 24 bits chunk is grouped in to four parts of 6 bit each.
  3. Each 6 bit group is converted into their corresponding Base64 character values, i.e. Base64 encoding converts three octets into four encoded characters. The ratio of output bytes to input bytes is 4:3 (33% overhead).
  4. Interestingly, the same characters will be encoded differently depending on their position within the three-octet group which is encoded to produce the four characters.
  5. The receiver will have to reverse this process to recover the original message.

Conditional Binding: if let error – Initializer for conditional binding must have Optional type

What it is telling you is - the 2nd guard let or the if let check is not happening on an Optional Int or Optional String. You already have a non-optional value, so guarding or if-letting is not needed anymore

Can constructors throw exceptions in Java?

Yes, it can throw an exception and you can declare that in the signature of the constructor too as shown in the example below:

public class ConstructorTest
{
    public ConstructorTest() throws InterruptedException
    {
        System.out.println("Preparing object....");
        Thread.sleep(1000);
        System.out.println("Object ready");
    }

    public static void main(String ... args)
    {
        try
        {
            ConstructorTest test = new ConstructorTest();
        }
        catch (InterruptedException e)
        {
            System.out.println("Got interrupted...");
        }
    }
}

WordPress is giving me 404 page not found for all pages except the homepage

I just changed the permalink to 'month and day'of all the posts by ging to setting>permalink.

Now all posts are open and working fine.

Again, I renamed to all posts to its actual permalink. Its again working fine.

This method worked for me :-)

What is let-* in Angular 2 templates?

update Angular 5

ngOutletContext was renamed to ngTemplateOutletContext

See also https://github.com/angular/angular/blob/master/CHANGELOG.md#500-beta5-2017-08-29

original

Templates (<template>, or <ng-template> since 4.x) are added as embedded views and get passed a context.

With let-col the context property $implicit is made available as col within the template for bindings. With let-foo="bar" the context property bar is made available as foo.

For example if you add a template

<ng-template #myTemplate let-col let-foo="bar">
  <div>{{col}}</div>
  <div>{{foo}}</div>
</ng-template>

<!-- render above template with a custom context -->
<ng-template [ngTemplateOutlet]="myTemplate"
             [ngTemplateOutletContext]="{
                                           $implicit: 'some col value',
                                           bar: 'some bar value'
                                        }"
></ng-template>

See also this answer and ViewContainerRef#createEmbeddedView.

*ngFor also works this way. The canonical syntax makes this more obvious

<ng-template ngFor let-item [ngForOf]="items" let-i="index" let-odd="odd">
  <div>{{item}}</div>
</ng-template>

where NgFor adds the template as embedded view to the DOM for each item of items and adds a few values (item, index, odd) to the context.

See also Using $implict to pass multiple parameters

PDO::__construct(): Server sent charset (255) unknown to the client. Please, report to the developers

I had the same issue to connect to local system.

I checked in the services list (Run->Services.msc->Enter) wampmysqld64 was stopped.

Restarted it. and was able to login.

How do I run .sh or .bat files from Terminal?

Type in

chmod 755 scriptname.sh

In other words, give yourself permission to run the file. I'm guessing you only have r/w permission on it.

Pull new updates from original GitHub repository into forked GitHub repository

Use:

git remote add upstream ORIGINAL_REPOSITORY_URL

This will set your upstream to the repository you forked from. Then do this:

git fetch upstream      

This will fetch all the branches including master from the original repository.

Merge this data in your local master branch:

git merge upstream/master

Push the changes to your forked repository i.e. to origin:

git push origin master

Voila! You are done with the syncing the original repository.

How to make a DIV always float on the screen in top right corner?

Use position:fixed, as previously stated, IE6 doesn't recognize position:fixed, but with some css magic you can get IE6 to behave:

html, body {
    height: 100%;
    overflow:auto;
}
body #fixedElement {
    position:fixed !important;
    position: absolute; /*ie6 */
    bottom: 0;
}

The !important flag makes it so you don't have to use a conditional comment for IE. This will have #fixedElement use position:fixed in all browsers but IE, and in IE, position:absolute will take effect with bottom:0. This will simulate position:fixed for IE6

Vue component event after render

updated() should be what you're looking for:

Called after a data change causes the virtual DOM to be re-rendered and patched.

The component’s DOM will have been updated when this hook is called, so you can perform DOM-dependent operations here.

How to create a inner border for a box in html?

Please have a look

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    <style>
    .box{ width:500px; height:200px; background:#000; border:2px solid #ccc;}
        .inner-border {
            border: 20px solid black;
            box-shadow: inset 0px 0px 0px 10px red;
            box-sizing: border-box; /* Include padding and border in element's width and height */
        }
        /* CSS3 solution only for rectangular shape */
        .inner-outline {
            outline: 10px solid red;
            outline-offset: -30px;
        }
    </style>
    </head>

    <body>
    <div class="box inner-border inner-outline"></div>
    </body>
    </html>

How to Apply global font to whole HTML document

Set it in the body selector of your css. E.g.

body {
    font: 16px Arial, sans-serif;
}

script to map network drive

Does this not work (assuming "ROUTERNAME" is the user name the router expects)?

net use Z: "\\10.0.1.1\DRIVENAME" /user:"ROUTERNAME" "PW"

Alternatively, you can use use a small VBScript:

Option Explicit
Dim u, p, s, l
Dim Network: Set Network= CreateObject("WScript.Network")

l = "Z:"
s = "\\10.0.1.1\DRIVENAME"

u = "ROUTERNAME"
p = "PW"

Network.MapNetworkDrive l, s, False, u, p

How do I UPDATE from a SELECT in SQL Server?

Here is another useful syntax:

UPDATE suppliers
SET supplier_name = (SELECT customers.name
                     FROM customers
                     WHERE customers.customer_id = suppliers.supplier_id)
WHERE EXISTS (SELECT customers.name
              FROM customers
              WHERE customers.customer_id = suppliers.supplier_id);

It checks if it is null or not by using "WHERE EXIST".

Write code to convert given number into words (eg 1234 as input should output one thousand two hundred and thirty four)

#include<iostream>
using namespace std;
void expand(int);
int main()
{
    int num;
    cout<<"Enter a number : ";
    cin>>num;
    expand(num);
}
void expand(int value)
{
    const char * const ones[20] = {"zero", "one", "two", "three","four","five","six","seven",
    "eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen",
    "eighteen","nineteen"};
    const char * const tens[10] = {"", "ten", "twenty", "thirty","forty","fifty","sixty","seventy",
    "eighty","ninety"};

    if(value<0)
    {
        cout<<"minus ";
        expand(-value);
    }
    else if(value>=1000)
    {
        expand(value/1000);
        cout<<" thousand";
        if(value % 1000)
        {
            if(value % 1000 < 100)
            {
                cout << " and";
            }
            cout << " " ;
            expand(value % 1000);
        }
    }
    else if(value >= 100)
    {
        expand(value / 100);
        cout<<" hundred";
        if(value % 100)
        {
            cout << " and ";
            expand (value % 100);
        }
    }
    else if(value >= 20)
    {
        cout << tens[value / 10];
        if(value % 10)
        {
            cout << " ";
            expand(value % 10);
        }
    }
    else
    {
        cout<<ones[value];
    }
    return;
}

How do you performance test JavaScript code?

I think JavaScript performance (time) testing is quite enough. I found a very handy article about JavaScript performance testing here.

How to check not in array element

I prefer this

if(in_array($id,$user_access_arr) == false)

respective

if (in_array(search_value, array) == false) 
// value is not in array 

How to declare a global variable in React?

Why don't you try using Context?

You can declare a global context variable in any of the parent components and this variable will be accessible across the component tree by this.context.varname. You only have to specify childContextTypes and getChildContext in the parent component and thereafter you can use/modify this from any component by just specifying contextTypes in the child component.

However, please take a note of this as mentioned in docs:

Just as global variables are best avoided when writing clear code, you should avoid using context in most cases. In particular, think twice before using it to "save typing" and using it instead of passing explicit props.

Removing spaces from string

String res =" Application " res=res.trim();

o/p: Application

Note: White space ,blank space are trim or removed

Generate Java class from JSON?

Try http://www.jsonschema2pojo.org

Or the jsonschema2pojo plug-in for Maven:

        <plugin>
            <groupId>org.jsonschema2pojo</groupId>
            <artifactId>jsonschema2pojo-maven-plugin</artifactId>
            <version>1.0.2</version>
            <configuration>
                <sourceDirectory>${basedir}/src/main/resources/schemas</sourceDirectory>
                <targetPackage>com.myproject.jsonschemas</targetPackage>
                <sourceType>json</sourceType>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>generate</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

The <sourceType>json</sourceType> covers the case where the sources are json (like the OP). If you have actual json schemas, remove this line.

Updated in 2014: Two things have happened since Dec '09 when this question was asked:

  • The JSON Schema spec has moved on a lot. It's still in draft (not finalised) but it's close to completion and is now a viable tool specifying your structural rules

  • I've recently started a new open source project specifically intended to solve your problem: jsonschema2pojo. The jsonschema2pojo tool takes a json schema document and generates DTO-style Java classes (in the form of .java source files). The project is not yet mature but already provides coverage of the most useful parts of json schema. I'm looking for more feedback from users to help drive the development. Right now you can use the tool from the command line or as a Maven plugin.

Hope this helps!

How to redirect output of systemd service to a file

I think there's a more elegant way to solve the problem: send the stdout/stderr to syslog with an identifier and instruct your syslog manager to split its output by program name.

Use the following properties in your systemd service unit file:

StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=<your program identifier> # without any quote

Then, assuming your distribution is using rsyslog to manage syslogs, create a file in /etc/rsyslog.d/<new_file>.conf with the following content:

if $programname == '<your program identifier>' then /path/to/log/file.log
& stop

Now make the log file writable by syslog:

# ls -alth /var/log/syslog 
-rw-r----- 1 syslog adm 439K Mar  5 19:35 /var/log/syslog
# chown syslog:adm /path/to/log/file.log

Restart rsyslog (sudo systemctl restart rsyslog) and enjoy! Your program stdout/stderr will still be available through journalctl (sudo journalctl -u <your program identifier>) but they will also be available in your file of choice.

Source via archive.org

Difference between CLOCK_REALTIME and CLOCK_MONOTONIC?

Robert Love's book LINUX System Programming 2nd Edition, specifically addresses your question at the beginning of Chapter 11, pg 363:

The important aspect of a monotonic time source is NOT the current value, but the guarantee that the time source is strictly linearly increasing, and thus useful for calculating the difference in time between two samplings

That said, I believe he is assuming the processes are running on the same instance of an OS, so you might want to have a periodic calibration running to be able to estimate drift.

How to import a module given its name as string?

The below piece worked for me:

>>>import imp; 
>>>fp, pathname, description = imp.find_module("/home/test_module"); 
>>>test_module = imp.load_module("test_module", fp, pathname, description);
>>>print test_module.print_hello();

if you want to import in shell-script:

python -c '<above entire code in one line>'

calculating execution time in c++

OVERVIEW

I have written a simple semantic hack for this using @AshutoshMehraresponse. You code looks really readable this way!

MACRO

#include <time.h>

#ifndef SYSOUT_F
#define SYSOUT_F(f, ...)      _RPT1( 0, f, __VA_ARGS__ ) // For Visual studio
#endif

#ifndef speedtest__             
#define speedtest__(data)   for (long blockTime = NULL; (blockTime == NULL ? (blockTime = clock()) != NULL : false); SYSOUT_F(data "%.9fs", (double) (clock() - blockTime) / CLOCKS_PER_SEC))
#endif

USAGE

speedtest__("Block Speed: ")
{
    // The code goes here
}

OUTPUT

Block Speed: 0.127000000s

Need to perform Wildcard (*,?, etc) search on a string using Regex

You can do a simple wildcard mach without RegEx using a Visual Basic function called LikeString.

using Microsoft.VisualBasic;
using Microsoft.VisualBasic.CompilerServices;

if (Operators.LikeString("This is just a test", "*just*", CompareMethod.Text))
{
  Console.WriteLine("This matched!");
}

If you use CompareMethod.Text it will compare case-insensitive. For case-sensitive comparison, you can use CompareMethod.Binary.

More info here: http://www.henrikbrinch.dk/Blog/2012/02/14/Wildcard-matching-in-C

MSDN: http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.compilerservices.operators.likestring%28v=vs.100%29.ASPX

SQLite in Android How to update a specific row

 public void updateRecord(ContactModel contact) {
    database = this.getReadableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COLUMN_FIRST_NAME, contact.getFirstName());
    contentValues.put(COLUMN_LAST_NAME, contact.getLastName());
    contentValues.put(COLUMN_NUMBER,contact.getNumber());
    contentValues.put(COLUMN_BALANCE,contact.getBalance());
    database.update(TABLE_NAME, contentValues, COLUMN_ID + " = ?", new String[]{contact.getID()});
    database.close();
}

What is the difference between T(n) and O(n)?

There's a simple way (a trick, I guess) to remember which notation means what.

All of the Big-O notations can be considered to have a bar.

When looking at a O, the bar is at the bottom, so it is an (asymptotic) lower bound.

When looking at a T, the bar is obviously in the middle. So it is an (asymptotic) tight bound.

When handwriting O, you usually finish at the top, and draw a squiggle. Therefore O(n) is the upper bound of the function. To be fair, this one doesn't work with most fonts, but it is the original justification of the names.

Angular - "has no exported member 'Observable'"

Just remove /Observable from 'rxjs/Observable';

If you then get Cannot find module 'rxjs-compat/Observable' just put below line to thr terminal and press enter.

npm install --save rxjs-compat

How do I parse JSON with Objective-C?

With the perspective of the OS X v10.7 and iOS 5 launches, probably the first thing to recommend now is NSJSONSerialization, Apple's supplied JSON parser. Use third-party options only as a fallback if you find that class unavailable at runtime.

So, for example:

NSData *returnedData = ...JSON data, probably from a web request...

// probably check here that returnedData isn't nil; attempting
// NSJSONSerialization with nil data raises an exception, and who
// knows how your third-party library intends to react?

if(NSClassFromString(@"NSJSONSerialization"))
{
    NSError *error = nil;
    id object = [NSJSONSerialization
                      JSONObjectWithData:returnedData
                      options:0
                      error:&error];

    if(error) { /* JSON was malformed, act appropriately here */ }

    // the originating poster wants to deal with dictionaries;
    // assuming you do too then something like this is the first
    // validation step:
    if([object isKindOfClass:[NSDictionary class]])
    {
        NSDictionary *results = object;
        /* proceed with results as you like; the assignment to
        an explicit NSDictionary * is artificial step to get 
        compile-time checking from here on down (and better autocompletion
        when editing). You could have just made object an NSDictionary *
        in the first place but stylistically you might prefer to keep
        the question of type open until it's confirmed */
    }
    else
    {
        /* there's no guarantee that the outermost object in a JSON
        packet will be a dictionary; if we get here then it wasn't,
        so 'object' shouldn't be treated as an NSDictionary; probably
        you need to report a suitable error condition */
    }
}
else
{
    // the user is using iOS 4; we'll need to use a third-party solution.
    // If you don't intend to support iOS 4 then get rid of this entire
    // conditional and just jump straight to
    // NSError *error = nil;
    // [NSJSONSerialization JSONObjectWithData:...
}

How do I create an executable in Visual Studio 2013 w/ C++?

All executable files from Visual Studio should be located in the debug folder of your project, e.g:

Visual Studio Directory: c:\users\me\documents\visual studio

Then the project which was called 'hello world' would be in the directory:

c:\users\me\documents\visual studio\hello world

And your exe would be located in:

c:\users\me\documents\visual studio\hello world\Debug\hello world.exe

Note the exe being named the same as the project.

Otherwise, you could publish it to a specified folder of your choice which comes with an installation, which would be good if you wanted to distribute it quickly

EDIT:

Everytime you build your project in VS, the exe is updated with the new one according to the code (as long as it builds without errors). When you publish it, you can choose the location, aswell as other factors, and the setup exe will be in that location, aswell as some manifest files and other files about the project.

Git merge reports "Already up-to-date" though there is a difference

A merge is always between the current HEAD and one or more commits (usually, branch head or tag),
and the index file must match the tree of HEAD commit (i.e. the contents of the last commit) when it starts out.
In other words, git diff --cached HEAD must report no changes.

The merged commit is already contained in HEAD. This is the simplest case, called "Already up-to-date."

That should mean the commits in test are already merged in master, but since other commits are done on master, git diff test would still give some differences.

What's the difference between '$(this)' and 'this'?

Yeah, by using $(this), you enabled jQuery functionality for the object. By just using this, it only has generic Javascript functionality.

Cannot attach the file *.mdf as database

In my case removing Initail Cataloge=.... from connection string resolved the issue

JVM option -Xss - What does it do exactly?

If I am not mistaken, this is what tells the JVM how much successive calls it will accept before issuing a StackOverflowError. Not something you wish to change generally.

How to create a foreign key in phpmyadmin

To be able to create a relation, the table Storage Engine must be InnoDB. You can edit in Operations tab. Storage Engine Configuration

Then, you need to be sure that the id column in your main table has been indexed. It should appear at Index section in Structure tab.

Index list

Finally, you could see the option Relations View in Structure tab. When edditing, you will be able to select the parent column in foreign table to create the relation.

enter image description here

See attachments. I hope this could be useful for anyone.

Check if string contains only digits

if you want to include float values also you can use the following code

theValue=$('#balanceinput').val();
var isnum1 = /^\d*\.?\d+$/.test(theValue);
var isnum2 =  /^\d*\.?\d+$/.test(theValue.split("").reverse().join(""));
alert(isnum1+' '+isnum2);

this will test for only digits and digits separated with '.' the first test will cover values such as 0.1 and 0 but also .1 , it will not allow 0. so the solution that I propose is to reverse theValue so .1 will be 1. then the same regular expression will not allow it .

example :

 theValue=3.4; //isnum1=true , isnum2=true 
theValue=.4; //isnum1=true , isnum2=false 
theValue=3.; //isnum1=flase , isnum2=true 

Group list by values

values = set(map(lambda x:x[1], mylist))
newlist = [[y[0] for y in mylist if y[1]==x] for x in values]

what is Ljava.lang.String;@

I also met this problem when I've made ListView for android app:

Map<String, Object> m;

for(int i=0; i < dates.length; i++){
    m = new HashMap<String, Object>();
    m.put(ATTR_DATES, dates[i]);
    m.put(ATTR_SQUATS, squats[i]);
    m.put(ATTR_BP, benchpress[i]);
    m.put(ATTR_ROW, row[i]);
    data.add(m);
}

The problem was that I've forgotten to use the [i] index inside the loop

Oracle database: How to read a BLOB?

What client do you use? .Net, Java, Ruby, SQLPLUS, SQL DEVELOPER? Where did you write that simple select statement?

And why do you want to read the content of the blob, a blob contains binary data so that data is unreadable. You should use a clob instead of a blob if you want to store text instead of binary content.

I suggest that you download SQL DEVELOPER: http://www.oracle.com/technetwork/developer-tools/sql-developer/overview/index.html . With SQL DEVELOPER you can see the content.

Maven project version inheritance - do I have to specify the parent version?

eFox's answer worked for a single project, but not when I was referencing a module from another one (the pom.xml were still stored in my .m2 with the property instead of the version).

However, it works if you combine it with the flatten-maven-plugin, since it generates the poms with the correct version, not the property.

The only option I changed in the plug-in definition is the outputDirectory, it's empty by default, but I prefer to have it in target, which is set in my .gitignore configuration:

<plugin>
   <groupId>org.codehaus.mojo</groupId>
   <artifactId>flatten-maven-plugin</artifactId>
   <version>1.0.1</version>
   <configuration>
      <updatePomFile>true</updatePomFile>
      <outputDirectory>target</outputDirectory>
   </configuration>
   <executions>
      <execution>
         <id>flatten</id>
         <phase>process-resources</phase>
         <goals>
            <goal>flatten</goal>
         </goals>
      </execution>
   </executions>
</plugin>

The plug-in configuration goes in the parent pom.xml

How to select all checkboxes with jQuery?

A more complete example that should work in your case:

_x000D_
_x000D_
$('#select_all').change(function() {_x000D_
  var checkboxes = $(this).closest('form').find(':checkbox');_x000D_
  checkboxes.prop('checked', $(this).is(':checked'));_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<form>_x000D_
  <table>_x000D_
    <tr>_x000D_
      <td><input type="checkbox" id="select_all" /></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td><input type="checkbox" name="select[]" /></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td><input type="checkbox" name="select[]" /></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td><input type="checkbox" name="select[]" /></td>_x000D_
    </tr>_x000D_
  </table>_x000D_
</form>
_x000D_
_x000D_
_x000D_

When the #select_all checkbox is clicked, the status of the checkbox is checked and all the checkboxes in the current form are set to the same status.

Note that you don't need to exclude the #select_all checkbox from the selection as that will have the same status as all the others. If you for some reason do need to exclude the #select_all, you can use this:

_x000D_
_x000D_
$('#select_all').change(function() {_x000D_
  var checkboxes = $(this).closest('form').find(':checkbox').not($(this));_x000D_
  checkboxes.prop('checked', $(this).is(':checked'));_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<form>_x000D_
  <table>_x000D_
    <tr>_x000D_
      <td><input type="checkbox" id="select_all" /></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td><input type="checkbox" name="select[]" /></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td><input type="checkbox" name="select[]" /></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td><input type="checkbox" name="select[]" /></td>_x000D_
    </tr>_x000D_
  </table>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Flask-SQLalchemy update a row's information

Retrieve an object using the tutorial shown in the Flask-SQLAlchemy documentation. Once you have the entity that you want to change, change the entity itself. Then, db.session.commit().

For example:

admin = User.query.filter_by(username='admin').first()
admin.email = '[email protected]'
db.session.commit()

user = User.query.get(5)
user.name = 'New Name'
db.session.commit()

Flask-SQLAlchemy is based on SQLAlchemy, so be sure to check out the SQLAlchemy Docs as well.

Formatting struct timespec

You could use a std::stringstream. You can stream anything into it:

std::stringstream stream;
stream << 5.7;
stream << foo.bar;

std::string s = stream.str();

That should be a quite general approach. (Works only for C++, but you asked the question for this language too.)

Permission is only granted to system app

Have same error from time to time (when I set install location to "prefer external" in manifest). Just clean and rebuild project. Works for me.

How to export a CSV to Excel using Powershell

I am using excelcnv.exe to convert csv into xlsx and that seemed to work properly. You will have to change the directory to where your excelcnv is. If 32 bit, it goes to Program Files (x86)

Start-Process -FilePath 'C:\Program Files\Microsoft Office\root\Office16\excelcnv.exe' -ArgumentList "-nme -oice ""$xlsFilePath"" ""$xlsToxlsxPath"""

Bootstrap Modal sitting behind backdrop

Put this code wherever you want

$('.modal').on('shown.bs.modal', function () {
    var max_index = null;
    $('.modal.fade.in').not($(this)).each(function (index , value){
        if(max_index< parseInt( $(this).css("z-index")))
            max_index = parseInt( $(this).css("z-index"));
    });
    if (max_index != null) $(this).css("z-index", max_index + 1);
});

Python Flask, how to set content type

Use the make_response method to get a response with your data. Then set the mimetype attribute. Finally return this response:

@app.route('/ajax_ddl')
def ajax_ddl():
    xml = 'foo'
    resp = app.make_response(xml)
    resp.mimetype = "text/xml"
    return resp

If you use Response directly, you lose the chance to customize the responses by setting app.response_class. The make_response method uses the app.responses_class to make the response object. In this you can create your own class, add make your application uses it globally:

class MyResponse(app.response_class):
    def __init__(self, *args, **kwargs):
        super(MyResponse, self).__init__(*args, **kwargs)
        self.set_cookie("last-visit", time.ctime())

app.response_class = MyResponse  

Disable arrow key scrolling in users browser

I've tried different ways of blocking scrolling when the arrow keys are pressed, both jQuery and native Javascript - they all work fine in Firefox, but don't work in recent versions of Chrome.
Even the explicit {passive: false} property for window.addEventListener, which is recommended as the only working solution, for example here.

In the end, after many tries, I found a way that works for me in both Firefox and Chrome:

window.addEventListener('keydown', (e) => {
    if (e.target.localName != 'input') {   // if you need to filter <input> elements
        switch (e.keyCode) {
            case 37: // left
            case 39: // right
                e.preventDefault();
                break;
            case 38: // up
            case 40: // down
                e.preventDefault();
                break;
            default:
                break;
        }
    }
}, {
    capture: true,   // this disables arrow key scrolling in modern Chrome
    passive: false   // this is optional, my code works without it
});

Quote for EventTarget.addEventListener() from MDN

options Optional
   An options object specifies characteristics about the event listener. The available options are:

capture
   A Boolean indicating that events of this type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree.
once
   ...
passive
   A Boolean that, if true, indicates that the function specified by listener will never call preventDefault(). If a passive listener does call preventDefault(), the user agent will do nothing other than generate a console warning. ...

How to create an empty array in PHP with predefined size?

PHP provides two types of array.

  • normal array
  • SplFixedArray

normal array : This array is dynamic.

SplFixedArray : this is a standard php library which provides the ability to create array of fix size.

How to unzip files programmatically in Android?

public class MainActivity extends Activity {

private String LOG_TAG = MainActivity.class.getSimpleName();

private File zipFile;
private File destination;

private TextView status;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    status = (TextView) findViewById(R.id.main_status);
    status.setGravity(Gravity.CENTER);

    if ( initialize() ) {
        zipFile = new File(destination, "BlueBoxnew.zip");
        try {
            Unzipper.unzip(zipFile, destination);
            status.setText("Extracted to \n"+destination.getAbsolutePath());
        } catch (ZipException e) {
            Log.e(LOG_TAG, e.getMessage());
        } catch (IOException e) {
            Log.e(LOG_TAG, e.getMessage());
        }
    } else {
        status.setText("Unable to initialize sd card.");
    }
}

public boolean initialize() {
    boolean result = false;
     File sdCard = new File(Environment.getExternalStorageDirectory()+"/zip/");
    //File sdCard = Environment.getExternalStorageDirectory();
    if ( sdCard != null ) {
        destination = sdCard;
        if ( !destination.exists() ) {
            if ( destination.mkdir() ) {
                result = true;
            }
        } else {
            result = true;
        }
    }

    return result;
}

 }

->Helper Class(Unzipper.java)

    import java.io.File;
    import java.io.FileInputStream;
   import java.io.FileOutputStream;
    import java.io.IOException;
       import java.util.zip.ZipEntry;
    import java.util.zip.ZipException;
    import java.util.zip.ZipInputStream;
     import android.util.Log;

   public class Unzipper {

private static String LOG_TAG = Unzipper.class.getSimpleName();

public static void unzip(final File file, final File destination) throws ZipException, IOException {
    new Thread() {
        public void run() {
            long START_TIME = System.currentTimeMillis();
            long FINISH_TIME = 0;
            long ELAPSED_TIME = 0;
            try {
                ZipInputStream zin = new ZipInputStream(new FileInputStream(file));
                String workingDir = destination.getAbsolutePath()+"/";

                byte buffer[] = new byte[4096];
                int bytesRead;
                ZipEntry entry = null;
                while ((entry = zin.getNextEntry()) != null) {
                    if (entry.isDirectory()) {
                        File dir = new File(workingDir, entry.getName());
                        if (!dir.exists()) {
                            dir.mkdir();
                        }
                        Log.i(LOG_TAG, "[DIR] "+entry.getName());
                    } else {
                        FileOutputStream fos = new FileOutputStream(workingDir + entry.getName());
                        while ((bytesRead = zin.read(buffer)) != -1) {
                            fos.write(buffer, 0, bytesRead);
                        }
                        fos.close();
                        Log.i(LOG_TAG, "[FILE] "+entry.getName());
                    }
                }
                zin.close();

                FINISH_TIME = System.currentTimeMillis();
                ELAPSED_TIME = FINISH_TIME - START_TIME;
                Log.i(LOG_TAG, "COMPLETED in "+(ELAPSED_TIME/1000)+" seconds.");
            } catch (Exception e) {
                Log.e(LOG_TAG, "FAILED");
            }
        };
    }.start();
}

   }

->xml layout(activity_main.xml):

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context=".MainActivity" >

<TextView
    android:id="@+id/main_status"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="@string/hello_world" />

</RelativeLayout>

->permission in Menifest file:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

A url resource that is a dot (%2E)

It is not possible. §2.3 says that "." is an unreserved character and that "URIs that differ in the replacement of an unreserved character with its corresponding percent-encoded US-ASCII octet are equivalent". Therefore, /%2E%2E/ is the same as /../, and that will get normalized away.

(This is a combination of an answer by bobince and a comment by slowpoison.)

What's the point of the X-Requested-With header?

Some frameworks are using this header to detect xhr requests e.g. grails spring security is using this header to identify xhr request and give either a json response or html response as response.

Most Ajax libraries (Prototype, JQuery, and Dojo as of v2.1) include an X-Requested-With header that indicates that the request was made by XMLHttpRequest instead of being triggered by clicking a regular hyperlink or form submit button.

Source: http://grails-plugins.github.io/grails-spring-security-core/guide/helperClasses.html

Change/Get check state of CheckBox

<input type="checkbox" name="checkAddress" onclick="if(this.checked){ alert('a'); }" />

Convert generic list to dataset in C#

I have slightly modified the accepted answer by handling value types. I came across this when trying to do the following and because GetProperties() is zero length for value types I was getting an empty dataset. I know this is not the use case for the OP but thought I'd post this change in case anyone else came across the same thing.

Enumerable.Range(1, 10).ToList().ToDataSet();

public static DataSet ToDataSet<T>(this IList<T> list)
{
    var elementType = typeof(T);
    var ds = new DataSet();
    var t = new DataTable();
    ds.Tables.Add(t);

    if (elementType.IsValueType)
    {
        var colType = Nullable.GetUnderlyingType(elementType) ?? elementType;
        t.Columns.Add(elementType.Name, colType);

    } else
    {
        //add a column to table for each public property on T
        foreach (var propInfo in elementType.GetProperties())
        {
            var colType = Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType;
            t.Columns.Add(propInfo.Name, colType);
        }
    }

    //go through each property on T and add each value to the table
    foreach (var item in list)
    {
        var row = t.NewRow();

        if (elementType.IsValueType)
        {
            row[elementType.Name] = item;
        }
        else
        {
            foreach (var propInfo in elementType.GetProperties())
            {
                row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value;
            }
        }
        t.Rows.Add(row);
    }

    return ds;
}

FB OpenGraph og:image not pulling images (possibly https?)

In addition, this problem also occurs when you add a user generated story (where you do not use og:image). For example:

POST /me/cookbook:eat?
  recipe=http://www.example.com/recipes/pizza/&
  image[0][url]=http://www.example.com/recipes/pizza/pizza.jpg&
  image[0][user_generated]=true&
  access_token=VALID_ACCESS_TOKEN

The above will only work with http and not with https. If you use https, you will get an error that says: Attached image () failed to upload

HTML-5 date field shows as "mm/dd/yyyy" in Chrome, even when valid date is set

I have same problem and i found solution which is given below with full datepicker using simple HTML,Javascript and CSS. In this code i prepare formate like dd/mm/yyyy but you can work any.

HTML Code:

    <body>
<input type="date" id="dt" onchange="mydate1();" hidden/>
<input type="text" id="ndt"  onclick="mydate();" hidden />
<input type="button" Value="Date" onclick="mydate();" />
</body>

CSS Code:

#dt{text-indent: -500px;height:25px; width:200px;}

Javascript Code :

function mydate()
{
  //alert("");
document.getElementById("dt").hidden=false;
document.getElementById("ndt").hidden=true;
}
function mydate1()
{
 d=new Date(document.getElementById("dt").value);
dt=d.getDate();
mn=d.getMonth();
mn++;
yy=d.getFullYear();
document.getElementById("ndt").value=dt+"/"+mn+"/"+yy
document.getElementById("ndt").hidden=false;
document.getElementById("dt").hidden=true;
}

Output:

enter image description here

How get data from material-ui TextField, DropDownMenu components?

Faced to this issue after a long time since question asked here. when checking material-ui code I found it's now accessible through inputRef property.

...
<CssTextField
  inputRef={(c) => {this.myRefs.username = c}}
  label="Username"
  placeholder="xxxxxxx"
  margin="normal"
  className={classes.textField}
  variant="outlined"
  fullWidth
/>
...

Then Access value like this.

  onSaveUser = () => {
    console.log('Saving user');
    console.log(this.myRefs.username.value);
  }

how to get program files x86 env variable?

IMHO, one point that is missing in this discussion is that whatever variable you use, it is guaranteed to always point at the appropriate folder. This becomes critical in the rare cases where Windows is installed on a drive other than C:\

How do I post button value to PHP?

Change the type to submit and give it a name (and remove the useless onclick and flat out the 90's style uppercased tags/attributes).

<input type="submit" name="foo" value="A" />
<input type="submit" name="foo" value="B" />
...

The value will be available by $_POST['foo'] (if the parent <form> has a method="post").

How to clear browser cache with php?

It seams you need to versionate, so when some change happens browser will catch something new and user won't need to clear browser's cache.

You can do it by subfolders (example /css/v1/style.css) or by filename (example: css/style_v1.css) or even by setting different folders for your website, example:

www.mywebsite.com/site1

www.mywebsite.com/site2

www.mywebsite.com/site3

And use a .htaccess or even change httpd.conf to redirect to your current application.

If's about one image or page:

    <?$time = date("H:i:s");?>
    <img src="myfile.jpg?time=<?$time;?>">

You can use $time on parts when you don't wanna cache. So it will always pull a new image. Versionate it seams a better approach, otherwise it can overload your server. Remember, browser's cache it's not only good to user experience, but also for your server.

WPF binding to Listbox selectedItem

Yocoder is right,

Inside the DataTemplate, your DataContext is set to the Rule its currently handling..

To access the parents DataContext, you can also consider using a RelativeSource in your binding:

<TextBlock Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ____Your Parent control here___ }}, Path=DataContext.SelectedRule.Name}" />

More info on RelativeSource can be found here:

http://msdn.microsoft.com/en-us/library/system.windows.data.relativesource.aspx

Removing Conda environment

You probably didn't fully deactivate the Conda environment - remember, the command you need to use with Conda is conda deactivate (for older versions, use source deactivate). So it may be wise to start a new shell and activate the environment in that before you try. Then deactivate it.

You can use the command

conda env remove -n ENV_NAME

to remove the environment with that name. (--name is equivalent to -n)

Note that you can also place environments anywhere you want using -p /path/to/env instead of -n ENV_NAME when both creating and deleting environments, if you choose. They don't have to live in your conda installation.

UPDATE, 30 Jan 2019: From Conda 4.6 onwards the conda activate command becomes the new official way to activate an environment across all platforms. The changes are described in this Anaconda blog post

No mapping found for HTTP request with URI.... in DispatcherServlet with name

Please check your [PROJECT_NAME]\target\classes directory to see whether myController.class is generated or not.

If not, please check all your java source code whether there are any compilation errors.

Cannot run Eclipse; JVM terminated. Exit code=13

Whenever you see this error, go to Configuration directory and check for a log file generated just now. It should have proper Exception stacktrace. Mine was a case where I got an updated 32-bit JRE (or JVM) installed which was the default Java that got added to the Path. And my Eclipse installation was 64-bit which meant it needed a 64-bit VM to run its native SWT libraries. So I simply uninstalled the 32-bit JVM and replaced it with a 64-bit JVM.

I wonder if they will improve this reporting mechanism, instead of silently generating a log file in some directory.

Whoops, looks like something went wrong. Laravel 5.0

  1. Rename the .env.example to .env
  2. Go to bootstrap=>app.php and uncomment $app->withEloquent();
  3. Make sure that APP_DEBUG=true in .env file. Now it will work.

How to calculate modulus of large numbers?

/* The algorithm is from the book "Discrete Mathematics and Its
   Applications 5th Edition" by Kenneth H. Rosen.
   (base^exp)%mod
*/

int modular(int base, unsigned int exp, unsigned int mod)
{
    int x = 1;
    int power = base % mod;

    for (int i = 0; i < sizeof(int) * 8; i++) {
        int least_sig_bit = 0x00000001 & (exp >> i);
        if (least_sig_bit)
            x = (x * power) % mod;
        power = (power * power) % mod;
    }

    return x;
}

What is the difference between partitioning and bucketing a table in Hive ?

There are great responses here. I would like to keep it short to memorize the difference between partition & buckets.

You generally partition on a less unique column. And bucketing on most unique column.

Example if you consider World population with country, person name and their bio-metric id as an example. As you can guess, country field would be the less unique column and bio-metric id would be the most unique column. So ideally you would need to partition the table by country and bucket it by bio-metric id.

Why is using the JavaScript eval function a bad idea?

It greatly reduces your level of confidence about security.

How to find MAC address of an Android device programmatically

WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
String macAddress = wInfo.getMacAddress(); 

Also, add below permission in your manifest file

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

Please refer to Android 6.0 Changes.

To provide users with greater data protection, starting in this release, Android removes programmatic access to the device’s local hardware identifier for apps using the Wi-Fi and Bluetooth APIs. The WifiInfo.getMacAddress() and the BluetoothAdapter.getAddress() methods now return a constant value of 02:00:00:00:00:00.

To access the hardware identifiers of nearby external devices via Bluetooth and Wi-Fi scans, your app must now have the ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION permissions.

How to create a temporary directory/folder in Java?

This code should work reasonably well:

public static File createTempDir() {
    final String baseTempPath = System.getProperty("java.io.tmpdir");

    Random rand = new Random();
    int randomInt = 1 + rand.nextInt();

    File tempDir = new File(baseTempPath + File.separator + "tempDir" + randomInt);
    if (tempDir.exists() == false) {
        tempDir.mkdir();
    }

    tempDir.deleteOnExit();

    return tempDir;
}

How to initialize an array in Kotlin with values?

Simple Way:

For Integer:

var number = arrayOf< Int> (10 , 20 , 30 , 40 ,50)

Hold All data types

var number = arrayOf(10 , "string value" , 10.5)

Python 'If not' syntax

Yes, if bar is not None is more explicit, and thus better, assuming it is indeed what you want. That's not always the case, there are subtle differences: if not bar: will execute if bar is any kind of zero or empty container, or False. Many people do use not bar where they really do mean bar is not None.

jQuery - Detect value change on hidden input field

Although this thread is 3 years old, here is my solution:

$(function ()
{
    keep_fields_uptodate();
});

function keep_fields_uptodate()
{
    // Keep all fields up to date!
    var $inputDate = $("input[type='date']");
    $inputDate.blur(function(event)
    {
        $("input").trigger("change");
    });
}

TypeError: 'undefined' is not an object

try out this if you want to assign value to object and it is showing this error in angular..

crate object in construtor

this.modelObj = new Model(); //<---------- after declaring object above

Generating a drop down list of timezones with PHP

In some projects it really doesn't make sense to have the detailed timezones of Africa, Europe or Pacific. So here is a short version

$timezoneTable = array(
    "-12" => "(GMT -12:00) Eniwetok, Kwajalein",
    "-11" => "(GMT -11:00) Midway Island, Samoa",
    "-10" => "(GMT -10:00) Hawaii",
    "-9" => "(GMT -9:00) Alaska",
    "-8" => "(GMT -8:00) Pacific Time (US &amp; Canada)",
    "-7" => "(GMT -7:00) Mountain Time (US &amp; Canada)",
    "-6" => "(GMT -6:00) Central Time (US &amp; Canada), Mexico City",
    "-5" => "(GMT -5:00) Eastern Time (US &amp; Canada), Bogota, Lima",
    "-4" => "(GMT -4:00) Atlantic Time (Canada), Caracas, La Paz",
    "-3.5" => "(GMT -3:30) Newfoundland",
    "-3" => "(GMT -3:00) Brazil, Buenos Aires, Georgetown",
    "-2" => "(GMT -2:00) Mid-Atlantic",
    "-1" => "(GMT -1:00) Azores, Cape Verde Islands",
    "0" => "(GMT) Western Europe Time, London, Lisbon, Casablanca",
    "1" => "(GMT +1:00) Brussels, Copenhagen, Madrid, Paris",
    "2" => "(GMT +2:00) Kaliningrad, South Africa",
    "3" => "(GMT +3:00) Baghdad, Riyadh, Moscow, St. Petersburg",
    "3.5" => "(GMT +3:30) Tehran",
    "4" => "(GMT +4:00) Abu Dhabi, Muscat, Baku, Tbilisi",
    "4.5" => "(GMT +4:30) Kabul",
    "5" => "(GMT +5:00) Ekaterinburg, Islamabad, Karachi, Tashkent",
    "5.5" => "(GMT +5:30) Bombay, Calcutta, Madras, New Delhi",
    "6" => "(GMT +6:00) Almaty, Dhaka, Colombo",
    "7" => "(GMT +7:00) Bangkok, Hanoi, Jakarta",
    "8" => "(GMT +8:00) Beijing, Perth, Singapore, Hong Kong",
    "9" => "(GMT +9:00) Tokyo, Seoul, Osaka, Sapporo, Yakutsk",
    "9.5" => "(GMT +9:30) Adelaide, Darwin",
    "10" => "(GMT +10:00) Eastern Australia, Guam, Vladivostok",
    "11" => "(GMT +11:00) Magadan, Solomon Islands, New Caledonia",
    "12" => "(GMT +12:00) Auckland, Wellington, Fiji, Kamchatka"
);

echo "<select>";
foreach ($timezoneTable as $k => $v){
    $sel = ($k==-5)?" selected":"";
    echo "<option value='".$k."'".$sel.">".$v."</option>";
}
echo "</select>" 

this will generate a select as below:

enter image description here

How to install gem from GitHub source?

In your Gemfile, add the following:

gem 'example', :git => 'git://github.com/example.git'

You can also add ref, branch and tag options,

For example if you want to download from a particular branch:

gem 'example', :git => "git://github.com/example.git", :branch => "my-branch"

Then run:

bundle install

Execution failed for task ':app:compileDebugJavaWithJavac' Android Studio 3.1 Update

I'm on Android Studio 3.1 Build #AI-173.4670197, built on March 22, 2018 JRE: 1.8.0_152-release-1024-b02 amd64 JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o Windows 10 10.

I had the same issue and it only worked after changing my build.grade file to

    compileOptions {                                                          
    sourceCompatibility JavaVersion.VERSION_1_8 
    targetCompatibility JavaVersion.VERSION_1_8


}

Prior to this change nothing worked and all compiles would fail. previously my settings were

sourceCompatibility JavaVersion.VERSION_1_7 
targetCompatibility JavaVersion.VERSION_1_8

how can I copy a conditional formatting in Excel 2010 to other cells, which is based on a other cells content?

I, too, have need for this! My situation involves comparing actuals with budget for cost centers, where expenses may have been mis-applied and therefore need to be re-allocated to the correct cost center so as to match how they were budgeted. It is very time consuming to try and scan row-by-row to see if each expense item has been correctly allocated. I decided that I should apply conditional formatting to highlight any cells where the actuals did not match the budget. I set up the conditional formatting to change the background color if the actual amount under the cost center did not match the budgeted amount.

Here's what I did:

Start in cell A1 (or the first cell you want to have the formatting). Open the Conditional Formatting dialogue box and select Apply formatting based on a formula. Then, I wrote a formula to compare one cell to another to see if they match:

=A1=A50

If the contents of cells A1 and A50 are equal, the conditional formatting will be applied. NOTICE: no $$, so the cell references are RELATIVE! Therefore, you can copy the formula from cell A1 and PasteSpecial (format). If you only click on the cells that you reference as you write your conditional formatting formula, the cells are by default locked, so then you wouldn't be able to apply them anywhere else (you would have to write out a new rule for each line- YUK!)

What is really cool about this is that if you insert rows under the conditionally formatted cell, the conditional formatting will be applied to the inserted rows as well!

Something else you could also do with this: Use ISBLANK if the amounts are not going to be exact matches, but you want to see if there are expenses showing up in columns where there are no budgeted amounts (i.e., BLANK) .

This has been a real time-saver for me. Give it a try and enjoy!

Hidden features of Python

Readable regular expressions

In Python you can split a regular expression over multiple lines, name your matches and insert comments.

Example verbose syntax (from Dive into Python):

>>> pattern = """
... ^                   # beginning of string
... M{0,4}              # thousands - 0 to 4 M's
... (CM|CD|D?C{0,3})    # hundreds - 900 (CM), 400 (CD), 0-300 (0 to 3 C's),
...                     #            or 500-800 (D, followed by 0 to 3 C's)
... (XC|XL|L?X{0,3})    # tens - 90 (XC), 40 (XL), 0-30 (0 to 3 X's),
...                     #        or 50-80 (L, followed by 0 to 3 X's)
... (IX|IV|V?I{0,3})    # ones - 9 (IX), 4 (IV), 0-3 (0 to 3 I's),
...                     #        or 5-8 (V, followed by 0 to 3 I's)
... $                   # end of string
... """
>>> re.search(pattern, 'M', re.VERBOSE)

Example naming matches (from Regular Expression HOWTO)

>>> p = re.compile(r'(?P<word>\b\w+\b)')
>>> m = p.search( '(((( Lots of punctuation )))' )
>>> m.group('word')
'Lots'

You can also verbosely write a regex without using re.VERBOSE thanks to string literal concatenation.

>>> pattern = (
...     "^"                 # beginning of string
...     "M{0,4}"            # thousands - 0 to 4 M's
...     "(CM|CD|D?C{0,3})"  # hundreds - 900 (CM), 400 (CD), 0-300 (0 to 3 C's),
...                         #            or 500-800 (D, followed by 0 to 3 C's)
...     "(XC|XL|L?X{0,3})"  # tens - 90 (XC), 40 (XL), 0-30 (0 to 3 X's),
...                         #        or 50-80 (L, followed by 0 to 3 X's)
...     "(IX|IV|V?I{0,3})"  # ones - 9 (IX), 4 (IV), 0-3 (0 to 3 I's),
...                         #        or 5-8 (V, followed by 0 to 3 I's)
...     "$"                 # end of string
... )
>>> print pattern
"^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$"

jQuery get specific option tag text

I needed this answer as I was dealing with a dynamically cast object, and the other methods here did not seem to work:

element.options[element.selectedIndex].text

This of course uses the DOM object instead of parsing its HTML with nodeValue, childNodes, etc.

PHP String to Float

Well, if user write 1,00,000 then floatvar will show error. So -

floatval(preg_replace("/[^-0-9\.]/","",$input));

This is much more reliable.

Usage :

$input = '1,03,24,23,434,500.6798633 this';
echo floatval(preg_replace("/[^-0-9\.]/","",$input));

How to drop a table if it exists?

There is an easier way

DROP TABLE IF EXISTS table_name;

How to test if list element exists?

Here is a performance comparison of the proposed methods in other answers.

> foo <- sapply(letters, function(x){runif(5)}, simplify = FALSE)
> microbenchmark::microbenchmark('k' %in% names(foo), 
                                 is.null(foo[['k']]), 
                                 exists('k', where = foo))
Unit: nanoseconds
                     expr  min   lq    mean median   uq   max neval cld
      "k" %in% names(foo)  467  933 1064.31    934  934 10730   100  a 
      is.null(foo[["k"]])    0    0  168.50      1  467  3266   100  a 
 exists("k", where = foo) 6532 6998 7940.78   7232 7465 56917   100   b

If you are planing to use the list as a fast dictionary accessed many times, then the is.null approach might be the only viable option. I assume it is O(1), while the %in% approach is O(n)?

How to change the buttons text using javascript

innerText is the current correct answer for this. The other answers are outdated and incorrect.

document.getElementById('ShowButton').innerText = 'Show filter';

innerHTML also works, and can be used to insert HTML.

AngularJS performs an OPTIONS HTTP request for a cross-origin resource

This fixed my problem:

$http.defaults.headers.post["Content-Type"] = "text/plain";

How do I implement Cross Domain URL Access from an Iframe using Javascript?

You can try and check for the referer, which should be the parent site if you're an iframe

you can do that like this:

var href = document.referrer;

Selecting only numeric columns from a data frame

EDIT: updated to avoid use of ill-advised sapply.

Since a data frame is a list we can use the list-apply functions:

nums <- unlist(lapply(x, is.numeric))  

Then standard subsetting

x[ , nums]

## don't use sapply, even though it's less code
## nums <- sapply(x, is.numeric)

For a more idiomatic modern R I'd now recommend

x[ , purrr::map_lgl(x, is.numeric)]

Less codey, less reflecting R's particular quirks, and more straightforward, and robust to use on database-back-ended tibbles:

dplyr::select_if(x, is.numeric)

Newer versions of dplyr, also support the following syntax:

x %>% dplyr::select(where(is.numeric))

Check input value length

You can add a form onsubmit handler, something like:

<form onsubmit="return validate();">

</form>


<script>function validate() {
 // check if input is bigger than 3
 var value = document.getElementById('titleeee').value;
 if (value.length < 3) {
   return false; // keep form from submitting
 }

 // else form is good let it submit, of course you will 
 // probably want to alert the user WHAT went wrong.

 return true;
}</script>

Pure CSS animation visibility with delay

You can play with delay prop of animation, just set visibility:visible after a delay, demo:

_x000D_
_x000D_
@keyframes delayedShow {_x000D_
  to {_x000D_
    visibility: visible;_x000D_
  }_x000D_
}_x000D_
_x000D_
.delayedShow{_x000D_
  visibility: hidden;_x000D_
  animation: 0s linear 2.3s forwards delayedShow ;_x000D_
}
_x000D_
So, Where are you?_x000D_
_x000D_
<div class="delayedShow">_x000D_
  Hey, I'm here!_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to abort a Task like aborting a Thread (Thread.Abort method)?

The guidance on not using a thread abort is controversial. I think there is still a place for it but in exceptional circumstance. However you should always attempt to design around it and see it as a last resort.

Example;

You have a simple windows form application that connects to a blocking synchronous web service. Within which it executes a function on the web service within a Parallel loop.

CancellationTokenSource cts = new CancellationTokenSource();
ParallelOptions po = new ParallelOptions();
po.CancellationToken = cts.Token;
po.MaxDegreeOfParallelism = System.Environment.ProcessorCount;

Parallel.ForEach(iListOfItems, po, (item, loopState) =>
{

    Thread.Sleep(120000); // pretend web service call

});

Say in this example, the blocking call takes 2 mins to complete. Now I set my MaxDegreeOfParallelism to say ProcessorCount. iListOfItems has 1000 items within it to process.

The user clicks the process button and the loop commences, we have 'up-to' 20 threads executing against 1000 items in the iListOfItems collection. Each iteration executes on its own thread. Each thread will utilise a foreground thread when created by Parallel.ForEach. This means regardless of the main application shutdown, the app domain will be kept alive until all threads have finished.

However the user needs to close the application for some reason, say they close the form. These 20 threads will continue to execute until all 1000 items are processed. This is not ideal in this scenario, as the application will not exit as the user expects and will continue to run behind the scenes, as can be seen by taking a look in task manger.

Say the user tries to rebuild the app again (VS 2010), it reports the exe is locked, then they would have to go into task manager to kill it or just wait until all 1000 items are processed.

I would not blame you for saying, but of course! I should be cancelling these threads using the CancellationTokenSource object and calling Cancel ... but there are some problems with this as of .net 4.0. Firstly this is still never going to result in a thread abort which would offer up an abort exception followed by thread termination, so the app domain will instead need to wait for the threads to finish normally, and this means waiting for the last blocking call, which would be the very last running iteration (thread) that ultimately gets to call po.CancellationToken.ThrowIfCancellationRequested. In the example this would mean the app domain could still stay alive for up to 2 mins, even though the form has been closed and cancel called.

Note that Calling Cancel on CancellationTokenSource does not throw an exception on the processing thread(s), which would indeed act to interrupt the blocking call similar to a thread abort and stop the execution. An exception is cached ready for when all the other threads (concurrent iterations) eventually finish and return, the exception is thrown in the initiating thread (where the loop is declared).

I chose not to use the Cancel option on a CancellationTokenSource object. This is wasteful and arguably violates the well known anti-patten of controlling the flow of the code by Exceptions.

Instead, it is arguably 'better' to implement a simple thread safe property i.e. Bool stopExecuting. Then within the loop, check the value of stopExecuting and if the value is set to true by the external influence, we can take an alternate path to close down gracefully. Since we should not call cancel, this precludes checking CancellationTokenSource.IsCancellationRequested which would otherwise be another option.

Something like the following if condition would be appropriate within the loop;

if (loopState.ShouldExitCurrentIteration || loopState.IsExceptional || stopExecuting) {loopState.Stop(); return;}

The iteration will now exit in a 'controlled' manner as well as terminating further iterations, but as I said, this does little for our issue of having to wait on the long running and blocking call(s) that are made within each iteration (parallel loop thread), since these have to complete before each thread can get to the option of checking if it should stop.

In summary, as the user closes the form, the 20 threads will be signaled to stop via stopExecuting, but they will only stop when they have finished executing their long running function call.

We can't do anything about the fact that the application domain will always stay alive and only be released when all foreground threads have completed. And this means there will be a delay associated with waiting for any blocking calls made within the loop to complete.

Only a true thread abort can interrupt the blocking call, and you must mitigate leaving the system in a unstable/undefined state the best you can in the aborted thread's exception handler which goes without question. Whether that's appropriate is a matter for the programmer to decide, based on what resource handles they chose to maintain and how easy it is to close them in a thread's finally block. You could register with a token to terminate on cancel as a semi workaround i.e.

CancellationTokenSource cts = new CancellationTokenSource();
ParallelOptions po = new ParallelOptions();
po.CancellationToken = cts.Token;
po.MaxDegreeOfParallelism = System.Environment.ProcessorCount;

Parallel.ForEach(iListOfItems, po, (item, loopState) =>
{

    using (cts.Token.Register(Thread.CurrentThread.Abort))
    {
        Try
        {
           Thread.Sleep(120000); // pretend web service call          
        }
        Catch(ThreadAbortException ex)
        {
           // log etc.
        }
        Finally
        {
          // clean up here
        }
    }

});

but this will still result in an exception in the declaring thread.

All things considered, interrupt blocking calls using the parallel.loop constructs could have been a method on the options, avoiding the use of more obscure parts of the library. But why there is no option to cancel and avoid throwing an exception in the declaring method strikes me as a possible oversight.

Eliminate space before \begin{itemize}

Use \vspace{-\topsep} before \begin{itemize}.

Use \setlength{\parskip}{0pt} \setlength{\itemsep}{0pt plus 1pt} after \begin{itemize}.

And for the space after the list, use \vspace{-\topsep} after \end{itemize}.

\vspace{-\topsep}
\begin{itemize}
  \setlength{\parskip}{0pt}
  \setlength{\itemsep}{0pt plus 1pt}
  \item ...
  \item ...
\end{itemize}
\vspace{-\topsep}

How do I execute a PowerShell script automatically using Windows task scheduler?

None of posted solutions worked for me. Workaround, which worked:

create a run.bat and put inside powershell.exe -file "C:\...\script.ps1"

then set Action to Program/Script: "C:\...\run.bat"

jQuery: Adding two attributes via the .attr(); method

Multiple Attribute

var tag = "tag name";
createNode(tag, target, attribute);

createNode: function(tag, target, attribute){
    var tag = jQuery("<" + tag + ">");
    jQuery.each(attribute, function(i,v){
        tag.attr(v);
    });
    target.append(tag);
    tag.appendTo(target);
}
var attribute = [
    {"data-level": "3"},
];

How is returning the output of a function different from printing it?

The below examples might help understand:

def add_nums1(x,y):
    print(x+y)

def add_nums2(x,y):
    return x+y 

#----Function output is usable for further processing
add_nums2(10,20)/2
15.0

#----Function output can't be used further (gives TypeError)
add_nums1(10,20)/2

30
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-124-e11302d7195e> in <module>
----> 1 add_nums1(10,20)/2

TypeError: unsupported operand type(s) for /: 'NoneType' and 'int'

Changing date format in R

I believe that

nzd$date <- as.Date(nzd$date, format = "%d/%m/%Y")

is sufficient.

How can I copy the content of a branch to a new local branch?

git checkout old_branch
git branch new_branch

This will give you a new branch "new_branch" with the same state as "old_branch".

This command can be combined to the following:

git checkout -b new_branch old_branch

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

Split string based on a regular expression

By using (,), you are capturing the group, if you simply remove them you will not have this problem.

>>> str1 = "a    b     c      d"
>>> re.split(" +", str1)
['a', 'b', 'c', 'd']

However there is no need for regex, str.split without any delimiter specified will split this by whitespace for you. This would be the best way in this case.

>>> str1.split()
['a', 'b', 'c', 'd']

If you really wanted regex you can use this ('\s' represents whitespace and it's clearer):

>>> re.split("\s+", str1)
['a', 'b', 'c', 'd']

or you can find all non-whitespace characters

>>> re.findall(r'\S+',str1)
['a', 'b', 'c', 'd']

Python error message io.UnsupportedOperation: not readable

You are opening the file as "w", which stands for writable.

Using "w" you won't be able to read the file. Use the following instead:

file = open("File.txt","r")

Additionally, here are the other options:

"r"   Opens a file for reading only.
"r+"  Opens a file for both reading and writing.
"rb"  Opens a file for reading only in binary format.
"rb+" Opens a file for both reading and writing in binary format.
"w"   Opens a file for writing only.
"a"   Open for writing.  The file is created if it does not exist.
"a+"  Open for reading and writing.  The file is created if it does not exist.

Two constructors

To call one constructor from another you need to use this() and you need to put it first. In your case the default constructor needs to call the one which takes an argument, not the other ways around.

CMake output/build directory

There's little need to set all the variables you're setting. CMake sets them to reasonable defaults. You should definitely not modify CMAKE_BINARY_DIR or CMAKE_CACHEFILE_DIR. Treat these as read-only.

First remove the existing problematic cache file from the src directory:

cd src
rm CMakeCache.txt
cd ..

Then remove all the set() commands and do:

cd Compile && rm -rf *
cmake ../src

As long as you're outside of the source directory when running CMake, it will not modify the source directory unless your CMakeList explicitly tells it to do so.

Once you have this working, you can look at where CMake puts things by default, and only if you're not satisfied with the default locations (such as the default value of EXECUTABLE_OUTPUT_PATH), modify only those you need. And try to express them relative to CMAKE_BINARY_DIR, CMAKE_CURRENT_BINARY_DIR, PROJECT_BINARY_DIR etc.

If you look at CMake documentation, you'll see variables partitioned into semantic sections. Except for very special circumstances, you should treat all those listed under "Variables that Provide Information" as read-only inside CMakeLists.

HTML/CSS--Creating a banner/header

Remove the position: absolute; attribute in the style

round() for float in C++

There are 2 problems we are looking at:

  1. rounding conversions
  2. type conversion.

Rounding conversions mean rounding ± float/double to nearest floor/ceil float/double. May be your problem ends here. But if you are expected to return Int/Long, you need to perform type conversion, and thus "Overflow" problem might hit your solution. SO, do a check for error in your function

long round(double x) {
   assert(x >= LONG_MIN-0.5);
   assert(x <= LONG_MAX+0.5);
   if (x >= 0)
      return (long) (x+0.5);
   return (long) (x-0.5);
}

#define round(x) ((x) < LONG_MIN-0.5 || (x) > LONG_MAX+0.5 ?\
      error() : ((x)>=0?(long)((x)+0.5):(long)((x)-0.5))

from : http://www.cs.tut.fi/~jkorpela/round.html

How do I get the absolute directory of a file in bash?

$cat abs.sh
#!/bin/bash
echo "$(cd "$(dirname "$1")"; pwd -P)"

Some explanations:

  1. This script get relative path as argument "$1"
  2. Then we get dirname part of that path (you can pass either dir or file to this script): dirname "$1"
  3. Then we cd "$(dirname "$1"); into this relative dir
  4. pwd -P and get absolute path. The -P option will avoid symlinks
  5. As final step we echo it

Then run your script:

abs.sh your_file.txt

Base64 decode snippet in C++

Here's my modification of the implementation that was originally written by René Nyffenegger. And why have I modified it? Well, because it didn't seem appropriate to me that I should work with binary data stored within std::string object ;)

base64.h:

#ifndef _BASE64_H_
#define _BASE64_H_

#include <vector>
#include <string>
typedef unsigned char BYTE;

std::string base64_encode(BYTE const* buf, unsigned int bufLen);
std::vector<BYTE> base64_decode(std::string const&);

#endif

base64.cpp:

#include "base64.h"
#include <iostream>

static const std::string base64_chars =
             "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
             "abcdefghijklmnopqrstuvwxyz"
             "0123456789+/";


static inline bool is_base64(BYTE c) {
  return (isalnum(c) || (c == '+') || (c == '/'));
}

std::string base64_encode(BYTE const* buf, unsigned int bufLen) {
  std::string ret;
  int i = 0;
  int j = 0;
  BYTE char_array_3[3];
  BYTE char_array_4[4];

  while (bufLen--) {
    char_array_3[i++] = *(buf++);
    if (i == 3) {
      char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
      char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
      char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
      char_array_4[3] = char_array_3[2] & 0x3f;

      for(i = 0; (i <4) ; i++)
        ret += base64_chars[char_array_4[i]];
      i = 0;
    }
  }

  if (i)
  {
    for(j = i; j < 3; j++)
      char_array_3[j] = '\0';

    char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
    char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
    char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
    char_array_4[3] = char_array_3[2] & 0x3f;

    for (j = 0; (j < i + 1); j++)
      ret += base64_chars[char_array_4[j]];

    while((i++ < 3))
      ret += '=';
  }

  return ret;
}

std::vector<BYTE> base64_decode(std::string const& encoded_string) {
  int in_len = encoded_string.size();
  int i = 0;
  int j = 0;
  int in_ = 0;
  BYTE char_array_4[4], char_array_3[3];
  std::vector<BYTE> ret;

  while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
    char_array_4[i++] = encoded_string[in_]; in_++;
    if (i ==4) {
      for (i = 0; i <4; i++)
        char_array_4[i] = base64_chars.find(char_array_4[i]);

      char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
      char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
      char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

      for (i = 0; (i < 3); i++)
          ret.push_back(char_array_3[i]);
      i = 0;
    }
  }

  if (i) {
    for (j = i; j <4; j++)
      char_array_4[j] = 0;

    for (j = 0; j <4; j++)
      char_array_4[j] = base64_chars.find(char_array_4[j]);

    char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
    char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
    char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

    for (j = 0; (j < i - 1); j++) ret.push_back(char_array_3[j]);
  }

  return ret;
}

Here's the usage:

std::vector<BYTE> myData;
...
std::string encodedData = base64_encode(&myData[0], myData.size());
std::vector<BYTE> decodedData = base64_decode(encodedData);

jquery to change style attribute of a div class

Try with

$('.handle').css({'left': '300px'});

Instead of

$('.handle').css({'style':'left: 300px'})

Paste text on Android Emulator

Made this Windows application that allows users to copy paste to Android emulators or connected devices from a visual interface. https://github.com/Florin-Birgu/Android-Copy-Paste

enter image description here

How do I set the request timeout for one controller action in an asp.net mvc application

You can set this programmatically in the controller:-

HttpContext.Current.Server.ScriptTimeout = 300;

Sets the timeout to 5 minutes instead of the default 110 seconds (what an odd default?)

Error Installing Homebrew - Brew Command Not Found

Check XCode is installed or not.

gcc --version
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
brew doctor
brew update

http://techsharehub.blogspot.com/2013/08/brew-command-not-found.html "click here for exact instruction updates"

How to efficiently check if variable is Array or Object (in NodeJS & V8)?

If its just about detecting whether or not you're dealing with an Object, I could think of

Object.getPrototypeOf( obj ) === Object.prototype

However, this would probably fail for non-object primitive values. Actually there is nothing wrong with invoking .toString() to retreive the [[cclass]] property. You can even create a nice syntax like

var type = Function.prototype.call.bind( Object.prototype.toString );

and then use it like

if( type( obj ) === '[object Object]' ) { }

It might not be the fastest operation but I don't think the performance leak there is too big.

How to handle button clicks using the XML onClick within Fragments

I would rather go for the click handling in code than using the onClick attribute in XML when working with fragments.

This becomes even easier when migrating your activities to fragments. You can just call the click handler (previously set to android:onClick in XML) directly from each case block.

findViewById(R.id.button_login).setOnClickListener(clickListener);
...

OnClickListener clickListener = new OnClickListener() {
    @Override
    public void onClick(final View v) {
        switch(v.getId()) {
           case R.id.button_login:
              // Which is supposed to be called automatically in your
              // activity, which has now changed to a fragment.
              onLoginClick(v);
              break;

           case R.id.button_logout:
              ...
        }
    }
}

When it comes to handling clicks in fragments, this looks simpler to me than android:onClick.

SQL query for today's date minus two months

If you are using SQL Server try this:

SELECT * FROM MyTable
WHERE MyDate < DATEADD(month, -2, GETDATE())

Based on your update it would be:

SELECT * FROM FB WHERE Dte <  DATEADD(month, -2, GETDATE())

Using the "start" command with parameters passed to the started program

Change The "Virtual PC.exe" to a name without space like "VirtualPC.exe" in the folder. When you write start "path" with "" the CMD starts a new cmd window with the path as the title. Change the name to a name without space,write this on Notepad and after this save like Name.cmd or Name.bat:

CD\
CD Program Files
CD Microsoft Virtual PC
start VirtualPC.exe
timeout 2
exit

This command will redirect the CMD to the folder,start the VirualPC.exe,wait 2 seconds and exit.

How do I raise the same Exception with a custom message in Python?

This code template should allow you to raise an exception with a custom message.

try:
     raise ValueError
except ValueError as err:
    raise type(err)("my message")

Where does Visual Studio look for C++ header files?

Visual Studio looks for headers in this order:

  • In the current source directory.
  • In the Additional Include Directories in the project properties (Project -> [project name] Properties, under C/C++ | General).
  • In the Visual Studio C++ Include directories under Tools ? Options ? Projects and Solutions ? VC++ Directories.
  • In new versions of Visual Studio (2015+) the above option is deprecated and a list of default include directories is available at Project Properties ? Configuration ? VC++ Directories

In your case, add the directory that the header is to the project properties (Project Properties ? Configuration ? C/C++ ? General ? Additional Include Directories).

How to identify and switch to the frame in selenium webdriver when frame does not have id

You also can use src to switch to frame, here is what you can use:

driver.switchTo().frame(driver.findElement(By.xpath(".//iframe[@src='https://tssstrpms501.corp.trelleborg.com:12001/teamworks/process.lsw?zWorkflowState=1&zTaskId=4581&zResetContext=true&coachDebugTrace=none']")));

HTTP authentication logout via PHP

Trac - by default - uses HTTP Authentication as well. Logout does not work and can not be fixed:

  • This is an issue with the HTTP authentication scheme itself, and there's nothing we can do in Trac to fix it properly.
  • There is currently no workaround (JavaScript or other) that works with all major browsers.

From: http://trac.edgewall.org/ticket/791#comment:103

Looks like that there is no working answer to the question, that issue has been reported seven years ago and it makes perfect sense: HTTP is stateless. Either a request is done with authentication credentials or not. But that's a matter of the client sending the request, not the server receiving it. The server can only say if a request URI needs authorization or not.

How to print the full NumPy array, without truncation?

with np.printoptions(edgeitems=50):
    print(x)

Change 50 to how many lines you wanna see

Source: here

MySQL - UPDATE query based on SELECT Query

You can use:

UPDATE Station AS st1, StationOld AS st2
   SET st1.already_used = 1
 WHERE st1.code = st2.code

Swipe to Delete and the "More" button (like in Mail app on iOS 7)

I was looking to add the same functionality to my app, and after going through so many different tutorials (raywenderlich being the best DIY solution), I found out that Apple has its own UITableViewRowActionclass, which is very handy.

You have to change the Tableview's boilerpoint method to this:

override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]?  {
    // 1   
    var shareAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Share" , handler: { (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in
    // 2
    let shareMenu = UIAlertController(title: nil, message: "Share using", preferredStyle: .ActionSheet)

    let twitterAction = UIAlertAction(title: "Twitter", style: UIAlertActionStyle.Default, handler: nil)
    let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)

    shareMenu.addAction(twitterAction)
    shareMenu.addAction(cancelAction)


    self.presentViewController(shareMenu, animated: true, completion: nil)
    })
    // 3
    var rateAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Rate" , handler: { (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in
    // 4
    let rateMenu = UIAlertController(title: nil, message: "Rate this App", preferredStyle: .ActionSheet)

    let appRateAction = UIAlertAction(title: "Rate", style: UIAlertActionStyle.Default, handler: nil)
    let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)

    rateMenu.addAction(appRateAction)
    rateMenu.addAction(cancelAction)


    self.presentViewController(rateMenu, animated: true, completion: nil)
    })
    // 5
    return [shareAction,rateAction]
  }

You can find out more about this on This Site. Apple's own documentation is really useful for changing the background colour:

The background color of the action button.

Declaration OBJECTIVE-C @property(nonatomic, copy) UIColor *backgroundColor Discussion Use this property to specify the background color for your button. If you do not specify a value for this property, UIKit assigns a default color based on the value in the style property.

Availability Available in iOS 8.0 and later.

If you want to change the font of the button, it's a bit more tricky. I've seen another post on SO. For the sake of providing the code as well as the link, here's the code they used there. You'd have to change the appearance of the button. You'd have to make a specific reference to tableviewcell, otherwise you'd change the button's appearance throughout your app (I didn't want that, but you might, I don't know :) )

Objective C:

+ (void)setupDeleteRowActionStyleForUserCell {

    UIFont *font = [UIFont fontWithName:@"AvenirNext-Regular" size:19];

    NSDictionary *attributes = @{NSFontAttributeName: font,
                      NSForegroundColorAttributeName: [UIColor whiteColor]};

    NSAttributedString *attributedTitle = [[NSAttributedString alloc] initWithString: @"DELETE"
                                                                          attributes: attributes];

    /*
     * We include UIView in the containment hierarchy because there is another button in UserCell that is a direct descendant of UserCell that we don't want this to affect.
     */
    [[UIButton appearanceWhenContainedIn:[UIView class], [UserCell class], nil] setAttributedTitle: attributedTitle
                                                                                          forState: UIControlStateNormal];
}

Swift:

    //create your attributes however you want to
    let attributes = [NSFontAttributeName: UIFont.systemFontOfSize(UIFont.systemFontSize())] as Dictionary!            

   //Add more view controller types in the []
    UIButton.appearanceWhenContainedInInstancesOfClasses([ViewController.self])

This is the easiest, and most stream-lined version IMHO. Hope it helps.

Update: Here's the Swift 3.0 version:

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    var shareAction:UITableViewRowAction = UITableViewRowAction(style: .default, title: "Share", handler: {(action, cellIndexpath) -> Void in
        let shareMenu = UIAlertController(title: nil, message: "Share using", preferredStyle: .actionSheet)

        let twitterAction = UIAlertAction(title: "Twitter", style: .default, handler: nil)
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)

        shareMenu.addAction(twitterAction)
        shareMenu.addAction(cancelAction)


        self.present(shareMenu,animated: true, completion: nil)
    })

    var rateAction:UITableViewRowAction = UITableViewRowAction(style: .default, title: "Rate" , handler: {(action, cellIndexpath) -> Void in
        // 4
        let rateMenu = UIAlertController(title: nil, message: "Rate this App", preferredStyle: .actionSheet)

        let appRateAction = UIAlertAction(title: "Rate", style: .default, handler: nil)
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)

        rateMenu.addAction(appRateAction)
        rateMenu.addAction(cancelAction)


        self.present(rateMenu, animated: true, completion: nil)
    })
    // 5
    return [shareAction,rateAction]
}

How to make padding:auto work in CSS?

if you're goal is to reset EVERYTHING then @Björn's answer should be your goal but applied as:

* {
  padding: initial;
}

if this is loaded after your original reset.css should have the same weight and will rely on each browser's default padding as initial value.

How to cast the size_t to double or int C++

A cast, as Blaz Bratanic suggested:

size_t data = 99999999;
int convertdata = static_cast<int>(data);

is likely to silence the warning (though in principle a compiler can warn about anything it likes, even if there's a cast).

But it doesn't solve the problem that the warning was telling you about, namely that a conversion from size_t to int really could overflow.

If at all possible, design your program so you don't need to convert a size_t value to int. Just store it in a size_t variable (as you've already done) and use that.

Converting to double will not cause an overflow, but it could result in a loss of precision for a very large size_t value. Again, it doesn't make a lot of sense to convert a size_t to a double; you're still better off keeping the value in a size_t variable.

(R Sahu's answer has some suggestions if you can't avoid the cast, such as throwing an exception on overflow.)

What's the difference between a 302 and a 307 redirect?

The difference concerns redirecting POST, PUT and DELETE requests and what the expectations of the server are for the user agent behavior (RFC 2616):

Note: RFC 1945 and RFC 2068 specify that the client is not allowed to change the method on the redirected request. However, most existing user agent implementations treat 302 as if it were a 303 response, performing a GET on the Location field-value regardless of the original request method. The status codes 303 and 307 have been added for servers that wish to make unambiguously clear which kind of reaction is expected of the client.

Also, read Wikipedia article on the 30x redirection codes.

Excel - Using COUNTIF/COUNTIFS across multiple sheets/same column

This could be solved without VBA by the following technique.

In this example I am counting all the threes (3) in the range A:A of the sheets Page M904, Page M905 and Page M906.

List all the sheet names in a single continuous range like in the following example. Here listed in the range D3:D5.

enter image description here

Then by having the lookup value in cell B2, the result can be found in cell B4 by using the following formula:

=SUMPRODUCT(COUNTIF(INDIRECT("'"&D3:D5&"'!A:A"), B2))

Set element width or height in Standards Mode

Try declaring the unit of width:

e1.style.width = "400px"; // width in PIXELS

Regex for numbers only

If you need to tolerate decimal point and thousand marker

var regex = new Regex(@"^-?[0-9][0-9,\.]+$");

You will need a "-", if the number can go negative.

Coerce multiple columns to factors at once

You can use mutate_if (dplyr):

For example, coerce integer in factor:

mydata=structure(list(a = 1:10, b = 1:10, c = c("a", "a", "b", "b", 
"c", "c", "c", "c", "c", "c")), row.names = c(NA, -10L), class = c("tbl_df", 
"tbl", "data.frame"))

# A tibble: 10 x 3
       a     b c    
   <int> <int> <chr>
 1     1     1 a    
 2     2     2 a    
 3     3     3 b    
 4     4     4 b    
 5     5     5 c    
 6     6     6 c    
 7     7     7 c    
 8     8     8 c    
 9     9     9 c    
10    10    10 c   

Use the function:

library(dplyr)

mydata%>%
    mutate_if(is.integer,as.factor)

# A tibble: 10 x 3
       a     b c    
   <fct> <fct> <chr>
 1     1     1 a    
 2     2     2 a    
 3     3     3 b    
 4     4     4 b    
 5     5     5 c    
 6     6     6 c    
 7     7     7 c    
 8     8     8 c    
 9     9     9 c    
10    10    10 c