Programs & Examples On #Toolchain

A toolchain is a collection of software tools that work together to build and manage programs.

Xcode 10, Command CodeSign failed with a nonzero exit code

In Xcode: Go to Preferences Logout of the current user.

Close Xcode

In Keychain: Go to Login and All items

        - Sort by kind
             - remove "Apple Worldwide Developer Relation Certification Authority"
             - remove "Developer ID Certification Authority"
             - remove "iPhone Developer ...."

Open Xcode

Go to Preferences and Login to you user apple account

  • This will reload your developer certificates you previous deleted Rebuild the project (Should be a successful build)

Run the build on your native device

Flutter plugin not installed error;. When running flutter doctor

The best way to install it on Windows 

Doctor summary (to see all details, run flutter doctor -v):
[v] Flutter (Channel stable, 1.20.1, on Microsoft Windows [Version 10.0.18363.959], locale en-US)
[v] Android toolchain - develop for Android devices (Android SDK version 30.0.0)
[v] Android Studio (version 4.0)
[v] VS Code (version 1.47.3)
[!] Connected device
    ! No devices available

1- Open Android Studio File->Settings->Plugins and Make Sure You have Flutter and Dart Installed enter image description here

2- Go to VSCode to Extensions and install Flutter and Dart Extension

enter image description here

Hope It Solved the problem

Flutter.io Android License Status Unknown

Just install the sdk command line tool(latest) the below in android studio. enter image description here

Flutter does not find android sdk

Flutter say Sdk build tool version(exp:android toolchain - develop for android devices (android sdk 28.0.3)) version=28.0.3 go to home/username/Android/Sdk/build-tools delete this version(28.0.3) and fixed bug

flutter run: No connected devices

I had the same issue. Setting up the Android SDK is also a correct answer. But this is very simple -

  1. Import an android project to a new Android studio window.
  2. Close your current Flutter project Android studio window.
  3. Import that Flutter project to new Android Studio window.

Dart SDK is not configured

Run this command:

$ echo "$(dirname $(which flutter))/cache/dart-sdk"

You'll get something like:

/home/lex/opt/flutter/bin/cache/dart-sdk

Enter that value as your Dart SDK path.

docker entrypoint running bash script gets "permission denied"

An executable file needs to have permissions for execute set before you can execute it.

In your machine where you are building the docker image (not inside the docker image itself) try running:

ls -la path/to/directory

The first column of the output for your executable (in this case docker-entrypoint.sh) should have the executable bits set something like:

-rwxrwxr-x

If not then try:

chmod +x docker-entrypoint.sh

and then build your docker image again.

Docker uses it's own file system but it copies everything over (including permissions bits) from the source directories.

Error: No toolchains found in the NDK toolchains folder for ABI with prefix: llvm

First, try updating the ndk version https://developer.android.com/ndk/downloads/

If that's not working then you can try the following:

  • Create a folder

    Go to the Sdk\ndk-bundle\toolchains folder (in my case its C:\Users\USER\AppData\Local\Android\Sdk\ndk-bundle\toolchains; you can find yours under File->project structure->SDK location in you android studio) and create a folder with the name that's shown as missing in the error for eg: if the error is

    Gradle sync failed: No toolchains found in the NDK toolchains folder for ABI with prefix: mipsel-linux-android

    Then create a folder with name mipsel-linux-android

  • Include content Go to the Sdk\ndk-bundle\toolchains folder again and open any folder that's already in it. For example:Sdk\ndk-bundle\toolchains\aarch64-linux-android-4.9 (in mycase C:\Users\USER\AppData\Local\Android\Sdk\ndk-bundle\toolchains\aarch64-linux-android-4.9) copy the prebuilt folder in it to the folder we created in the last step

  • Run the project again and it will work

Hope it helps!!

Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its dependencies could not be resolved

refering to Deepak Vishwakarma's answer, I tried with that and was facing same problem with the url-problem. I installed maven-3.6.3 and inside .m2 folder I found a

settings.xml.bak

file and from that copied that mirror link and just changed url what @Deepak did. It worked like charm! Mirror link I got from that .bak file

http://local.maven.repo:9081/nexus/content/groups/public

Then executed :

mvn clean 
mvn clean install

How to install numpy on windows using pip install?

Check installation of python 2.7 than install/reinstall pip which described here than open command line and write

pip install numpy

or

pip install scipy

if already installed try this

pip install -U numpy

command/usr/bin/codesign failed with exit code 1- code sign error

Do everything d4Rk suggests, that is a great walk-through. if it still isn't signing, you might have some expired or revoked certificates. I find this can happen when you're working on a team.

  1. quit xcode.
  2. open Keychain Access.
  3. in the 'Certificates' section, go through all "iPhone Distribution" certificates and if they're expired or revoked or otherwise invalid, delete them.
  4. same as 3, but for the 'My Certificates' section.
  5. re-open xcode and try again.

Is it possible to use std::string in a constexpr?

Since the problem is the non-trivial destructor so if the destructor is removed from the std::string, it's possible to define a constexpr instance of that type. Like this

struct constexpr_str {
    char const* str;
    std::size_t size;

    // can only construct from a char[] literal
    template <std::size_t N>
    constexpr constexpr_str(char const (&s)[N])
        : str(s)
        , size(N - 1) // not count the trailing nul
    {}
};

int main()
{
    constexpr constexpr_str s("constString");

    // its .size is a constexpr
    std::array<int, s.size> a;
    return 0;
}

Command failed due to signal: Segmentation fault: 11

I hit this error. After some frustration I tried Xcode clean and everything started working again. Just leaving this here for future reference.

CMake is not able to find BOOST libraries

Long answer to short, if you install boost in custom path, all header files must in ${path}/boost/.

if you want to konw why cmake can't find the requested Boost libraries after you have set BOOST_ROOT/BOOST_INCLUDEDIR, you can check cmake install location path_to_cmake/share/cmake-xxx/Modules/FindBoost.

cmake which will find Boost_INCLUDE_DIR in boost/config.hpp in BOOST_ROOT. That means your boost header file must in ${path}/boost/, any other format (such as ${path}/boost-x.y.z) will not be suitable for find_package in CMakeLists.txt.

Xcode - ld: library not found for -lPods

For me this is worked. I have changed my app name from someApp to otherApp. And I am using cocoa pods for multiple third party services integration. So Because of that 2 libPod files added(As I have changed name and target of app). Finally I had to remove one libPod. And it worked.

target-> Build phases-> Link Binary With Libraries

libz.so.1: cannot open shared object file

Check below link: Specially "Install 32 bit libraries (if you're on 64 bit)"

 https://github.com/meteor/meteor/wiki/Mobile-Dev-Install:-Android-on-Linux

How to install the Raspberry Pi cross compiler on my Linux host machine?

The initial question has been posted quite some time ago and in the meantime Debian has made huge headway in the area of multiarch support.

Multiarch is a great achievement for cross compilation!

In a nutshell the following steps are required to leverage multiarch for Raspbian Jessie cross compilation:

  • On your Ubuntu host install Debian Jessie amd64 within a chroot or a LXC container.
  • Enable the foreign architecture armhf.
  • Install the cross compiler from the emdebian tools repository.
  • Tweak the cross compiler (it would generate code for ARMv7-A by default) by writing a custom gcc specs file.
  • Install armhf libraries (libstdc++ etc.) from the Raspbian repository.
  • Build your source code.

Since this is a lot of work I have automated the above setup. You can read about it here:

Cross Compiling for Raspbian

gcc-arm-linux-gnueabi command not found

try the following command:

which gcc-arm-linux-gnueabi

Its very likely the command is installed in /usr/bin.

Eclipse C++: Symbol 'std' could not be resolved

The problem you are reporting seems to me caused by the following:

  1. you are trying to compile C code and the source file has .cpp extension
  2. you are trying to compile C++ code and the source file has .c extension

In such situation Eclipse cannot recognize the proper compiler to use.

How do you set CMAKE_C_COMPILER and CMAKE_CXX_COMPILER for building Assimp for iOS?

Option 1:

You can set CMake variables at command line like this:

cmake -D CMAKE_C_COMPILER="/path/to/your/c/compiler/executable" -D CMAKE_CXX_COMPILER "/path/to/your/cpp/compiler/executable" /path/to/directory/containing/CMakeLists.txt

See this to learn how to create a CMake cache entry.


Option 2:

In your shell script build_ios.sh you can set environment variables CC and CXX to point to your C and C++ compiler executable respectively, example:

export CC=/path/to/your/c/compiler/executable
export CXX=/path/to/your/cpp/compiler/executable
cmake /path/to/directory/containing/CMakeLists.txt

Option 3:

Edit the CMakeLists.txt file of "Assimp": Add these lines at the top (must be added before you use project() or enable_language() command)

set(CMAKE_C_COMPILER "/path/to/your/c/compiler/executable")
set(CMAKE_CXX_COMPILER "/path/to/your/cpp/compiler/executable")

See this to learn how to use set command in CMake. Also this is a useful resource for understanding use of some of the common CMake variables.


Here is the relevant entry from the official FAQ: https://gitlab.kitware.com/cmake/community/wikis/FAQ#how-do-i-use-a-different-compiler

Command /Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang failed with exit code 1

For me this error appears after cloning the project from a repository. Someone removed a white space from the projects name (renamed: "The Project" to "TheProject") which caused some Build Settings errors to unvalid paths.

Sometimes reading the whole error logs is not a bad idea....

The program can't start because cygwin1.dll is missing... in Eclipse CDT

You can compile with either Cygwin's g++ or MinGW (via stand-alone or using Cygwin package). However, in order to run it, you need to add the Cygwin1.dll (and others) PATH to the system Windows PATH, before any cygwin style paths.

Thus add: ;C:\cygwin64\bin to the end of your Windows system PATH variable.

Also, to compile for use in CMD or PowerShell, you may need to use:

x86_64-w64-mingw32-g++.exe -static -std=c++11 prog_name.cc -o prog_name.exe

(This invokes the cross-compiler, if installed.)

CMAKE_MAKE_PROGRAM not found

I have two suggestions:

  1. Do you have make in your %PATH% environment variable? On my system, I need to add %MINGW_DIR%\bin to %PATH%.

  2. Do you have make installed? Depending on your mingw installation, it can be a separate package.

  3. Last resort: Can you pass the full path to make on the commandline? cmake -D"CMAKE_MAKE_PROGRAM:PATH=C:/MinGW-32/bin/make.exe" ..\Source

How can I link to a specific glibc version?

Link with -static. When you link with -static the linker embeds the library inside the executable, so the executable will be bigger, but it can be executed on a system with an older version of glibc because the program will use it's own library instead of that of the system.

What is the best IDE for C Development / Why use Emacs over an IDE?

Emacs is an IDE.

edit: OK, I'll elaborate. What is an IDE?

As a starting point, let's expand the acronym: Integrated Development Environment. To analyze this, I start from the end.

An environment is, generally speaking, the part of the world that surrounds the point of view. In this case, it is what we see on our monitor (perhaps hear from our speakers) and manipulate through our keyboard (and perhaps a mouse).

Development is what we want to do in this environment, its purpose, if you want. We use the environment to develop software. This defines what subparts we need: an editor, an interface to the REPL, resp. the compiler, an interface to the debugger, and access to online documentation (this list may not be exhaustive).

Integrated means that all parts of the environment are somehow under a uniform surface. In an IDE, we can access and use the different subparts with a minimum of switching; we don't have to leave our defined environment. This integration lets the different subparts interact better. For example, the editor can know about what language we write in, and give us symbol autocompletion, jump-to-definition, auto-indentation, syntax highlighting, etc.. It can get information from the compiler, automatically jump to errors, and highlight them. In most, if not all IDEs, the editor is naturally at the heart of the development process.

Emacs does all this, it does it with a wide range of languages and tasks, and it does it with excellence, since it is seamlessly expandable by the user wherever he misses anything.

Counterexample: you could develop using something like Notepad, access documentation through Firefox and XPdf, and steer the compiler and debugger from a shell. This would be a Development Environment, but it would not be integrated.

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

Your library is a dynamic library. You need to tell the operating system where it can locate it at runtime.

To do so, we will need to do those easy steps:

(1 ) Find where the library is placed if you don't know it.

sudo find / -name the_name_of_the_file.so

(2) Check for the existence of the dynamic library path environment variable(LD_LIBRARY_PATH)

$ echo $LD_LIBRARY_PATH

if there is nothing to be displayed, add a default path value (or not if you wish to)

$ LD_LIBRARY_PATH=/usr/local/lib

(3) We add the desire path, export it and try the application.

Note that the path should be the directory where the path.so.something is. So if path.so.something is in /my_library/path.so.something it should be :

$ LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/my_library/
$ export LD_LIBRARY_PATH
$ ./my_app

source : http://www.gnu.org/software/gsl/manual/html_node/Shared-Libraries.html

How do I pass a string into subprocess.Popen (using the stdin argument)?

There's a beautiful solution if you're using Python 3.4 or better. Use the input argument instead of the stdin argument, which accepts a bytes argument:

output = subprocess.check_output(
    ["sed", "s/foo/bar/"],
    input=b"foo",
)

This works for check_output and run, but not call or check_call for some reason.

Where are static variables stored in C and C++?

Where your statics go depends on whether they are zero-initialized. zero-initialized static data goes in .BSS (Block Started by Symbol), non-zero-initialized data goes in .DATA

Are there pointers in php?

You can simulate pointers to instantiated objects to some degree:

class pointer {
   var $child;

   function pointer(&$child) {
       $this->child = $child;
   }

   public function __call($name, $arguments) {
       return call_user_func_array(
           array($this->child, $name), $arguments);
   }
}

Use like this:

$a = new ClassA();

$p = new pointer($a);

If you pass $p around, it will behave like a C++ pointer regarding method calls (you can't touch object variables directly, but that's evil anyways :) ).

How to horizontally center an unordered list of unknown width?

The answer of philfreo is great, it works perfectly (cross-browser, with IE 7+). Just add my exp for the anchor tag inside li.

#footer ul li { display: inline; }
#footer ul li a { padding: 2px 4px; } /* no display: block here */

#footer ul li { position: relative; float: left; display: block; right: 50%; }
#footer ul li a {display: block; left: 0; } 

How to remove margin space around body or clear default css styles

Go with this

body {
    padding:0px;
    margin:0px;
}

How do I get a file name from a full path with PHP?

It's simple. For example:

<?php
    function filePath($filePath)
    {
        $fileParts = pathinfo($filePath);

        if (!isset($fileParts['filename']))
        {
            $fileParts['filename'] = substr($fileParts['basename'], 0, strrpos($fileParts['basename'], '.'));
        }
        return $fileParts;
    }

    $filePath = filePath('/www/htdocs/index.html');
    print_r($filePath);
?>

The output will be:

Array
(
    [dirname] => /www/htdocs
    [basename] => index.html
    [extension] => html
    [filename] => index
)

Can you style an html radio button to look like a checkbox?

In CSS3:

input[type=radio] {content:url(mycheckbox.png)}
input[type=radio]:checked {content:url(mycheckbox-checked.png)}

In reality:

<span class=fakecheckbox><input type=radio><img src="checkbox.png" alt=""></span>

@media screen {.fakecheckbox img {display:none}}
@media print {.fakecheckbox input {display:none;}}

and you'll need Javascript to keep <img> and radios in sync (and ideally insert them there in a first place).

I've used <img>, because browsers are usually configured not to print background-image. It's better to use image than another control, because image is non-interactive and less likely to cause problems.

Tkinter scrollbar for frame

Please note that the proposed code is only valid with Python 2

Here is an example:

from Tkinter import *   # from x import * is bad practice
from ttk import *

# http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame

class VerticalScrolledFrame(Frame):
    """A pure Tkinter scrollable frame that actually works!
    * Use the 'interior' attribute to place widgets inside the scrollable frame
    * Construct and pack/place/grid normally
    * This frame only allows vertical scrolling

    """
    def __init__(self, parent, *args, **kw):
        Frame.__init__(self, parent, *args, **kw)            

        # create a canvas object and a vertical scrollbar for scrolling it
        vscrollbar = Scrollbar(self, orient=VERTICAL)
        vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE)
        canvas = Canvas(self, bd=0, highlightthickness=0,
                        yscrollcommand=vscrollbar.set)
        canvas.pack(side=LEFT, fill=BOTH, expand=TRUE)
        vscrollbar.config(command=canvas.yview)

        # reset the view
        canvas.xview_moveto(0)
        canvas.yview_moveto(0)

        # create a frame inside the canvas which will be scrolled with it
        self.interior = interior = Frame(canvas)
        interior_id = canvas.create_window(0, 0, window=interior,
                                           anchor=NW)

        # track changes to the canvas and frame width and sync them,
        # also updating the scrollbar
        def _configure_interior(event):
            # update the scrollbars to match the size of the inner frame
            size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
            canvas.config(scrollregion="0 0 %s %s" % size)
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the canvas's width to fit the inner frame
                canvas.config(width=interior.winfo_reqwidth())
        interior.bind('<Configure>', _configure_interior)

        def _configure_canvas(event):
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the inner frame's width to fill the canvas
                canvas.itemconfigure(interior_id, width=canvas.winfo_width())
        canvas.bind('<Configure>', _configure_canvas)


if __name__ == "__main__":

    class SampleApp(Tk):
        def __init__(self, *args, **kwargs):
            root = Tk.__init__(self, *args, **kwargs)


            self.frame = VerticalScrolledFrame(root)
            self.frame.pack()
            self.label = Label(text="Shrink the window to activate the scrollbar.")
            self.label.pack()
            buttons = []
            for i in range(10):
                buttons.append(Button(self.frame.interior, text="Button " + str(i)))
                buttons[-1].pack()

    app = SampleApp()
    app.mainloop()

It does not yet have the mouse wheel bound to the scrollbar but it is possible. Scrolling with the wheel can get a bit bumpy, though.

edit:

to 1)
IMHO scrolling frames is somewhat tricky in Tkinter and does not seem to be done a lot. It seems there is no elegant way to do it.
One problem with your code is that you have to set the canvas size manually - that's what the example code I posted solves.

to 2)
You are talking about the data function? Place works for me, too. (In general I prefer grid).

to 3)
Well, it positions the window on the canvas.

One thing I noticed is that your example handles mouse wheel scrolling by default while the one I posted does not. Will have to look at that some time.

Which mime type should I use for mp3

Use .mp3 audio/mpeg, that's the one I always used. I guess others are just aliases.

How do I reformat HTML code using Sublime Text 2?

I'm using tidy together with custom build system to prettify HTML.

I have HTMLTidy.sublime-build in my Packages/User/ directory:

{
  "cmd": ["tidy", "-config", "$packages/User/tidy_config.cfg", "$file"]
}

and tidy_config.cfg file in the same directory:

indent: auto
tab-size: 4
show-warnings: no
write-back: yes
quiet: yes
indent-cdata: yes
tidy-mark: no
wrap: 0

And just select build system and press ctrl+b or cmd+b to reformat file content. One minor issue with that is that ST2 does not automatically reload the file so to see the results you have to switch to some other file and back (or to other application and back).

On Mac I've used macports to install tidy, on Windows you'd have to download it yourself and specify working directory in the build system, where tidy is located:

"working_dir": "c:\\HTMLTidy\\"

or add it to the PATH.

Form inline inside a form horizontal in twitter bootstrap?

Since bootstrap 4 use div class="form-row" in combination with div class="form-group col-X". X is the width you need. You will get nice inline columns. See fiddle.

<form class="form-horizontal" name="FORMNAME" method="post" action="ACTION" enctype="multipart/form-data">
    <div class="form-group">
        <label class="control-label col-sm-2" for="naam">Naam:&nbsp;*</label>
        <div class="col-sm-10">
            <input type="text" require class="form-control" id="naam" name="Naam" placeholder="Uw naam" value="{--NAAM--}" >
            <div id="naamx" class="form-error form-hidden">Wat is uw naam?</div>
        </div>
    </div>

    <div class="form-row">

        <div class="form-group col-5">
            <label class="control-label col-sm-4" for="telefoon">Telefoon:&nbsp;*</label>
            <div class="col-sm-12">
                <input type="tel" require class="form-control" id="telefoon" name="Telefoon" placeholder="Telefoon nummer" value="{--TELEFOON--}" >
                <div id="telefoonx" class="form-error form-hidden">Wat is uw telefoonnummer?</div>
            </div>
        </div>

        <div class="form-group col-5">
            <label class="control-label col-sm-4" for="email">E-mail: </label>
            <div class="col-sm-12">
                <input type="email" require class="form-control" id="email" name="E-mail" placeholder="E-mail adres" value="{--E-MAIL--}" >
                <div id="emailx" class="form-error form-hidden">Wat is uw e-mail adres?</div>
                    </div>
                </div>

        </div>

    <div class="form-group">
        <label class="control-label col-sm-2" for="titel">Titel:&nbsp;*</label>
        <div class="col-sm-10">
            <input type="text" require class="form-control" id="titel" name="Titel" placeholder="Titel van uw vraag of aanbod" value="{--TITEL--}" >
            <div id="titelx" class="form-error form-hidden">Wat is de titel van uw vraag of aanbod?</div>
        </div>
    </div>
<from>

Interfaces vs. abstract classes

The advantages of an abstract class are:

  • Ability to specify default implementations of methods
  • Added invariant checking to functions
  • Have slightly more control in how the "interface" methods are called
  • Ability to provide behavior related or unrelated to the interface for "free"

Interfaces are merely data passing contracts and do not have these features. However, they are typically more flexible as a type can only be derived from one class, but can implement any number of interfaces.

Android: How to programmatically access the device serial number shown in the AVD manager (API Version 8)

This is the hardware serial number. To access it on

  • Android Q (>= SDK 29) android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE is required. Only system apps can require this permission. If the calling package is the device or profile owner then the READ_PHONE_STATE permission suffices.

  • Android 8 and later (>= SDK 26) use android.os.Build.getSerial() which requires the dangerous permission READ_PHONE_STATE. Using android.os.Build.SERIAL returns android.os.Build.UNKNOWN.

  • Android 7.1 and earlier (<= SDK 25) and earlier android.os.Build.SERIAL does return a valid serial.

It's unique for any device. If you are looking for possibilities on how to get/use a unique device id you should read here.

For a solution involving reflection without requiring a permission see this answer.

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1922-1' for key 'IDX_STOCK_PRODUCT'

I also encountered this problem. I found after changing the table storage engine from MyISAM to Innodb, problem solved .

sql delete statement where date is greater than 30 days

You could also set between two dates:

Delete From tblAudit
WHERE Date_dat < DATEADD(day, -360, GETDATE())
GO
Delete From tblAudit
WHERE Date_dat > DATEADD(day, -60, GETDATE())
GO

Shell command to tar directory excluding certain files/folders

old question with many answers, but I found that none were quite clear enough for me, so I would like to add my try.

if you have the following structure

/home/ftp/mysite/

with following file/folders

/home/ftp/mysite/file1
/home/ftp/mysite/file2
/home/ftp/mysite/file3
/home/ftp/mysite/folder1
/home/ftp/mysite/folder2
/home/ftp/mysite/folder3

so, you want to make a tar file that contain everyting inside /home/ftp/mysite (to move the site to a new server), but file3 is just junk, and everything in folder3 is also not needed, so we will skip those two.

we use the format

tar -czvf <name of tar file> <what to tar> <any excludes>

where the c = create, z = zip, and v = verbose (you can see the files as they are entered, usefull to make sure none of the files you exclude are being added). and f= file.

so, my command would look like this

cd /home/ftp/
tar -czvf mysite.tar.gz mysite --exclude='file3' --exclude='folder3'

note the files/folders excluded are relatively to the root of your tar (I have tried full path here relative to / but I can not make that work).

hope this will help someone (and me next time I google it)

How to get the containing form of an input?

If using jQuery and have a handle to any form element, you need to get(0) the element before using .form

var my_form = $('input[name=first_name]').get(0).form;

Opening Android Settings programmatically

open android location setting programmatically using alert dialog

AlertDialog.Builder alertDialog = new AlertDialog.Builder(YourActivity.this);
alertDialog.setTitle("Enable Location");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent);
      }
});
alertDialog.show();

How do I set a variable to the output of a command in Bash?

In addition to backticks `command`, command substitution can be done with $(command) or "$(command)", which I find easier to read, and allows for nesting.

OUTPUT=$(ls -1)
echo "${OUTPUT}"

MULTILINE=$(ls \
   -1)
echo "${MULTILINE}"

Quoting (") does matter to preserve multi-line variable values; it is optional on the right-hand side of an assignment, as word splitting is not performed, so OUTPUT=$(ls -1) would work fine.

undefined reference to `std::ios_base::Init::Init()'

You can resolve this in several ways:

  • Use g++ in stead of gcc: g++ -g -o MatSim MatSim.cpp
  • Add -lstdc++: gcc -g -o MatSim MatSim.cpp -lstdc++
  • Replace <string.h> by <string>

This is a linker problem, not a compiler issue. The same problem is covered in the question iostream linker error – it explains what is going on.

Calling a JavaScript function returned from an Ajax response

PHP side code Name of file class.sendCode.php

<?php
class  sendCode{ 

function __construct($dateini,$datefin) {

            echo $this->printCode($dateini,$datefin);
        }

    function printCode($dateini,$datefin){

        $code =" alert ('code Coming from AJAX {$this->dateini} and {$this->datefin}');";
//Insert all the code you want to execute, 
//only javascript or Jquery code , dont incluce <script> tags
            return $code ;
    }
}
new sendCode($_POST['dateini'],$_POST['datefin']);

Now from your Html page you must trigger the ajax function to send the data.

....  <script src="http://code.jquery.com/jquery-1.9.1.js"></script> ....
Date begin: <input type="text" id="startdate"><br>
Date end : <input type="text" id="enddate"><br>
<input type="button" value="validate'" onclick="triggerAjax()"/>

Now at our local script.js we will define the ajax

function triggerAjax() {
    $.ajax({
            type: "POST",
            url: 'class.sendCode.php',
            dataType: "HTML",
            data : {

                dateini : $('#startdate').val(),
                datefin : $('#enddate').val()},

                  success: function(data){
                      $.globalEval(data);
// here is where the magic is made by executing the data that comes from
// the php class.  That is our javascript code to be executed
                  }


        });
}

How to redirect stderr to null in cmd.exe

Your DOS command 2> nul

Read page Using command redirection operators. Besides the "2>" construct mentioned by Tanuki Software, it lists some other useful combinations.

Pretty printing XML with javascript

This my version, maybe usefull for others, using String builder Saw that someone had the same piece of code.

    public String FormatXml(String xml, String tab)
    {
        var sb = new StringBuilder();
        int indent = 0;
        // find all elements
        foreach (string node in Regex.Split(xml,@">\s*<"))
        {
            // if at end, lower indent
            if (Regex.IsMatch(node, @"^\/\w")) indent--;
            sb.AppendLine(String.Format("{0}<{1}>", string.Concat(Enumerable.Repeat(tab, indent).ToArray()), node));
            // if at start, increase indent
            if (Regex.IsMatch(node, @"^<?\w[^>]*[^\/]$")) indent++;
        }
        // correct first < and last > from the output
        String result = sb.ToString().Substring(1);
        return result.Remove(result.Length - Environment.NewLine.Length-1);
    }

Why doesn't logcat show anything in my Android?

Set the same date and time in your android phone and in your laptop.

I had a similar problem of logs not showing, and when I set the correct date in the phone I started seeing the logs (I restarted the phone and the hour was completely wrong!).

PHP date() with timezone?

U can just add, timezone difference to unix timestamp. Example for Moscow (UTC+3)

echo date('d.m.Y H:i:s', time() + 3 * 60 * 60);

How do I check if a Sql server string is null or empty

Select              
Coalesce(NullIf(listing.OfferText, ''), NullIf(company.OfferText, ''), '') As Offer_Text,         
from tbl_directorylisting listing  
 Inner Join tbl_companymaster company            
  On listing.company_id= company.company_id

Remove directory from remote repository after adding them to .gitignore

If you're working from PowerShell, try the following as a single command.

PS MyRepo> git filter-branch --force --index-filter
>> "git rm --cached --ignore-unmatch -r .\\\path\\\to\\\directory"
>> --prune-empty --tag-name-filter cat -- --all

Then, git push --force --all.

Documentation: https://git-scm.com/docs/git-filter-branch

How does inline Javascript (in HTML) work?

The best way to answer your question is to see it in action.

<a id="test" onclick="alert('test')"> test </a> ?

In the js

var test = document.getElementById('test');
console.log( test.onclick ); 

As you see in the console, if you're using chrome it prints an anonymous function with the event object passed in, although it's a little different in IE.

function onclick(event) {
   alert('test')
}

I agree with some of your points about inline event handlers. Yes they are easy to write, but i don't agree with your point about having to change code in multiple places, if you structure your code well, you shouldn't need to do this.

startsWith() and endsWith() functions in PHP

Many of the previous answers will work just as well. However, this is possibly as short as you can make it and have it do what you desire. You just state that you'd like it to 'return true'. So I've included solutions that returns boolean true/false and the textual true/false.

// boolean true/false
function startsWith($haystack, $needle)
{
    return strpos($haystack, $needle) === 0 ? 1 : 0;
}

function endsWith($haystack, $needle)
{
    return stripos($haystack, $needle) === 0 ? 1 : 0;
}


// textual true/false
function startsWith($haystack, $needle)
{
    return strpos($haystack, $needle) === 0 ? 'true' : 'false';
}

function endsWith($haystack, $needle)
{
    return stripos($haystack, $needle) === 0 ? 'true' : 'false';
}

Can't concatenate 2 arrays in PHP

Both will have a key of 0, and that method of combining the arrays will collapse duplicates. Try using array_merge() instead.

$arr1 = array('foo'); // Same as array(0 => 'foo')
$arr2 = array('bar'); // Same as array(0 => 'bar')

// Will contain array('foo', 'bar');
$combined = array_merge($arr1, $arr2);

If the elements in your array used different keys, the + operator would be more appropriate.

$arr1 = array('one' => 'foo');
$arr2 = array('two' => 'bar');

// Will contain array('one' => 'foo', 'two' => 'bar');
$combined = $arr1 + $arr2;

Edit: Added a code snippet to clarify

Lowercase and Uppercase with jQuery

Try this:

var jIsHasKids = $('#chkIsHasKids').attr('checked');
jIsHasKids = jIsHasKids.toString().toLowerCase();
//OR
jIsHasKids = jIsHasKids.val().toLowerCase();

Possible duplicate with: How do I use jQuery to ignore case when selecting

start MySQL server from command line on Mac OS Lion

I like the aliases too ... however, I've had issues with MySQLCOM for start ... it fails silently ... My workaround is akin to the others ... ~/.bash_aliases

alias mysqlstart='sudo /usr/local/mysql/support-files/mysql.server start'
alias mysqlstop='sudo /usr/local/mysql/support-files/mysql.server stop' 

Provide password to ssh command inside bash script, Without the usage of public keys and Expect

Install sshpass, then launch the command:

sshpass -p "yourpassword" ssh -o StrictHostKeyChecking=no yourusername@hostname

How to filter Android logcat by application?

On Linux/Un*X/Cygwin you can get list of all tags in project (with appended :V after each) with this command (split because readability):

$ git grep 'String\s\+TAG\s*=\s*' |  \
  perl -ne 's/.*String\s+TAG\s*=\s*"?([^".]+).*;.*/$1:V/g && print ' | \
  sort | xargs
AccelerometerListener:V ADNList:V Ashared:V AudioDialog:V BitmapUtils:V # ...

It covers tags defined both ways of defining tags:

private static final String TAG = "AudioDialog";
private static final String TAG = SipProfileDb.class.getSimpleName();

And then just use it for adb logcat.

How to select only the records with the highest date in LINQ

If you want the whole record,here is a lambda way:

var q = _context
             .lasttraces
             .GroupBy(s => s.AccountId)
             .Select(s => s.OrderByDescending(x => x.Date).FirstOrDefault());

Get string character by index - Java

CharAt function not working

Edittext.setText(YourString.toCharArray(),0,1);

This code working fine

forEach() in React JSX does not output any HTML

You need to pass an array of element to jsx. The problem is that forEach does not return anything (i.e it returns undefined). So it's better to use map because map returns an array:

class QuestionSet extends Component {
render(){ 
    <div className="container">
       <h1>{this.props.question.text}</h1>
       {this.props.question.answers.map((answer, i) => {     
           console.log("Entered");                 
           // Return the element. Also pass key     
           return (<Answer key={answer} answer={answer} />) 
        })}
}

export default QuestionSet;

How to draw a rounded Rectangle on HTML Canvas?

I started with @jhoff's solution, but rewrote it to use width/height parameters, and using arcTo makes it quite a bit more terse:

CanvasRenderingContext2D.prototype.roundRect = function (x, y, w, h, r) {
  if (w < 2 * r) r = w / 2;
  if (h < 2 * r) r = h / 2;
  this.beginPath();
  this.moveTo(x+r, y);
  this.arcTo(x+w, y,   x+w, y+h, r);
  this.arcTo(x+w, y+h, x,   y+h, r);
  this.arcTo(x,   y+h, x,   y,   r);
  this.arcTo(x,   y,   x+w, y,   r);
  this.closePath();
  return this;
}

Also returning the context so you can chain a little. E.g.:

ctx.roundRect(35, 10, 225, 110, 20).stroke(); //or .fill() for a filled rect

does linux shell support list data structure?

For make a list, simply do that

colors=(red orange white "light gray")

Technically is an array, but - of course - it has all list features.
Even python list are implemented with array

How do you find all subclasses of a given class in Java?

This is not possible to do using only the built-in Java Reflections API.

A project exists that does the necessary scanning and indexing of your classpath so you can get access this information...

Reflections

A Java runtime metadata analysis, in the spirit of Scannotations

Reflections scans your classpath, indexes the metadata, allows you to query it on runtime and may save and collect that information for many modules within your project.

Using Reflections you can query your metadata for:

  • get all subtypes of some type
  • get all types annotated with some annotation
  • get all types annotated with some annotation, including annotation parameters matching
  • get all methods annotated with some

(disclaimer: I have not used it, but the project's description seems to be an exact fit for your needs.)

Convert object of any type to JObject with Json.NET

This will work:

var cycles = cycleSource.AllCycles();

var settings = new JsonSerializerSettings
{
    ContractResolver = new CamelCasePropertyNamesContractResolver()
};

var vm = new JArray();

foreach (var cycle in cycles)
{
    var cycleJson = JObject.FromObject(cycle);
    // extend cycleJson ......
    vm.Add(cycleJson);
}

return vm;

remove / reset inherited css from an element

Only set the relevant / important CSS properties.

Example (only change the attributes which may cause your div to look completely different):

background: #FFF;
border: none;
color: #000;
display: block;
font: initial;
height: auto;
letter-spacing: normal;
line-height: normal;
margin: 0;
padding: 0;
text-transform: none;
visibility: visible;
width: auto;
word-spacing: normal;
z-index: auto;

Choose a very specific selector, such as div#donttouchme, <div id="donttouchme"></div>. Additionally, you can add `!important before every semicolon in the declaration. Your customers are deliberately trying to mess up your lay-out when this option fails.

In PowerShell, how do I define a function in a file and call it from the PowerShell commandline?

. "$PSScriptRoot\MyFunctions.ps1" MyA1Func

Availalbe starting in v3, before that see How can I get the file system location of a PowerShell script?. It is VERY common.

P.S. I don't subscribe to the 'everything is a module' rule. My scripts are used by other developers out of GIT, so I don't like to put stuff in specific a place or modify system environment variables before my script will run. It's just a script (or two, or three).

node.js, socket.io with SSL

Depending on your needs, you could allow both secure and unsecure connections and still only use one Socket.io instance.

You simply have to instanciate two servers, one for HTTP and one for HTTPS, then attach those servers to the Socket.io instance.

Server side :

// needed to read certificates from disk
const fs          = require( "fs"    );

// Servers with and without SSL
const http        = require( "http"  )
const https       = require( "https" );
const httpPort    = 3333;
const httpsPort   = 3334;
const httpServer  = http.createServer();
const httpsServer = https.createServer({
    "key" : fs.readFileSync( "yourcert.key" ),
    "cert": fs.readFileSync( "yourcert.crt" ),
    "ca"  : fs.readFileSync( "yourca.crt"   )
});
httpServer.listen( httpPort, function() {
    console.log(  `Listening HTTP on ${httpPort}` );
});
httpsServer.listen( httpsPort, function() {
    console.log(  `Listening HTTPS on ${httpsPort}` );
});

// Socket.io
const ioServer = require( "socket.io" );
const io       = new ioServer();
io.attach( httpServer  );
io.attach( httpsServer );

io.on( "connection", function( socket ) {

    console.log( "user connected" );
    // ... your code

});

Client side :

var url    = "//example.com:" + ( window.location.protocol == "https:" ? "3334" : "3333" );
var socket = io( url, {
    // set to false only if you use self-signed certificate !
    "rejectUnauthorized": true
});
socket.on( "connect", function( e ) {
    console.log( "connect", e );
});

If your NodeJS server is different from your Web server, you will maybe need to set some CORS headers. So in the server side, replace:

const httpServer  = http.createServer();
const httpsServer = https.createServer({
    "key" : fs.readFileSync( "yourcert.key" ),
    "cert": fs.readFileSync( "yourcert.crt" ),
    "ca"  : fs.readFileSync( "yourca.crt"   )
});

With:

const CORS_fn = (req, res) => {
    res.setHeader( "Access-Control-Allow-Origin"     , "*"    );
    res.setHeader( "Access-Control-Allow-Credentials", "true" );
    res.setHeader( "Access-Control-Allow-Methods"    , "*"    );
    res.setHeader( "Access-Control-Allow-Headers"    , "*"    );
    if ( req.method === "OPTIONS" ) {
        res.writeHead(200);
        res.end();
        return;
    }
};
const httpServer  = http.createServer( CORS_fn );
const httpsServer = https.createServer({
        "key" : fs.readFileSync( "yourcert.key" ),
        "cert": fs.readFileSync( "yourcert.crt" ),
        "ca"  : fs.readFileSync( "yourca.crt"   )
}, CORS_fn );

And of course add/remove headers and set the values of the headers according to your needs.

CSS height 100% percent not working

I would say you have two options:

  1. to get all parent divs styled with 100% height (including body and html)

  2. to use absolute positioning for one of the parent divs (for example #content) and then all child divs set to height 100%

How do I create an .exe for a Java program?

The Java Service Wrapper might help you, depending on your requirements.

Upload a file to Amazon S3 with NodeJS

I found the following to be a working solution::

npm install aws-sdk


Once you've installed the aws-sdk , use the following code replacing values with your where needed.

var AWS = require('aws-sdk');
var fs =  require('fs');

var s3 = new AWS.S3();

// Bucket names must be unique across all S3 users

var myBucket = 'njera';

var myKey = 'jpeg';
//for text file
//fs.readFile('demo.txt', function (err, data) {
//for Video file
//fs.readFile('demo.avi', function (err, data) {
//for image file                
fs.readFile('demo.jpg', function (err, data) {
  if (err) { throw err; }



     params = {Bucket: myBucket, Key: myKey, Body: data };

     s3.putObject(params, function(err, data) {

         if (err) {

             console.log(err)

         } else {

             console.log("Successfully uploaded data to myBucket/myKey");

         }

      });

});

I found the complete tutorial on the subject here in case you're looking for references ::


How to upload files (text/image/video) in amazon s3 using node.js

How to remove certain characters from a string in C++?

Here's yet another alternative:

template<typename T>
void Remove( std::basic_string<T> & Str, const T * CharsToRemove )
{
    std::basic_string<T>::size_type pos = 0;
    while (( pos = Str.find_first_of( CharsToRemove, pos )) != std::basic_string<T>::npos )
    {
        Str.erase( pos, 1 ); 
    }
}

std::string a ("(555) 555-5555");
Remove( a, "()-");

Works with std::string and std::wstring

What is the difference between a hash join and a merge join (Oracle RDBMS )?

A "sort merge" join is performed by sorting the two data sets to be joined according to the join keys and then merging them together. The merge is very cheap, but the sort can be prohibitively expensive especially if the sort spills to disk. The cost of the sort can be lowered if one of the data sets can be accessed in sorted order via an index, although accessing a high proportion of blocks of a table via an index scan can also be very expensive in comparison to a full table scan.

A hash join is performed by hashing one data set into memory based on join columns and reading the other one and probing the hash table for matches. The hash join is very low cost when the hash table can be held entirely in memory, with the total cost amounting to very little more than the cost of reading the data sets. The cost rises if the hash table has to be spilled to disk in a one-pass sort, and rises considerably for a multipass sort.

(In pre-10g, outer joins from a large to a small table were problematic performance-wise, as the optimiser could not resolve the need to access the smaller table first for a hash join, but the larger table first for an outer join. Consequently hash joins were not available in this situation).

The cost of a hash join can be reduced by partitioning both tables on the join key(s). This allows the optimiser to infer that rows from a partition in one table will only find a match in a particular partition of the other table, and for tables having n partitions the hash join is executed as n independent hash joins. This has the following effects:

  1. The size of each hash table is reduced, hence reducing the maximum amount of memory required and potentially removing the need for the operation to require temporary disk space.
  2. For parallel query operations the amount of inter-process messaging is vastly reduced, reducing CPU usage and improving performance, as each hash join can be performed by one pair of PQ processes.
  3. For non-parallel query operations the memory requirement is reduced by a factor of n, and the first rows are projected from the query earlier.

You should note that hash joins can only be used for equi-joins, but merge joins are more flexible.

In general, if you are joining large amounts of data in an equi-join then a hash join is going to be a better bet.

This topic is very well covered in the documentation.

http://download.oracle.com/docs/cd/B28359_01/server.111/b28274/optimops.htm#i51523

12.1 docs: https://docs.oracle.com/database/121/TGSQL/tgsql_join.htm

Sorting list based on values from another list

I actually came here looking to sort a list by a list where the values matched.

list_a = ['foo', 'bar', 'baz']
list_b = ['baz', 'bar', 'foo']
sorted(list_b, key=lambda x: list_a.index(x))
# ['foo', 'bar', 'baz']

android adb turn on wifi via adb

No need to edit any database directly, there is a command for it :)

svc wifi [enable|disable]

What is the difference between const int*, const int * const, and int const *?

It's simple but tricky. Please note that we can swap the const qualifier with any data type (int, char, float, etc.).

Let's see the below examples.


const int *p ==> *p is read-only [p is a pointer to a constant integer]

int const *p ==> *p is read-only [p is a pointer to a constant integer]


int *p const ==> Wrong Statement. Compiler throws a syntax error.

int *const p ==> p is read-only [p is a constant pointer to an integer]. As pointer p here is read-only, the declaration and definition should be in same place.


const int *p const ==> Wrong Statement. Compiler throws a syntax error.

const int const *p ==> *p is read-only

const int *const p1 ==> *p and p are read-only [p is a constant pointer to a constant integer]. As pointer p here is read-only, the declaration and definition should be in same place.


int const *p const ==> Wrong Statement. Compiler throws a syntax error.

int const int *p ==> Wrong Statement. Compiler throws a syntax error.

int const const *p ==> *p is read-only and is equivalent to int const *p

int const *const p ==> *p and p are read-only [p is a constant pointer to a constant integer]. As pointer p here is read-only, the declaration and definition should be in same place.

How to "fadeOut" & "remove" a div in jQuery?

.fadeOut('slow', this.remove);

How can I edit a .jar file?

A jar file is a zip archive. You can extract it using 7zip (a great simple tool to open archives). You can also change its extension to zip and use whatever to unzip the file.

Now you have your class file. There is no easy way to edit class file, because class files are binaries (you won't find source code in there. maybe some strings, but not java code). To edit your class file you can use a tool like classeditor.

You have all the strings your class is using hard-coded in the class file. So if the only thing you would like to change is some strings you can do it without using classeditor.

Cell color changing in Excel using C#

Note: This assumes that you will declare constants for row and column indexes named COLUMN_HEADING_ROW, FIRST_COL, and LAST_COL, and that _xlSheet is the name of the ExcelSheet (using Microsoft.Interop.Excel)

First, define the range:

var columnHeadingsRange = _xlSheet.Range[
    _xlSheet.Cells[COLUMN_HEADING_ROW, FIRST_COL],
    _xlSheet.Cells[COLUMN_HEADING_ROW, LAST_COL]];

Then, set the background color of that range:

columnHeadingsRange.Interior.Color = XlRgbColor.rgbSkyBlue;

Finally, set the font color:

columnHeadingsRange.Font.Color = XlRgbColor.rgbWhite;

And here's the code combined:

var columnHeadingsRange = _xlSheet.Range[
    _xlSheet.Cells[COLUMN_HEADING_ROW, FIRST_COL],
    _xlSheet.Cells[COLUMN_HEADING_ROW, LAST_COL]];

columnHeadingsRange.Interior.Color = XlRgbColor.rgbSkyBlue;

columnHeadingsRange.Font.Color = XlRgbColor.rgbWhite;

string encoding and decoding?

You can't decode a unicode, and you can't encode a str. Try doing it the other way around.

How do I pass a class as a parameter in Java?

I am not sure what you are trying to accomplish, but you may want to consider that passing a class may not be what you really need to be doing. In many cases, dealing with Class like this is easily encapsulated within a factory pattern of some type and the use of that is done through an interface. here's one of dozens of articles on that pattern: http://today.java.net/pub/a/today/2005/03/09/factory.html

using a class within a factory can be accomplished in a variety of ways, most notably by having a config file that contains the name of the class that implements the required interface. Then the factory can find that class from within the class path and construct it as an object of the specified interface.

Get hostname of current request in node.js Express

You can use the os Module:

var os = require("os");
os.hostname();

See http://nodejs.org/docs/latest/api/os.html#os_os_hostname

Caveats:

  1. if you can work with the IP address -- Machines may have several Network Cards and unless you specify it node will listen on all of them, so you don't know on which NIC the request came in, before it comes in.

  2. Hostname is a DNS matter -- Don't forget that several DNS aliases can point to the same machine.

How to initialize an array in Java?

You cannot initialize an array like that. In addition to what others have suggested, you can do :

data[0] = 10;
data[1] = 20;
...
data[9] = 91;

Is it possible to set transparency in CSS3 box-shadow?

I suppose rgba() would work here. After all, browser support for both box-shadow and rgba() is roughly the same.

/* 50% black box shadow */
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);

_x000D_
_x000D_
div {_x000D_
    width: 200px;_x000D_
    height: 50px;_x000D_
    line-height: 50px;_x000D_
    text-align: center;_x000D_
    color: white;_x000D_
    background-color: red;_x000D_
    margin: 10px;_x000D_
}_x000D_
_x000D_
div.a {_x000D_
  box-shadow: 10px 10px 10px #000;_x000D_
}_x000D_
_x000D_
div.b {_x000D_
  box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);_x000D_
}
_x000D_
<div class="a">100% black shadow</div>_x000D_
<div class="b">50% black shadow</div>
_x000D_
_x000D_
_x000D_

LIKE operator in LINQ

You can also use the EF function tested in .net5

public async Task<IEnumerable<District>> SearchDistrict(string query, int stateId)
        {
            return await _dbContext
                .Districts
                .Include(s => s.State)
                .Where(s => s.StateId == stateId && EF.Functions.Like(s.Name, "$%{query}%"))
                .AsNoTracking()
                .ToListAsync();
        }

What's the difference between xsd:include and xsd:import?

I'm interested in this as well. The only explanation I've found is that xsd:include is used for intra-namespace inclusions, while xsd:import is for inter-namespace inclusion.

Remove portion of a string after a certain character

How about using explode:

$input = 'Posted On April 6th By Some Dude';
$result = explode(' By',$input);
return $result[0];

Advantages:

How to set a value for a span using jQuery

Syntax:

$(selector).text() returns the text content.

$(selector).text(content) sets the text content.

$(selector).text(function(index, curContent)) sets text content using a function.

kaynak: https://www.geeksforgeeks.org/jquery-change-the-text-of-a-span-element/

File.separator vs FileSystem.getSeparator() vs System.getProperty("file.separator")?

If your code doesn't cross filesystem boundaries, i.e. you're just working with one filesystem, then use java.io.File.separator.

This will, as explained, get you the default separator for your FS. As Bringer128 explained, System.getProperty("file.separator") can be overriden via command line options and isn't as type safe as java.io.File.separator.

The last one, java.nio.file.FileSystems.getDefault().getSeparator(); was introduced in Java 7, so you might as well ignore it for now if you want your code to be portable across older Java versions.

So, every one of these options is almost the same as others, but not quite. Choose one that suits your needs.

Outline effect to text

Edit: text-stroke is now fairly mature and implemented in most browsers. It is easier, sharper and more precise. If your browser audience can support it, you should now use text-stroke first, instead of text-shadow.


You can and should do this with just the text-shadow effect without any offsets:

.outline {
    color: #fff;
    text-shadow: #000 0px 0px 1px;
    -webkit-font-smoothing: antialiased;
}

Why? When you offset multiple shadow effects, you’ll begin to notice ungainly, jagged corners: Shadow effect offsets result in noticeable jagged corners.


Having text-shadow effects in just one position eliminates the offsets, meaning If you feel that’s too thin and would prefer a darker outline instead, no problem — you can repeat the same effect (keeping the same position and blur), several times. Like so:

text-shadow: #000 0px 0px 1px,   #000 0px 0px 1px,   #000 0px 0px 1px,
             #000 0px 0px 1px,   #000 0px 0px 1px,   #000 0px 0px 1px;

Here’s a sample of just one effect (top), and the same effect repeated 14 times (bottom):


Sample text rendered with text-shadow

Also note: Because the lines become so thin, it’s a very good idea to turn off sub-pixel rendering using
-webkit-font-smoothing: antialiased.

How to check if an Object is a Collection Type in Java?

Update: there are two possible scenarios here:

  1. You are determining if an object is a collection;

  2. You are determining if a class is a collection.

The solutions are slightly different but the principles are the same. You also need to define what exactly constitutes a "collection". Implementing either Collection or Map will cover the Java Collections.

Solution 1:

public static boolean isCollection(Object ob) {
  return ob instanceof Collection || ob instanceof Map;
}

Solution 2:

public static boolean isClassCollection(Class c) {
  return Collection.class.isAssignableFrom(c) || Map.class.isAssignableFrom(c);
}

(1) can also be implemented in terms of (2):

public static boolean isCollection(Object ob) {
  return ob != null && isClassCollection(ob.getClass());
}

I don't think the efficiency of either method will be greatly different from the other.

How to solve this java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream?

just put all apache comons jar and file upload jar in lib folder of tomcat

Setting CSS pseudo-class rules from JavaScript

A function to cope with the cross-browser stuff:

addCssRule = function(/* string */ selector, /* string */ rule) {
  if (document.styleSheets) {
    if (!document.styleSheets.length) {
      var head = document.getElementsByTagName('head')[0];
      head.appendChild(bc.createEl('style'));
    }

    var i = document.styleSheets.length-1;
    var ss = document.styleSheets[i];

    var l=0;
    if (ss.cssRules) {
      l = ss.cssRules.length;
    } else if (ss.rules) {
      // IE
      l = ss.rules.length;
    }

    if (ss.insertRule) {
      ss.insertRule(selector + ' {' + rule + '}', l);
    } else if (ss.addRule) {
      // IE
      ss.addRule(selector, rule, l);
    }
  }
};

Could not resolve all dependencies for configuration ':classpath'

I try to modify the repositories and import the cer to java, but both failed, then I upgrade my jdk version from 1.8.0_66 to 1.8.0_74, gradle build success.

exit application when click button - iOS

You can use exit method to quit an ios app :

exit(0);

You should say same alert message and ask him to quit

Another way is by using [[NSThread mainThread] exit]

However you should not do this way

According to Apple, your app should not terminate on its own. Since the user did not hit the Home button, any return to the Home screen gives the user the impression that your app crashed. This is confusing, non-standard behavior and should be avoided.

printf not printing on console

Apparently this is a known bug of Eclipse. This bug is resolved with the resolution of WONT-FIX. I have no idea why though. here is the link: Eclipse C Console Bug.

How to install python developer package?

For me none of the packages mentioned above did help.

I finally managed to install lxml after running:

sudo apt-get install python3.5-dev

Moving all files from one directory to another using Python

def copy_myfile_dirOne_to_dirSec(src, dest, ext): 

    if not os.path.exists(dest):    # if dest dir is not there then we create here
        os.makedirs(dest);
        
    for item in os.listdir(src):
        if item.endswith(ext):
            s = os.path.join(src, item);
            fd = open(s, 'r');
            data = fd.read();
            fd.close();
            
            fname = str(item); #just taking file name to make this name file is destination dir     
            
            d = os.path.join(dest, fname);
            fd = open(d, 'w');
            fd.write(data);
            fd.close();
    
    print("Files are copyed successfully")

How to compare arrays in C#?

You're comparing the object references, and they are not the same. You need to compare the array contents.

.NET2 solution

An option is iterating through the array elements and call Equals() for each element. Remember that you need to override the Equals() method for the array elements, if they are not the same object reference.

An alternative is using this generic method to compare two generic arrays:

static bool ArraysEqual<T>(T[] a1, T[] a2)
{
    if (ReferenceEquals(a1, a2))
        return true;

    if (a1 == null || a2 == null)
        return false;

    if (a1.Length != a2.Length)
        return false;

    var comparer = EqualityComparer<T>.Default;
    for (int i = 0; i < a1.Length; i++)
    {
        if (!comparer.Equals(a1[i], a2[i])) return false;
    }
    return true;
}

.NET 3.5 or higher solution

Or use SequenceEqual if Linq is available for you (.NET Framework >= 3.5)

jQuery delete all table rows except first

This works perfectly

$("#myTable tbody").children( 'tr:not(:first)' ).html("");

CURL alternative in Python

You can use HTTP Requests that are described in the Requests: HTTP for Humans user guide.

Update Query with INNER JOIN between tables in 2 different databases on 1 server

It is very simple to update using Inner join query in SQL .You can do it without using FROM clause. Here is an example :

    UPDATE customer_table c 

      INNER JOIN  
          employee_table e
          ON (c.city_id = e.city_id)  

    SET c.active = "Yes"

    WHERE c.city = "New york";

python dict to numpy structured array

I would prefer storing keys and values on separate arrays. This i often more practical. Structures of arrays are perfect replacement to array of structures. As most of the time you have to process only a subset of your data (in this cases keys or values, operation only with only one of the two arrays would be more efficient than operating with half of the two arrays together.

But in case this way is not possible, I would suggest to use arrays sorted by column instead of by row. In this way you would have the same benefit as having two arrays, but packed only in one.

import numpy as np
result = {0: 1.1181753789488595, 1: 0.5566080288678394, 2: 0.4718269778030734, 3: 0.48716683119447185, 4: 1.0, 5: 0.1395076201641266, 6: 0.20941558441558442}

names = 0
values = 1
array = np.empty(shape=(2, len(result)), dtype=float)
array[names] = result.keys()
array[values] = result.values()

But my favorite is this (simpler):

import numpy as np
result = {0: 1.1181753789488595, 1: 0.5566080288678394, 2: 0.4718269778030734, 3: 0.48716683119447185, 4: 1.0, 5: 0.1395076201641266, 6: 0.20941558441558442}

arrays = {'names': np.array(result.keys(), dtype=float),
          'values': np.array(result.values(), dtype=float)}

How to programmatically disable page scrolling with jQuery

For folks who have centered layouts (via margin:0 auto;), here's a mash-up of the position:fixed solution along with @tfe's proposed solution.

Use this solution if you're experiencing page-snapping (due to the scrollbar showing/hiding).

// lock scroll position, but retain settings for later
var scrollPosition = [
    window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
    window.pageYOffset || document.documentElement.scrollTop  || document.body.scrollTop
];
var $html = $('html'); // bow to the demon known as MSIE(v7)
$html.addClass('modal-noscroll');
$html.data('scroll-position', scrollPosition);
$html.data('margin-top', $html.css('margin-top'));
$html.css('margin-top', -1 * scrollPosition[1]);

…combined with…

// un-lock scroll position
var $html = $('html').removeClass('modal-noscroll');
var scrollPosition = $html.data('scroll-position');
var marginTop = $html.data('margin-top');
$html.css('margin-top', marginTop);
window.scrollTo(scrollPosition[0], scrollPosition[1])

…and finally, the CSS for .modal-noscroll

.modal-noscroll
{
    position: fixed;
    overflow-y: scroll;
    width: 100%;
}

I would venture to say this is more of a proper fix than any of the other solutions out there, but I haven't tested it that thoroughly yet… :P


Edit: please note that I have no clue how badly this might perform (read: blow up) on a touch device.

Why do you have to link the math library in C?

Because of ridiculous historical practice that nobody is willing to fix. Consolidating all of the functions required by C and POSIX into a single library file would not only avoid this question getting asked over and over, but would also save a significant amount of time and memory when dynamic linking, since each .so file linked requires the filesystem operations to locate and find it, and a few pages for its static variables, relocations, etc.

An implementation where all functions are in one library and the -lm, -lpthread, -lrt, etc. options are all no-ops (or link to empty .a files) is perfectly POSIX conformant and certainly preferable.

Note: I'm talking about POSIX because C itself does not specify anything about how the compiler is invoked. Thus you can just treat gcc -std=c99 -lm as the implementation-specific way the compiler must be invoked for conformant behavior.

How exactly do you configure httpOnlyCookies in ASP.NET?

If you want to do it in code, use the System.Web.HttpCookie.HttpOnly property.

This is directly from the MSDN docs:

// Create a new HttpCookie.
HttpCookie myHttpCookie = new HttpCookie("LastVisit", DateTime.Now.ToString());
// By default, the HttpOnly property is set to false 
// unless specified otherwise in configuration.
myHttpCookie.Name = "MyHttpCookie";
Response.AppendCookie(myHttpCookie);
// Show the name of the cookie.
Response.Write(myHttpCookie.Name);
// Create an HttpOnly cookie.
HttpCookie myHttpOnlyCookie = new HttpCookie("LastVisit", DateTime.Now.ToString());
// Setting the HttpOnly value to true, makes
// this cookie accessible only to ASP.NET.
myHttpOnlyCookie.HttpOnly = true;
myHttpOnlyCookie.Name = "MyHttpOnlyCookie";
Response.AppendCookie(myHttpOnlyCookie);
// Show the name of the HttpOnly cookie.
Response.Write(myHttpOnlyCookie.Name);

Doing it in code allows you to selectively choose which cookies are HttpOnly and which are not.

How to install Selenium WebDriver on Mac OS

Install

If you use homebrew (which I recommend), you can install selenium using:

brew install selenium-server-standalone

Running

updated -port port_number

To run selenium, do: selenium-server -port 4444

For more options: selenium-server -help

Is there a 'box-shadow-color' property?

You could use a CSS pre-processor to do your skinning. With Sass you can do something similar to this:

_theme1.scss:

$theme-primary-color: #a00;
$theme-secondary-color: #d00;
// etc.

_theme2.scss:

$theme-primary-color: #666;
$theme-secondary-color: #ccc;
// etc.

styles.scss:

// import whichever theme you want to use
@import 'theme2';

-webkit-box-shadow: inset 0px 0px 2px $theme-primary-color;
-moz-box-shadow: inset 0px 0px 2px $theme-primary-color;

If it's not site wide theming but class based theming you need, then you can do this: http://codepen.io/jjenzz/pen/EaAzo

How to show the "Are you sure you want to navigate away from this page?" when changes committed?

This is an easy way to present the message if any data is input into the form, and not to show the message if the form is submitted:

$(function () {
    $("input, textarea, select").on("input change", function() {
        window.onbeforeunload = window.onbeforeunload || function (e) {
            return "You have unsaved changes.  Do you want to leave this page and lose your changes?";
        };
    });
    $("form").on("submit", function() {
        window.onbeforeunload = null;
    });
})

AngularJS - Trigger when radio button is selected

i prefer to use ng-value with ng-if, [ng-value] will handle trigger changes

<input type="radio"  name="isStudent" ng-model="isStudent" ng-value="true" />

//to show and hide input by removing it from the DOM, that's make me secure from malicious data

<input type="text" ng-if="isStudent"  name="textForStudent" ng-model="job">

Convert object to JSON string in C#

I have used Newtonsoft JSON.NET (Documentation) It allows you to create a class / object, populate the fields, and serialize as JSON.

public class ReturnData 
{
    public int totalCount { get; set; }
    public List<ExceptionReport> reports { get; set; }  
}

public class ExceptionReport
{
    public int reportId { get; set; }
    public string message { get; set; }  
}


string json = JsonConvert.SerializeObject(myReturnData);

How to plot time series in python

Convert your x-axis data from text to datetime.datetime, use datetime.strptime:

>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
 datetime.datetime(2012, 5, 31, 19, 0)

This is an example of how to plot data once you have an array of datetimes:

import matplotlib.pyplot as plt
import datetime
import numpy as np

x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)

plt.plot(x,y)
plt.show()

enter image description here

Preventing multiple clicks on button

disable the button on click, enable it after the operation completes

$(document).ready(function () {
    $("#btn").on("click", function() {
        $(this).attr("disabled", "disabled");
        doWork(); //this method contains your logic
    });
});

function doWork() {
    alert("doing work");
    //actually this function will do something and when processing is done the button is enabled by removing the 'disabled' attribute
    //I use setTimeout so you can see the button can only be clicked once, and can't be clicked again while work is being done
    setTimeout('$("#btn").removeAttr("disabled")', 1500);
}

working example

How can I access localhost from another computer in the same network?

localhost is a special hostname that almost always resolves to 127.0.0.1. If you ask someone else to connect to http://localhost they'll be connecting to their computer instead or yours.

To share your web server with someone else you'll need to find your IP address or your hostname and provide that to them instead. On windows you can find this with ipconfig /all on a command line.

You'll also need to make sure any firewalls you may have configured allow traffic on port 80 to connect to the WAMP server.

Dynamically load a JavaScript file

I know my answer is bit late for this question, but, here is a great article in www.html5rocks.com - Deep dive into the murky waters of script loading .

In that article it is concluded that in regards of browser support, the best way to dynamically load JavaScript file without blocking content rendering is the following way:

Considering you've four scripts named script1.js, script2.js, script3.js, script4.js then you can do it with applying async = false:

[
  'script1.js',
  'script2.js',
  'script3.js',
  'script4.js'
].forEach(function(src) {
  var script = document.createElement('script');
  script.src = src;
  script.async = false;
  document.head.appendChild(script);
});

Now, Spec says: Download together, execute in order as soon as all download.

Firefox < 3.6, Opera says: I have no idea what this “async” thing is, but it just so happens I execute scripts added via JS in the order they’re added.

Safari 5.0 says: I understand “async”, but don’t understand setting it to “false” with JS. I’ll execute your scripts as soon as they land, in whatever order.

IE < 10 says: No idea about “async”, but there is a workaround using “onreadystatechange”.

Everything else says: I’m your friend, we’re going to do this by the book.

Now, the full code with IE < 10 workaround:

var scripts = [
  'script1.js',
  'script2.js',
  'script3.js',
  'script4.js'
];
var src;
var script;
var pendingScripts = [];
var firstScript = document.scripts[0];

// Watch scripts load in IE
function stateChange() {
  // Execute as many scripts in order as we can
  var pendingScript;
  while (pendingScripts[0] && pendingScripts[0].readyState == 'loaded') {
    pendingScript = pendingScripts.shift();
    // avoid future loading events from this script (eg, if src changes)
    pendingScript.onreadystatechange = null;
    // can't just appendChild, old IE bug if element isn't closed
    firstScript.parentNode.insertBefore(pendingScript, firstScript);
  }
}

// loop through our script urls
while (src = scripts.shift()) {
  if ('async' in firstScript) { // modern browsers
    script = document.createElement('script');
    script.async = false;
    script.src = src;
    document.head.appendChild(script);
  }
  else if (firstScript.readyState) { // IE<10
    // create a script and add it to our todo pile
    script = document.createElement('script');
    pendingScripts.push(script);
    // listen for state changes
    script.onreadystatechange = stateChange;
    // must set src AFTER adding onreadystatechange listener
    // else we’ll miss the loaded event for cached scripts
    script.src = src;
  }
  else { // fall back to defer
    document.write('<script src="' + src + '" defer></'+'script>');
  }
}

A few tricks and minification later, it’s 362 bytes

!function(e,t,r){function n(){for(;d[0]&&"loaded"==d[0][f];)c=d.shift(),c[o]=!i.parentNode.insertBefore(c,i)}for(var s,a,c,d=[],i=e.scripts[0],o="onreadystatechange",f="readyState";s=r.shift();)a=e.createElement(t),"async"in i?(a.async=!1,e.head.appendChild(a)):i[f]?(d.push(a),a[o]=n):e.write("<"+t+' src="'+s+'" defer></'+t+">"),a.src=s}(document,"script",[
  "//other-domain.com/1.js",
  "2.js"
])

Round number to nearest integer

This one is tricky, to be honest. There are many simple ways to do this nevertheless. Using math.ceil(), round(), and math.floor(), you can get a integer by using for example:

n = int(round(n))

If before we used this function n = 5.23, we would get returned 5. If you wanted to round to different place values, you could use this function:

def Round(n,k):
  point = '%0.' + str(k) + 'f'
  if k == 0:
    return int(point % n)
  else:
    return float(point % n)

If we used n (5.23) again, round it to the nearest tenth, and print the answer to the console, our code would be:

Round(5.23,1)

Which would return 5.2. Finally, if you wanted to round something to the nearest, let's say, 1.2, you can use the code:

def Round(n,k):
    return k * round(n/k)

If we wanted n to be rounded to 1.2, our code would be:

print(Round(n,1.2))

and our result:

4.8

Thank you! If you have any questions, please add a comment. :) (Happy Holidays!)

VBA Print to PDF and Save with Automatic File Name

Hopefully this is self explanatory enough. Use the comments in the code to help understand what is happening. Pass a single cell to this function. The value of that cell will be the base file name. If the cell contains "AwesomeData" then we will try and create a file in the current users desktop called AwesomeData.pdf. If that already exists then try AwesomeData2.pdf and so on. In your code you could just replace the lines filename = Application..... with filename = GetFileName(Range("A1"))

Function GetFileName(rngNamedCell As Range) As String
    Dim strSaveDirectory As String: strSaveDirectory = ""
    Dim strFileName As String: strFileName = ""
    Dim strTestPath As String: strTestPath = ""
    Dim strFileBaseName As String: strFileBaseName = ""
    Dim strFilePath As String: strFilePath = ""
    Dim intFileCounterIndex As Integer: intFileCounterIndex = 1

    ' Get the users desktop directory.
    strSaveDirectory = Environ("USERPROFILE") & "\Desktop\"
    Debug.Print "Saving to: " & strSaveDirectory

    ' Base file name
    strFileBaseName = Trim(rngNamedCell.Value)
    Debug.Print "File Name will contain: " & strFileBaseName

    ' Loop until we find a free file number
    Do
        If intFileCounterIndex > 1 Then
            ' Build test path base on current counter exists.
            strTestPath = strSaveDirectory & strFileBaseName & Trim(Str(intFileCounterIndex)) & ".pdf"
        Else
            ' Build test path base just on base name to see if it exists.
            strTestPath = strSaveDirectory & strFileBaseName & ".pdf"
        End If

        If (Dir(strTestPath) = "") Then
            ' This file path does not currently exist. Use that.
            strFileName = strTestPath
        Else
            ' Increase the counter as we have not found a free file yet.
            intFileCounterIndex = intFileCounterIndex + 1
        End If

    Loop Until strFileName <> ""

    ' Found useable filename
    Debug.Print "Free file name: " & strFileName
    GetFileName = strFileName

End Function

The debug lines will help you figure out what is happening if you need to step through the code. Remove them as you see fit. I went a little crazy with the variables but it was to make this as clear as possible.

In Action

My cell O1 contained the string "FileName" without the quotes. Used this sub to call my function and it saved a file.

Sub Testing()
    Dim filename As String: filename = GetFileName(Range("o1"))

    ActiveWorkbook.Worksheets("Sheet1").Range("A1:N24").ExportAsFixedFormat Type:=xlTypePDF, _
                                              filename:=filename, _
                                              Quality:=xlQualityStandard, _
                                              IncludeDocProperties:=True, _
                                              IgnorePrintAreas:=False, _
                                              OpenAfterPublish:=False
End Sub

Where is your code located in reference to everything else? Perhaps you need to make a module if you have not already and move your existing code into there.

How to create/make rounded corner buttons in WPF?

Well the best way to get round corners fast and with standard animation is to create a copy of the control template with Blend. Once you get a copy set the corner radius on the Grid tag and you should be able to have your control with full animation functionality and applyable to any button control. look this is the code:

<ControlTemplate x:Key="ButtonControlTemplate" TargetType="Button">        
    <Grid x:Name="RootGrid" Background="{TemplateBinding Background}"
          CornerRadius="8,8,8,8">
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="CommonStates">
                <VisualState x:Name="Normal">
                    <Storyboard>
                        <PointerUpThemeAnimation Storyboard.TargetName="RootGrid" />
                    </Storyboard>
                </VisualState>
                <VisualState x:Name="PointerOver">
                    <Storyboard>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="RootGrid" Storyboard.TargetProperty="Background">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonBackgroundPointerOver}" />
                        </ObjectAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="BorderBrush">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonBorderBrushPressed}" />
                        </ObjectAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonForegroundPointerOver}" />
                        </ObjectAnimationUsingKeyFrames>
                        <PointerUpThemeAnimation Storyboard.TargetName="RootGrid" />
                    </Storyboard>
                </VisualState>
                <VisualState x:Name="Pressed">
                    <Storyboard>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="RootGrid" Storyboard.TargetProperty="Background">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonBackgroundPressed}" />
                        </ObjectAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="BorderBrush">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonBorderBrushPressed}" />
                        </ObjectAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonForegroundPressed}" />
                        </ObjectAnimationUsingKeyFrames>
                        <PointerDownThemeAnimation Storyboard.TargetName="RootGrid" />
                    </Storyboard>
                </VisualState>
                <VisualState x:Name="Disabled">
                    <Storyboard>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="RootGrid" Storyboard.TargetProperty="Background">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonBackgroundDisabled}" />
                        </ObjectAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="BorderBrush">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonBorderBrushDisabled}" />
                        </ObjectAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonForegroundDisabled}" />
                        </ObjectAnimationUsingKeyFrames>
                    </Storyboard>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
        <!--<Border CornerRadius="8,8,8,8"
                        Background="#002060"
                        BorderBrush="Red"
                        BorderThickness="2">-->
            <ContentPresenter x:Name="ContentPresenter"
                              BorderBrush="{TemplateBinding BorderBrush}"
                              BorderThickness="{TemplateBinding BorderThickness}"
                              Content="{TemplateBinding Content}"
                              ContentTransitions="{TemplateBinding ContentTransitions}"
                              ContentTemplate="{TemplateBinding ContentTemplate}"
                              Padding="{TemplateBinding Padding}"
                              HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
                              VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"
                              AutomationProperties.AccessibilityView="Raw"/>
        <!--</Border>-->
    </Grid>        
</ControlTemplate>

I also edited the VisualState="PointerOver" specifically at Storyboard.TargetName="BorderBrush", because its ThemeResource get squared corners whenever PointerOver triggers.

Then you should be able to apply it to your control style like this:

<Style TargetType="ContentControl" x:Key="ButtonLoginStyle"
       BasedOn="{StaticResource CommonLoginStyleMobile}">
    <Setter Property="FontWeight" Value="Bold"/>
    <Setter Property="Background" Value="#002060"/>
    <Setter Property="Template" Value="{StaticResource ButtonControlTemplate}"/>        
</Style>

So you can apply your styles to any Button.

Setting Column width in Apache POI

Unfortunately there is only the function setColumnWidth(int columnIndex, int width) from class Sheet; in which width is a number of characters in the standard font (first font in the workbook) if your fonts are changing you cannot use it. There is explained how to calculate the width in function of a font size. The formula is:

width = Truncate([{NumOfVisibleChar} * {MaxDigitWidth} + {5PixelPadding}] / {MaxDigitWidth}*256) / 256

You can always use autoSizeColumn(int column, boolean useMergedCells) after inputting the data in your Sheet.

how to parse a "dd/mm/yyyy" or "dd-mm-yyyy" or "dd-mmm-yyyy" formatted date string using JavaScript or jQuery

Try this:

 function GetDateFormat(controlName) {
        if ($('#' + controlName).val() != "") {      
            var d1 = Date.parse($('#' + controlName).val().toString().replace(/([0-9]+)\/([0-9]+)/,'$2/$1'));
            if (d1 == null) {
                alert('Date Invalid.');
                $('#' + controlName).val("");
            }
                var array = d1.toString('dd-MMM-yyyy');
                $('#' + controlName).val(array);
        }
    }

The RegExp replace .replace(/([0-9]+)\/([0-9]+)/,'$2/$1') change day/month position.

The pipe ' ' could not be found angular2 custom pipe

I have created a module for pipes in the same directory where my pipes are present

import { NgModule } from '@angular/core';
///import pipe...
import { Base64ToImage, TruncateString} from './'  

   @NgModule({
        imports: [],
        declarations: [Base64ToImage, TruncateString],
        exports: [Base64ToImage, TruncateString]
    })

    export class SharedPipeModule { }   

Now import that module in app.module:

import {SharedPipeModule} from './pipe/shared.pipe.module'
 @NgModule({
     imports: [
    ...
    , PipeModule.forRoot()
    ....
  ],

Now it can be used by importing the same in the nested module

How can one grab a stack trace in C?

For Windows, CaptureStackBackTrace() is also an option, which requires less preparation code on the user's end than StackWalk64() does. (Also, for a similar scenario I had, CaptureStackBackTrace() ended up working better (more reliably) than StackWalk64().)

Get month name from number

This is not so helpful if you need to just know the month name for a given number (1 - 12), as the current day doesn't matter.

calendar.month_name[i]

or

calendar.month_abbr[i]

are more useful here.

Here is an example:

import calendar

for month_idx in range(1, 13):
    print (calendar.month_name[month_idx])
    print (calendar.month_abbr[month_idx])
    print ("")

Sample output:

January
Jan

February
Feb

March
Mar

...

Automatically enter SSH password with script

In linux/ubuntu

ssh username@server_ip_address -p port_number

Press enter and then enter your server password

if you are not a root user then add sudo in starting of command

How do I make an image smaller with CSS?

You can try this:

-ms-transform: scale(width,height); /* IE 9 */
-webkit-transform: scale(width,height); /* Safari */
transform: scale(width, height);

Example: image "grows" 1.3 times

-ms-transform: scale(1.3,1.3); /* IE 9 */
-webkit-transform: scale(1.3,1.3); /* Safari */
transform: scale(1.3,1.3);

How to best display in Terminal a MySQL SELECT returning too many fields?

The default pager is stdout. The stdout has the column limitation, so the output would be wrapped. You could set other tools as pager to format the output. There are two methods. One is to limit the column, the other is to processed it in vim.

The first method:

?  ~  echo $COLUMNS
179

mysql> nopager
PAGER set to stdout
mysql> pager cut -c -179
PAGER set to 'cut -c -179'
mysql> select * from db;
+-----------+------------+------------+-------------+-------------+-------------+-------------+-------------+-----------+------------+-----------------+------------+------------+-
| Host      | Db         | User       | Select_priv | Insert_priv | Update_priv | Delete_priv | Create_priv | Drop_priv | Grant_priv | References_priv | Index_priv | Alter_priv |
+-----------+------------+------------+-------------+-------------+-------------+-------------+-------------+-----------+------------+-----------------+------------+------------+-
| %         | test       |            | Y           | Y           | Y           | Y           | Y           | Y         | N          | Y               | Y          | Y          |
| %         | test\_%    |            | Y           | Y           | Y           | Y           | Y           | Y         | N          | Y               | Y          | Y          |
| localhost | phpmyadmin | phpmyadmin | Y           | Y           | Y           | Y           | Y           | Y         | N          | Y               | Y          | Y          |
| localhost | it         | it         | Y           | Y           | Y           | Y           | Y           | Y         | N          | Y               | Y          | Y          |
+-----------+------------+------------+-------------+-------------+-------------+-------------+-------------+-----------+------------+-----------------+------------+------------+-
4 rows in set (0.00 sec)

mysql>

The output is not complete. The content fits to your screen.

The second one:

Set vim mode to nowrap in your .vimrc

?  ~  tail ~/.vimrc

" no-wrap for myslq cli
set nowrap

mysql> pager vim -
PAGER set to 'vim -'
mysql> select * from db;
    Vim: Reading from stdin...
+-----------+------------+------------+-------------+-------------+----------
| Host      | Db         | User       | Select_priv | Insert_priv | Update_pr
+-----------+------------+------------+-------------+-------------+----------
| %         | test       |            | Y           | Y           | Y
| %         | test\_%    |            | Y           | Y           | Y
| localhost | phpmyadmin | phpmyadmin | Y           | Y           | Y
| localhost | it         | it         | Y           | Y           | Y
+-----------+------------+------------+-------------+-------------+----------
~
~
~

Python: How exactly can you take a string, split it, reverse it and join it back together again?

Not fitting 100% to this particular question but if you want to split from the back you can do it like this:

theStringInQuestion[::-1].split('/', 1)[1][::-1]

This code splits once at symbol '/' from behind.

setting multiple column using one update

UPDATE some_table 
   SET this_column=x, that_column=y 
   WHERE something LIKE 'them'

Plot 3D data in R

Adding to the solutions of others, I'd like to suggest using the plotly package for R, as this has worked well for me.

Below, I'm using the reformatted dataset suggested above, from xyz-tripplets to axis vectors x and y and a matrix z:

x <- 1:5/10
y <- 1:5
z <- x %o% y
z <- z + .2*z*runif(25) - .1*z

library(plotly)
plot_ly(x=x,y=y,z=z, type="surface")

enter image description here

The rendered surface can be rotated and scaled using the mouse. This works fairly well in RStudio.

You can also try it with the built-in volcano dataset from R:

plot_ly(z=volcano, type="surface")

enter image description here

Function in JavaScript that can be called only once

If you want to be able to reuse the function in the future then this works well based on ed Hopp's code above (I realize that the original question didn't call for this extra feature!):

   var something = (function() {
   var executed = false;              
    return function(value) {
        // if an argument is not present then
        if(arguments.length == 0) {               
            if (!executed) {
            executed = true;
            //Do stuff here only once unless reset
            console.log("Hello World!");
            }
            else return;

        } else {
            // otherwise allow the function to fire again
            executed = value;
            return;
        }       
    }
})();

something();//Hello World!
something();
something();
console.log("Reset"); //Reset
something(false);
something();//Hello World!
something();
something();

The output look like:

Hello World!
Reset
Hello World!

Get the size of a 2D array

Expanding on what Mark Elliot said earlier, the easiest way to get the size of a 2D array given that each array in the array of arrays is of the same size is:

array.length * array[0].length

What killed my process and why?

We have had recurring problems under Linux at a customer site (Red Hat, I think), with OOMKiller (out-of-memory killer) killing both our principle application (i.e. the reason the server exists) and it's data base processes.

In each case OOMKiller simply decided that the processes were using to much resources... the machine wasn't even about to fail for lack of resources. Neither the application nor it's database has problems with memory leaks (or any other resource leak).

I am not a Linux expert, but I rather gathered it's algorithm for deciding when to kill something and what to kill is complex. Also, I was told (I can't speak as to the accuracy of this) that OOMKiller is baked into the Kernel and you can't simply not run it.

The FastCGI process exited unexpectedly

If you are installing PHP 7.1.14 on windows server 2008 rc2 Enterprise, only thing worked for me is to install microsoft Visual C++ 2015 Redistributable Update 3 from https://www.microsoft.com/en-us/download/details.aspx?id=53587

How do I seed a random class to avoid getting duplicate random values

Bit late, but the implementation used by System.Random is Environment.TickCount:

public Random() 
  : this(Environment.TickCount) {
}

This avoids having to cast DateTime.UtcNow.Ticks from a long, which is risky anyway as it doesn't represent ticks since system start, but "the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001 (0:00:00 UTC on January 1, 0001, in the Gregorian calendar)".

Was looking for a good integer seed for the TestApi's StringFactory.GenerateRandomString

Like Operator in Entity Framework?

This is an old post now, but for anyone looking for the answer, this link should help. Go to this answer if you are already using EF 6.2.x. To this answer if you're using EF Core 2.x

Short version:

SqlFunctions.PatIndex method - returns the starting position of the first occurrence of a pattern in a specified expression, or zeros if the pattern is not found, on all valid text and character data types

Namespace: System.Data.Objects.SqlClient Assembly: System.Data.Entity (in System.Data.Entity.dll)

A bit of an explanation also appears in this forum thread.

Undefined behavior and sequence points

C++17 (N4659) includes a proposal Refining Expression Evaluation Order for Idiomatic C++ which defines a stricter order of expression evaluation.

In particular, the following sentence

8.18 Assignment and compound assignment operators:
....

In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression. The right operand is sequenced before the left operand.

together with the following clarification

An expression X is said to be sequenced before an expression Y if every value computation and every side effect associated with the expression X is sequenced before every value computation and every side effect associated with the expression Y.

make several cases of previously undefined behavior valid, including the one in question:

a[++i] = i;

However several other similar cases still lead to undefined behavior.

In N4140:

i = i++ + 1; // the behavior is undefined

But in N4659

i = i++ + 1; // the value of i is incremented
i = i++ + i; // the behavior is undefined

Of course, using a C++17 compliant compiler does not necessarily mean that one should start writing such expressions.

How to access random item in list?

I needed to more item instead of just one. So, I wrote this:

public static TList GetSelectedRandom<TList>(this TList list, int count)
       where TList : IList, new()
{
    var r = new Random();
    var rList = new TList();
    while (count > 0 && list.Count > 0)
    {
        var n = r.Next(0, list.Count);
        var e = list[n];
        rList.Add(e);
        list.RemoveAt(n);
        count--;
    }

    return rList;
}

With this, you can get elements how many you want as randomly like this:

var _allItems = new List<TModel>()
{
    // ...
    // ...
    // ...
}

var randomItemList = _allItems.GetSelectedRandom(10); 

Mask output of `The following objects are masked from....:` after calling attach() function

If you look at the down arrow in environment tab. The attached file can appear multiple times. You may need to highlight and run detach(filename) several times until all cases are gone then attach(newfilename) should have no output message.

attached files under environment tab

Getting the object's property name

To get the property of the object or the "array key" or "array index" depending on what your native language is..... Use the Object.keys() method.

Important, this is only compatible with "Modern browsers":

So if your object is called, myObject...

var c = 0;
for(c in myObject) {
    console.log(Object.keys(myObject[c]));
}

Walla! This will definitely work in the latest firefox and ie11 and chrome...

Here is some documentation at MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

OnClick vs OnClientClick for an asp:CheckBox?

One solution is with JQuery:

$(document).ready(
    function () {
        $('#mycheckboxId').click(function () {
               // here the action or function to call
        });
    }
);

How can I solve a connection pool problem between ASP.NET and SQL Server?

You can try that too, for solve timeout problem:

If you didn't add httpRuntime to your webconfig, add that in <system.web> tag

<sytem.web>
     <httpRuntime maxRequestLength="20000" executionTimeout="999999"/>
</system.web>

and

Modify your connection string like this;

 <add name="connstring" connectionString="Data Source=DSourceName;Initial Catalog=DBName;Integrated Security=True;Max Pool Size=50000;Pooling=True;" providerName="System.Data.SqlClient" />

At last use

    try
    {...} 
    catch
    {...} 
    finaly
    {
     connection.close();
    }

How to enable/disable bluetooth programmatically in android

Here is a bit more robust way of doing this, also handling the return values of enable()\disable() methods:

public static boolean setBluetooth(boolean enable) {
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    boolean isEnabled = bluetoothAdapter.isEnabled();
    if (enable && !isEnabled) {
        return bluetoothAdapter.enable(); 
    }
    else if(!enable && isEnabled) {
        return bluetoothAdapter.disable();
    }
    // No need to change bluetooth state
    return true;
}

And add the following permissions into your manifest file:

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

But remember these important points:

This is an asynchronous call: it will return immediately, and clients should listen for ACTION_STATE_CHANGED to be notified of subsequent adapter state changes. If this call returns true, then the adapter state will immediately transition from STATE_OFF to STATE_TURNING_ON, and some time later transition to either STATE_OFF or STATE_ON. If this call returns false then there was an immediate problem that will prevent the adapter from being turned on - such as Airplane mode, or the adapter is already turned on.

UPDATE:

Ok, so how to implement bluetooth listener?:

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();

        if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
            final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
                                                 BluetoothAdapter.ERROR);
            switch (state) {
            case BluetoothAdapter.STATE_OFF:
                // Bluetooth has been turned off;
                break;
            case BluetoothAdapter.STATE_TURNING_OFF:
                // Bluetooth is turning off;
                break;
            case BluetoothAdapter.STATE_ON:
                // Bluetooth is on
                break;
            case BluetoothAdapter.STATE_TURNING_ON:
                // Bluetooth is turning on
                break;
            }
        }
    }
};

And how to register/unregister the receiver? (In your Activity class)

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // ...

    // Register for broadcasts on BluetoothAdapter state change
    IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    registerReceiver(mReceiver, filter);
}

@Override
public void onStop() {
    super.onStop();

     // ...

    // Unregister broadcast listeners
    unregisterReceiver(mReceiver);
}

How to view instagram profile picture in full-size?

replace "150x150" with 720x720 and remove /vp/ from the link.it should work.

Compute elapsed time

Try something like this (FIDDLE)

// record start time
var startTime = new Date();

...

// later record end time
var endTime = new Date();

// time difference in ms
var timeDiff = endTime - startTime;

// strip the ms
timeDiff /= 1000;

// get seconds (Original had 'round' which incorrectly counts 0:28, 0:29, 1:30 ... 1:59, 1:0)
var seconds = Math.round(timeDiff % 60);

// remove seconds from the date
timeDiff = Math.floor(timeDiff / 60);

// get minutes
var minutes = Math.round(timeDiff % 60);

// remove minutes from the date
timeDiff = Math.floor(timeDiff / 60);

// get hours
var hours = Math.round(timeDiff % 24);

// remove hours from the date
timeDiff = Math.floor(timeDiff / 24);

// the rest of timeDiff is number of days
var days = timeDiff ;

Array to Hash Ruby

This is what I was looking for when googling this:

[{a: 1}, {b: 2}].reduce({}) { |h, v| h.merge v } => {:a=>1, :b=>2}

Convert Linq Query Result to Dictionary

Use namespace

using System.Collections.Specialized;

Make instance of DataContext Class

LinqToSqlDataContext dc = new LinqToSqlDataContext();

Use

OrderedDictionary dict = dc.TableName.ToDictionary(d => d.key, d => d.value);

In order to retrieve the values use namespace

   using System.Collections;

ICollection keyCollections = dict.Keys;
ICOllection valueCollections = dict.Values;

String[] myKeys = new String[dict.Count];
String[] myValues = new String[dict.Count];

keyCollections.CopyTo(myKeys,0);
valueCollections.CopyTo(myValues,0);

for(int i=0; i<dict.Count; i++)
{
Console.WriteLine("Key: " + myKeys[i] + "Value: " + myValues[i]);
}
Console.ReadKey();

How do you resize a form to fit its content automatically?

I User this Code in my project, Useful for me.

    private void Form1_Resize(object sender, EventArgs e)
    {
        int w = MainPanel.Width; // you can use form.width when you don't use panels

        w = (w - 120)/4; // 120 because set 15px for each side of panels
                         // and put panels in FlowLayoutPanel
                         // 4 because i have 4 panel boxes
        panel1.Width = w;
        panel2.Width = w;
        panel3.Width = w;
        panel4.Width = w;
    }

enter image description here

Remove border radius from Select tag in bootstrap 3

In addition to border-radius: 0, add -webkit-appearance: none;.

How to position a CSS triangle using ::after?

You can set triangle with position see this code for reference

.top-left-corner {
    width: 0px;
    height: 0px;
    border-top: 0px solid transparent;
    border-bottom: 55px solid transparent;
    border-left: 55px solid #289006;
    position: absolute;
    left: 0px;
    top: 0px;
}

TextView bold via xml file?

Example:

use: android:textStyle="bold"

 <TextView
    android:id="@+id/txtVelocidade"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/txtlatitude"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="34dp"
    android:textStyle="bold"
    android:text="Aguardando GPS"
    android:textAppearance="?android:attr/textAppearanceLarge" />

React Native: Getting the position of an element

You can use onLayout to get the width, height, and relative-to-parent position of a component at the earliest moment that they're available:

<View
  onLayout={event => {
    const layout = event.nativeEvent.layout;
    console.log('height:', layout.height);
    console.log('width:', layout.width);
    console.log('x:', layout.x);
    console.log('y:', layout.y);
  }}
>

Compared to using .measure() as shown in the accepted answer, this has the advantage that you'll never have to fiddle around deferring your .measure() calls with setTimeout to make sure that the measurements are available, but the disadvantage that it doesn't give you offsets relative to the entire page, only ones relative to the element's parent.

Find and Replace string in all files recursive using grep and sed

grep -rl $oldstring . | xargs sed -i "s/$oldstring/$newstring/g"

An error occurred while updating the entries. See the inner exception for details

Click "View Detail..." a window will open where you can expand the "Inner Exception" my guess is that when you try to delete the record there is a reference constraint violation. The inner exception will give you more information on that so you can modify your code to remove any references prior to deleting the record.

enter image description here

How to retrieve form values from HTTPPOST, dictionary or?

Simply, you can use FormCollection like:

[HttpPost] 
public ActionResult SubmitAction(FormCollection collection)
{
     // Get Post Params Here
 string var1 = collection["var1"];
}

You can also use a class, that is mapped with Form values, and asp.net mvc engine automagically fills it:

//Defined in another file
class MyForm
{
  public string var1 { get; set; }
}

[HttpPost]
public ActionResult SubmitAction(MyForm form)
{      
  string var1 = form1.Var1;
}

Git - How to close commit editor?

Better yet, configure the editor to something you are comfortable with (gedit as an example):

git config --global core.editor "gedit"

You can read the current configuration like this:

git config core.editor

You can also add the commit message from the command line.

git commit -m "blablabla"

and the editor will not be opened in the first place.

How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?

Tip for RxJS

I'll often have member variables of type Observable<string>, and I won't be initializing it until ngOnInit (using Angular). The compiler then assumes it to be uninitialized becasue it isn't 'definitely assigned in the constructor' - and the compiler is never going to understand ngOnInit.

You can use the ! assertion operator on the definition to avoid the error:

favoriteColor!: Observable<string>;

An uninitialized observable can cause all kinds of runtime pain with errors like 'you must provide a stream but you provided null'. The ! is fine if you definitely know it's going to be set in something like ngOnInit, but there may be cases where the value is set in some other less deterministic way.

So an alternative I'll sometimes use is :

public loaded$: Observable<boolean> = uninitialized('loaded');

Where uninitialized is defined globally somewhere as:

export const uninitialized = (name: string) => throwError(name + ' not initialized');

Then if you ever use this stream without it being defined it will immediately throw a runtime error.

Regex to replace multiple spaces with a single space

Comprehensive unencrypted answer for newbies et al.

This is for all of the dummies like me who test the scripts written by some of you guys which do not work.

The following 3 examples are the steps I took to remove special characters AND extra spaces on the following 3 websites (all of which work perfectly) {1. EtaVisa.com 2. EtaStatus.com 3. Tikun.com} so I know that these work perfectly.

We have chained these together with over 50 at a time and NO problems.

// This removed special characters + 0-9 and allows for just letters (upper and LOWER case)

function NoDoublesPls1()
{
var str=document.getElementById("NoDoubles1");
var regex=/[^a-z]/gi;
str.value=str.value.replace(regex ,"");
}

// This removed special characters and allows for just letters (upper and LOWER case) and 0-9 AND spaces

function NoDoublesPls2()
{
var str=document.getElementById("NoDoubles2");
var regex=/[^a-z 0-9]/gi;
str.value=str.value.replace(regex ,"");
}

// This removed special characters and allows for just letters (upper and LOWER case) and 0-9 AND spaces // The .replace(/\s\s+/g, " ") at the end removes excessive spaces // when I used single quotes, it did not work.

function NoDoublesPls3()
{    var str=document.getElementById("NoDoubles3");
var regex=/[^a-z 0-9]/gi;
str.value=str.value.replace(regex ,"") .replace(/\s\s+/g, " ");
}

::NEXT:: Save #3 as a .js // I called mine NoDoubles.js

::NEXT:: Include your JS into your page

 <script language="JavaScript" src="js/NoDoubles.js"></script>

Include this in your form field:: such as

<INPUT type="text" name="Name"
     onKeyUp="NoDoublesPls3()" onKeyDown="NoDoublesPls3()" id="NoDoubles3"/>

So that it looks like this

<INPUT type="text" name="Name" onKeyUp="NoDoublesPls3()" onKeyDown="NoDoublesPls3()" id="NoDoubles3"/>

This will remove special characters, allow for single spaces and remove extra spaces.

How to auto adjust the <div> height according to content in it?

Don't set height. Use min-height and max-height instead.

Git for Windows: .bashrc or equivalent configuration files for Git Bash shell

Create a .bashrc file under ~/.bashrc and away you go. Similarly for ~/.gitconfig.

~ is usually your C:\Users\<your user name> folder. Typing echo ~ in the Git Bash terminal will tell you what that folder is.

If you can't create the file (e.g. running Windows), run the below command:

copy > ~/.bashrc

The window will output an error message (command not found), but the file will be created and ready for you to edit.

How can I print variable and string on same line in Python?

use string format :

birth = 5.25487
print(f'''
{birth} 
''')

How to use google maps without api key

this simple code work 100% all you need is changing 'lat','long' for address to show

<iframe src="http://maps.google.com/maps?q=25.3076008,51.4803216&z=16&output=embed" height="450" width="600"></iframe>

jQuery Force set src attribute for iframe

Setting src attribute didn't work for me. The iframe didn't display the url.

What worked for me was:

window.open(url, "nameof_iframe");

Hope it helps someone.

Hidden Columns in jqGrid

This thread is pretty old I suppose, but in case anyone else stumbles across this question... I had to grab a value from the selected row of a table, but I didn't want to show the column that row was from. I used hideCol, but had the same problem as Andy where it looked messy. To fix it (call it a hack) I just re-set the width of the grid.

jQuery(document).ready(function() {

       jQuery("#ItemGrid").jqGrid({ 
                ..., 
                width: 700,
                ...
        }).hideCol('StoreId').setGridWidth(700)

Since my row widths are automatic, when I reset the width of the table it reset the column widths but excluded the hidden one, so they filled in the gap.

How can I create a two dimensional array in JavaScript?

Two dimensional arrays are created the same way single dimensional arrays are. And you access them like array[0][1].

var arr = [1, 2, [3, 4], 5];

alert (arr[2][1]); //alerts "4"

PersistenceContext EntityManager injection NullPointerException

If you have any NamedQueries in your entity classes, then check the stack trace for compilation errors. A malformed query which cannot be compiled can cause failure to load the persistence context.

Is it possible to use vh minus pixels in a CSS calc()?

It does work indeed. Issue was with my less compiler. It was compiled in to:

.container {
  min-height: calc(-51vh);
}

Fixed with the following code in less file:

.container {
  min-height: calc(~"100vh - 150px");
}

Thanks to this link: Less Aggressive Compilation with CSS3 calc

Purge Kafka Topic

Thomas' advice is great but unfortunately zkCli in old versions of Zookeeper (for example 3.3.6) do not seem to support rmr. For example compare the command line implementation in modern Zookeeper with version 3.3.

If you are faced with an old version of Zookeeper one solution is to use a client library such as zc.zk for Python. For people not familiar with Python you need to install it using pip or easy_install. Then start a Python shell (python) and you can do:

import zc.zk
zk = zc.zk.ZooKeeper('localhost:2181')
zk.delete_recursive('brokers/MyTopic') 

or even

zk.delete_recursive('brokers')

if you want to remove all the topics from Kafka.

How do I create a pause/wait function using Qt?

Since you're trying to "test some class code," I'd really recommend learning to use QTestLib. It provides a QTest namespace and a QtTest module that contain a number of useful functions and objects, including QSignalSpy that you can use to verify that certain signals are emitted.

Since you will eventually be integrating with a full GUI, using QTestLib and testing without sleeping or waiting will give you a more accurate test -- one that better represents the true usage patterns. But, should you choose not to go that route, you could use QTestLib::qSleep to do what you've requested.

Since you just need a pause between starting your pump and shutting it down, you could easily use a single shot timer:

class PumpTest: public QObject {
    Q_OBJECT
    Pump &pump;
public:
    PumpTest(Pump &pump):pump(pump) {};
public slots:
    void start() { pump.startpump(); }
    void stop() { pump.stoppump(); }
    void stopAndShutdown() {
        stop();
        QCoreApplication::exit(0);
    }
    void test() {
        start();
        QTimer::singleShot(1000, this, SLOT(stopAndShutdown));
    }
};

int main(int argc, char* argv[]) {
    QCoreApplication app(argc, argv);
    Pump p;
    PumpTest t(p);
    t.test();
    return app.exec();
}

But qSleep() would definitely be easier if all you're interested in is verifying a couple of things on the command line.

EDIT: Based on the comment, here's the required usage patterns.

First, you need to edit your .pro file to include qtestlib:

CONFIG += qtestlib

Second, you need to include the necessary files:

  • For the QTest namespace (which includes qSleep): #include <QTest>
  • For all the items in the QtTest module: #include <QtTest>. This is functionally equivalent to adding an include for each item that exists within the namespace.

C# generics syntax for multiple type parameter constraints

void foo<TOne, TTwo>() 
   where TOne : BaseOne
   where TTwo : BaseTwo

More info here:
http://msdn.microsoft.com/en-us/library/d5x73970.aspx

How to add text to an existing div with jquery

Very easy from My side:-

<html>
<head>
<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
    $(document).ready(function() {
        $("input").click(function() {
            $('<input type="text" name="name" value="value"/>').appendTo('#testdiv');
        });

    });
</script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <div id="testdiv"></div>
    <input type="button" value="Add" />
</body>
</html>

Easiest way to copy a single file from host to Vagrant guest?

Best way to copy file from local to vagrant, No need to write any code or any thing or any configuration changes. 1- First up the vagrant (vagrant up) 2- open cygwin 3- cygwin : go to your folder where is vagrantfile or from where you launch the vagrant 4- ssh vagrant 5- now it will work like a normal system.

How to change Navigation Bar color in iOS 7?

The behavior of tintColor for bars has changed in iOS 7.0. It no longer affects the bar's background.

From the documentation:

barTintColor Class Reference

The tint color to apply to the navigation bar background.

@property(nonatomic, retain) UIColor *barTintColor

Discussion
This color is made translucent by default unless you set the translucent property to NO.

Availability

Available in iOS 7.0 and later.

Declared In
UINavigationBar.h

Code

NSArray *ver = [[UIDevice currentDevice].systemVersion componentsSeparatedByString:@"."];
if ([[ver objectAtIndex:0] intValue] >= 7) {
    // iOS 7.0 or later   
    self.navigationController.navigationBar.barTintColor = [UIColor redColor];
    self.navigationController.navigationBar.translucent = NO;
}else {
    // iOS 6.1 or earlier
    self.navigationController.navigationBar.tintColor = [UIColor redColor];
}

We can also use this to check iOS Version as mention in iOS 7 UI Transition Guide

if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {
        // iOS 6.1 or earlier
        self.navigationController.navigationBar.tintColor = [UIColor redColor];
    } else {
        // iOS 7.0 or later     
        self.navigationController.navigationBar.barTintColor = [UIColor redColor];
        self.navigationController.navigationBar.translucent = NO;
    }

EDIT Using xib

enter image description here

TextView Marquee not working

These attributes must be included in the textview tag in order to allow scrolling.

Everything else is optional.

android:focusable="true"
android:focusableInTouchMode="true"
android:layout_width="fill_parent"
android:ellipsize="marquee"

Calling UserForm_Initialize() in a Module

SOLUTION After all this time, I managed to resolve the problem.

In Module: UserForms(Name).Userform_Initialize

This method works best to dynamically init the current UserForm

Percentage Height HTML 5/CSS

You need to set the height on the <html> and <body> elements as well; otherwise, they will only be large enough to fit the content. For example:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<title>Example of 100% width and height</title>_x000D_
<style>_x000D_
html, body { height: 100%; margin: 0; }_x000D_
div { height: 100%; width: 100%; background: red; }_x000D_
</style>_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

Unable to start debugging on the web server. Could not start ASP.NET debugging VS 2010, II7, Win 7 x64

I had the same problem. All the answers above did not work for me. The solution was to delete the bin and obj folder manually.

How to display the first few characters of a string in Python?

If you want first 2 letters and last 2 letters of a string then you can use the following code: name = "India" name[0:2]="In" names[-2:]="ia"

Maven "build path specifies execution environment J2SE-1.5", even though I changed it to 1.7

All of the answers above may work for the time being but whenever you run maven on the command line or Maven → Update project… the JDK will be reset, this was also the question as I understand it.

To fix this for good add the following code to your pom file. Remember to do a Maven → Update project… afterwards or mvn clean compile at the command line.

<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>

    </pluginManagement>
</build>

How to get the second column from command output?

#!/usr/bin/python
import sys 

col = int(sys.argv[1]) - 1

for line in sys.stdin:
    columns = line.split()

    try:
        print(columns[col])
    except IndexError:
        # ignore
        pass

Then, supposing you name the script as co, say, do something like this to get the sizes of files (the example assumes you're using Linux, but the script itself is OS-independent) :-

ls -lh | co 5

Maintaining href "open in new tab" with an onClick handler in React

The answer from @gunn is correct, target="_blank makes the link open in a new tab.

But this can be a security risk for you page; you can read about it here. There is a simple solution for that: adding rel="noopener noreferrer".

<a style={{display: "table-cell"}} href = "someLink" target = "_blank" 
rel = "noopener noreferrer">text</a>

Determine if two rectangles overlap each other?

Ask yourself the opposite question: How can I determine if two rectangles do not intersect at all? Obviously, a rectangle A completely to the left of rectangle B does not intersect. Also if A is completely to the right. And similarly if A is completely above B or completely below B. In any other case A and B intersect.

What follows may have bugs, but I am pretty confident about the algorithm:

struct Rectangle { int x; int y; int width; int height; };

bool is_left_of(Rectangle const & a, Rectangle const & b) {
   if (a.x + a.width <= b.x) return true;
   return false;
}
bool is_right_of(Rectangle const & a, Rectangle const & b) {
   return is_left_of(b, a);
}

bool not_intersect( Rectangle const & a, Rectangle const & b) {
   if (is_left_of(a, b)) return true;
   if (is_right_of(a, b)) return true;
   // Do the same for top/bottom...
 }

bool intersect(Rectangle const & a, Rectangle const & b) {
  return !not_intersect(a, b);
}

JSON encode MySQL results

Code:

$rows = array();

while($r = mysqli_fetch_array($result,MYSQL_ASSOC)) {

 $row_array['result'] = $r;

  array_push($rows,$row_array); // here we push every iteration to an array otherwise you will get only last iteration value
}

echo json_encode($rows);

Find an object in SQL Server (cross-database)

There is a schema called INFORMATION_SCHEMA schema which contains a set of views on tables from the SYS schema that you can query to get what you want.

A major upside of the INFORMATION_SCHEMA is that the object names are very query friendly and user readable. The downside of the INFORMATION_SCHEMA is that you have to write one query for each type of object.

The Sys schema may seem a little cryptic initially, but it has all the same information (and more) in a single spot.

You'd start with a table called SysObjects (each database has one) that has the names of all objects and their types.

One could search in a database as follows:

Select [name] as ObjectName, Type as ObjectType
From Sys.Objects
Where 1=1
    and [Name] like '%YourObjectName%'

Now, if you wanted to restrict this to only search for tables and stored procs, you would do

Select [name] as ObjectName, Type as ObjectType
From Sys.Objects
Where 1=1
    and [Name] like '%YourObjectName%'
    and Type in ('U', 'P')

If you look up object types, you will find a whole list for views, triggers, etc.

Now, if you want to search for this in each database, you will have to iterate through the databases. You can do one of the following:

If you want to search through each database without any clauses, then use the sp_MSforeachdb as shown in an answer here.

If you only want to search specific databases, use the "USE DBName" and then search command.

You will benefit greatly from having it parameterized in that case. Note that the name of the database you are searching in will have to be replaced in each query (DatabaseOne, DatabaseTwo...). Check this out:

Declare @ObjectName VarChar (100)

Set @ObjectName = '%Customer%'

Select 'DatabaseOne' as DatabaseName, [name] as ObjectName, Type as ObjectType
From DatabaseOne.Sys.Objects
Where 1=1
    and [Name] like @ObjectName
    and Type in ('U', 'P')

UNION ALL

Select 'DatabaseTwo' as DatabaseName, [name] as ObjectName, Type as ObjectType
From DatabaseTwo.Sys.Objects
Where 1=1
    and [Name] like @ObjectName
    and Type in ('U', 'P')

UNION ALL

Select 'DatabaseThree' as DatabaseName, [name] as ObjectName, Type as ObjectType
From DatabaseThree.Sys.Objects
Where 1=1
    and [Name] like @ObjectName
    and Type in ('U', 'P')

java.util.regex - importance of Pattern.compile()?

Compile parses the regular expression and builds an in-memory representation. The overhead to compile is significant compared to a match. If you're using a pattern repeatedly it will gain some performance to cache the compiled pattern.

Paritition array into N chunks with Numpy

How about this? Here you split the array using the length you want to have.

a = np.random.randint(0,10,[4,4])

a
Out[27]: 
array([[1, 5, 8, 7],
       [3, 2, 4, 0],
       [7, 7, 6, 2],
       [7, 4, 3, 0]])

a[0:2,:]
Out[28]: 
array([[1, 5, 8, 7],
       [3, 2, 4, 0]])

a[2:4,:]
Out[29]: 
array([[7, 7, 6, 2],
       [7, 4, 3, 0]])

Running PowerShell as another user, and launching a script

Try adding the RunAs option to your Start-Process

Start-Process powershell.exe -Credential $Credential -Verb RunAs -ArgumentList ("-file $args")

How can I map "insert='false' update='false'" on a composite-id key-property which is also used in a one-to-many FK?

"Dino TW" has provided the link to the comment Hibernate Mapping Exception : Repeated column in mapping for entity which has the vital information.

The link hints to provide "inverse=true" in the set mapping, I tried it and it actually works. It is such a rare situation wherein a Set and Composite key come together. Make inverse=true, we leave the insert & update of the table with Composite key to be taken care by itself.

Below can be the required mapping,

<class name="com.example.CompanyEntity" table="COMPANY">
    <id name="id" column="COMPANY_ID"/>
    <set name="names" inverse="true" table="COMPANY_NAME" cascade="all-delete-orphan" fetch="join" batch-size="1" lazy="false">
        <key column="COMPANY_ID" not-null="true"/>
        <one-to-many entity-name="vendorName"/>
    </set>
</class>

How to split a string of space separated numbers into integers?

Just use strip() to remove empty spaces and apply explicit int conversion on the variable.

Ex:

a='1  ,  2, 4 ,6 '
f=[int(i.strip()) for i in a]

convert ArrayList<MyCustomClass> to JSONArray

Add to your gradle:

implementation 'com.squareup.retrofit2:converter-gson:2.3.0'

Convert ArrayList to JsonArray

JsonArray jsonElements = (JsonArray) new Gson().toJsonTree(itemsArrayList);

What is context in _.each(list, iterator, [context])?

The context lets you provide arguments at call-time, allowing easy customization of generic pre-built helper functions.

some examples:

// stock footage:
function addTo(x){ "use strict"; return x + this; }
function pluck(x){ "use strict"; return x[this]; }
function lt(x){ "use strict"; return x < this; }

// production:
var r = [1,2,3,4,5,6,7,8,9];
var words = "a man a plan a canal panama".split(" ");

// filtering numbers:
_.filter(r, lt, 5); // elements less than 5
_.filter(r, lt, 3); // elements less than 3

// add 100 to the elements:
_.map(r, addTo, 100);

// encode eggy peggy:
_.map(words, addTo, "egg").join(" ");

// get length of words:
_.map(words, pluck, "length"); 

// find words starting with "e" or sooner:
_.filter(words, lt, "e"); 

// find all words with 3 or more chars:
_.filter(words, pluck, 2); 

Even from the limited examples, you can see how powerful an "extra argument" can be for creating re-usable code. Instead of making a different callback function for each situation, you can usually adapt a low-level helper. The goal is to have your custom logic bundling a verb and two nouns, with minimal boilerplate.

Admittedly, arrow functions have eliminated a lot of the "code golf" advantages of generic pure functions, but the semantic and consistency advantages remain.

I always add "use strict" to helpers to provide native [].map() compatibility when passing primitives. Otherwise, they are coerced into objects, which usually still works, but it's faster and safer to be type-specific.

How do I add a linker or compile flag in a CMake file?

Try setting the variable CMAKE_CXX_FLAGS instead of CMAKE_C_FLAGS:

set (CMAKE_CXX_FLAGS "-fexceptions")

The variable CMAKE_C_FLAGS only affects the C compiler, but you are compiling C++ code.

Adding the flag to CMAKE_EXE_LINKER_FLAGS is redundant.

printf \t option

A tab is a tab. How many spaces it consumes is a display issue, and depends on the settings of your shell.

If you want to control the width of your data, then you could use the width sub-specifiers in the printf format string. Eg. :

printf("%5d", 2);

It's not a complete solution (if the value is longer than 5 characters, it will not be truncated), but might be ok for your needs.

If you want complete control, you'll probably have to implement it yourself.

Convert data.frame column format from character to factor

I've doing it with a function. In this case I will only transform character variables to factor:

for (i in 1:ncol(data)){
    if(is.character(data[,i])){
        data[,i]=factor(data[,i])
    }
}

Understanding __get__ and __set__ and Python descriptors

I tried (with minor changes as suggested) the code from Andrew Cooke's answer. (I am running python 2.7).

The code:

#!/usr/bin/env python
class Celsius:
    def __get__(self, instance, owner): return 9 * (instance.fahrenheit + 32) / 5.0
    def __set__(self, instance, value): instance.fahrenheit = 32 + 5 * value / 9.0

class Temperature:
    def __init__(self, initial_f): self.fahrenheit = initial_f
    celsius = Celsius()

if __name__ == "__main__":

    t = Temperature(212)
    print(t.celsius)
    t.celsius = 0
    print(t.fahrenheit)

The result:

C:\Users\gkuhn\Desktop>python test2.py
<__main__.Celsius instance at 0x02E95A80>
212

With Python prior to 3, make sure you subclass from object which will make the descriptor work correctly as the get magic does not work for old style classes.

.rar, .zip files MIME Type

The answers from freedompeace, Kiyarash and Sam Vloeberghs:

.rar    application/x-rar-compressed, application/octet-stream
.zip    application/zip, application/octet-stream, application/x-zip-compressed, multipart/x-zip

I would do a check on the file name too. Here is how you could check if the file is a RAR or ZIP file. I tested it by creating a quick command line application.

<?php

if (isRarOrZip($argv[1])) {
    echo 'It is probably a RAR or ZIP file.';
} else {
    echo 'It is probably not a RAR or ZIP file.';
}

function isRarOrZip($file) {
    // get the first 7 bytes
    $bytes = file_get_contents($file, FALSE, NULL, 0, 7);
    $ext = strtolower(substr($file, - 4));

    // RAR magic number: Rar!\x1A\x07\x00
    // http://en.wikipedia.org/wiki/RAR
    if ($ext == '.rar' and bin2hex($bytes) == '526172211a0700') {
        return TRUE;
    }

    // ZIP magic number: none, though PK\003\004, PK\005\006 (empty archive), 
    // or PK\007\008 (spanned archive) are common.
    // http://en.wikipedia.org/wiki/ZIP_(file_format)
    if ($ext == '.zip' and substr($bytes, 0, 2) == 'PK') {
        return TRUE;
    }

    return FALSE;
}

Notice that it still won't be 100% certain, but it is probably good enough.

$ rar.exe l somefile.zip
somefile.zip is not RAR archive

But even WinRAR detects non RAR files as SFX archives:

$ rar.exe l somefile.srr
SFX Volume somefile.srr

Handling the window closing event with WPF / MVVM Light Toolkit

Here is an answer according to the MVVM-pattern if you don't want to know about the Window (or any of its event) in the ViewModel.

public interface IClosing
{
    /// <summary>
    /// Executes when window is closing
    /// </summary>
    /// <returns>Whether the windows should be closed by the caller</returns>
    bool OnClosing();
}

In the ViewModel add the interface and implementation

public bool OnClosing()
{
    bool close = true;

    //Ask whether to save changes och cancel etc
    //close = false; //If you want to cancel close

    return close;
}

In the Window I add the Closing event. This code behind doesn't break the MVVM pattern. The View can know about the viewmodel!

void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    IClosing context = DataContext as IClosing;
    if (context != null)
    {
        e.Cancel = !context.OnClosing();
    }
}

How can I listen to the form submit event in javascript?

Based on your requirements you can also do the following without libraries like jQuery:

Add this to your head:

window.onload = function () {
    document.getElementById("frmSubmit").onsubmit = function onSubmit(form) {
        var isValid = true;
        //validate your elems here
        isValid = false;

        if (!isValid) {
            alert("Please check your fields!");
            return false;
        }
        else {
            //you are good to go
            return true;
        }
    }
}

And your form may still look something like:

    <form id="frmSubmit" action="/Submit">
        <input type="submit" value="Submit" />
    </form>

Creating a file only if it doesn't exist in Node.js

Todo this in a single system call you can use the fs-extra npm module. After this the file will have been created as well as the directory it is to be placed in.

const fs = require('fs-extra');
const file = '/tmp/this/path/does/not/exist/file.txt'
fs.ensureFile(file, err => {
    console.log(err) // => null
});

Another way is to use ensureFileSync which will do the same thing but synchronous.

const fs = require('fs-extra');
const file = '/tmp/this/path/does/not/exist/file.txt'
fs.ensureFileSync(file)

Is there a better way to refresh WebView?

Yes for some reason WebView.reload() causes a crash if it failed to load before (something to do with the way it handles history). This is the code I use to refresh my webview. I store the current url in self.url

# 1: Pause timeout and page loading

self.timeout.pause()
sleep(1)

# 2: Check for internet connection (Really lazy way)

while self.page().networkAccessManager().networkAccessible() == QNetworkAccessManager.NotAccessible: sleep(2)

# 3:Try again

if self.url == self.page().mainFrame().url():
    self.page().action(QWebPage.Reload)
    self.timeout.resume(60)

else:
    self.page().action(QWebPage.Stop)
    self.page().mainFrame().load(self.url)
    self.timeout.resume(30)

return False

Adding an .env file to React Project

4 steps

  1. npm install dotenv --save

  2. Next add the following line to your app.

    require('dotenv').config()

  3. Then create a .env file at the root directory of your application and add the variables to it.

// contents of .env 

REACT_APP_API_KEY = 'my-secret-api-key'
  1. Finally, add .env to your .gitignore file so that Git ignores it and it never ends up on GitHub.

If you are using create-react-app then you only need step 3 and 4 but keep in mind variable needs to start with REACT_APP_ for it to work.

Reference: https://create-react-app.dev/docs/adding-custom-environment-variables/

NOTE - Need to restart application after adding variable in .env file.

Reference - https://medium.com/@thejasonfile/using-dotenv-package-to-create-environment-variables-33da4ac4ea8f

Dynamic variable names in Bash

I've been looking for better way of doing it recently. Associative array sounded like overkill for me. Look what I found:

suffix=bzz
declare prefix_$suffix=mystr

...and then...

varname=prefix_$suffix
echo ${!varname}

How to round up value C# to the nearest integer?

It is also possible to round negative integers

// performing d = c * 3/4 where d can be pos or neg
d = ((c * a) + ((c>0? (b>>1):-(b>>1)))) / b;
// explanation:
// 1.) multiply:          c * a  
// 2.) if c is negative:  (c>0? subtract half of the dividend 
//                              (b>>1) is bit shift right = (b/2)
//     if c is positive:  else  add half of the dividend 
// 3.) do the division
// on a C51/52 (8bit embedded) or similar like ATmega the below code may execute in approx 12cpu cycles (not tested)

Extended from a tip somewhere else in here. Sorry, missed from where.

/* Example test: integer rounding example including negative*/
#include <stdio.h>
#include <string.h>

int main () {
   //rounding negative int
   // doing something like d = c * 3/4
   int a=3;
   int b=4;
   int c=-5;
   int d;
   int s=c;
   int e=c+10;


   for(int f=s; f<=e; f++) {
      printf("%d\t",f);

      double cd=f, ad=a, bd=b , dd;

      // d = c * 3/4  with double
      dd = cd * ad / bd;

      printf("%.2f\t",dd);
      printf("%.1f\t",dd);        
      printf("%.0f\t",dd);

      // try again with typecast have used that a lot in Borland C++ 35 years ago....... maybe evolution has overtaken it ;) ***
      // doing div before mul on purpose
      dd =(double)c * ((double)a / (double)b);
      printf("%.2f\t",dd);

      c=f;
      // d = c * 3/4  with integer rounding
      d = ((c * a) + ((c>0? (b>>1):-(b>>1)))) / b;
      printf("%d\t",d);
      puts("");
  }
 return 0;
}

/* test output
in  2f     1f   0f cast int   
-5  -3.75   -3.8    -4  -3.75   -4  
-4  -3.00   -3.0    -3  -3.75   -3  
-3  -2.25   -2.2    -2  -3.00   -2  
-2  -1.50   -1.5    -2  -2.25   -2  
-1  -0.75   -0.8    -1  -1.50   -1  
 0   0.00    0.0     0  -0.75    0  
 1   0.75    0.8     1   0.00    1  
 2   1.50    1.5     2   0.75    2  
 3   2.25    2.2     2   1.50    2  
 4   3.00    3.0     3   2.25  3    
 5   3.75    3.8     4   3.00   

// by the way evolution: 
// Is there any decent small integer library out there for that by now?

Deleting an SVN branch

Command to delete a branch is as follows:

svn delete -m "<your message>" <branch url>

If you wish to not fetch/checkout the entire repo, execute the following command on your terminal:

1) get the absolute path of the directory that will contain your working copy
> pwd
2) Start svn code checkout
> svn checkout <branch url> <absolute path from point 1>

The above steps will get you the files inside the branch folder and not the entire folder.

How to position a Bootstrap popover?

Simply add an attribute to your popover! See my JSFiddle if you're in a hurry.

We want to add an ID or a class to a particular popover so that we may customize it the way we want via CSS.

Please note that we don't want to customize all popovers! This is terrible idea.

Here is a simple example - display the popover like this:

enter image description here

_x000D_
_x000D_
// We add the id 'my-popover'_x000D_
$("#my-button").popover({_x000D_
    html : true,_x000D_
    placement: 'bottom'_x000D_
}).data('bs.popover').tip().attr('id', 'my-popover');
_x000D_
#my-popover {_x000D_
    left: -169px!important;_x000D_
}_x000D_
#my-popover .arrow {_x000D_
    left: 90%_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>_x000D_
_x000D_
<button id="my-button" data-toggle="popover">My Button</button>
_x000D_
_x000D_
_x000D_

ICommand MVVM implementation

I have written this article about the ICommand interface.

The idea - creating a universal command that takes two delegates: one is called when ICommand.Execute (object param) is invoked, the second checks the status of whether you can execute the command (ICommand.CanExecute (object param)).

Requires the method to switching event CanExecuteChanged. It is called from the user interface elements for switching the state CanExecute() command.

public class ModelCommand : ICommand
{
    #region Constructors

    public ModelCommand(Action<object> execute)
        : this(execute, null) { }

    public ModelCommand(Action<object> execute, Predicate<object> canExecute)
    {
        _execute = execute;
        _canExecute = canExecute;
    }

    #endregion

    #region ICommand Members

    public event EventHandler CanExecuteChanged;

    public bool CanExecute(object parameter)
    {
        return _canExecute != null ? _canExecute(parameter) : true;
    }

    public void Execute(object parameter)
    {
        if (_execute != null)
            _execute(parameter);
    }

    public void OnCanExecuteChanged()
    {
        CanExecuteChanged(this, EventArgs.Empty);
    }

    #endregion

    private readonly Action<object> _execute = null;
    private readonly Predicate<object> _canExecute = null;
}

Get Cell Value from Excel Sheet with Apache Poi

May be by:-

    for(Row row : sheet) {          
        for(Cell cell : row) {              
            System.out.print(cell.getStringCellValue());

        }
    }       

For specific type of cell you can try:

switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
    cellValue = cell.getStringCellValue();
    break;

case Cell.CELL_TYPE_FORMULA:
    cellValue = cell.getCellFormula();
    break;

case Cell.CELL_TYPE_NUMERIC:
    if (DateUtil.isCellDateFormatted(cell)) {
        cellValue = cell.getDateCellValue().toString();
    } else {
        cellValue = Double.toString(cell.getNumericCellValue());
    }
    break;

case Cell.CELL_TYPE_BLANK:
    cellValue = "";
    break;

case Cell.CELL_TYPE_BOOLEAN:
    cellValue = Boolean.toString(cell.getBooleanCellValue());
    break;

}

Change bootstrap datepicker date format on select

If by ID:

$('#datepicker').datepicker({
    format: 'dd/mm/yyyy'

});

If by Class:

$('.datepicker').datepicker({
    format: 'dd/mm/yyyy'

});

Sort a Custom Class List<T>

For this case you can also sort using LINQ:

week = week.OrderBy(w => DateTime.Parse(w.date)).ToList();

How do I find the parent directory in C#?

IO.Path.GetFullPath(@"..\..")

If you clear the "bin\Debug\" in the Project properties -> Build -> Output path, then you can just use AppDomain.CurrentDomain.BaseDirectory

Check if a Bash array contains a value

I typically just use:

inarray=$(echo ${haystack[@]} | grep -o "needle" | wc -w)

non zero value indicates a match was found.

MySQL "between" clause not inclusive?

From the MySQL-manual:

This is equivalent to the expression (min <= expr AND expr <= max)

htaccess remove index.php from url

This will work, use the following code in .htaccess file RewriteEngine On

# Send would-be 404 requests to Craft
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/(favicon\.ico|apple-touch-icon.*\.png)$ [NC]
RewriteRule (.+) index.php?p=$1 [QSA,L]

How do I compare a value to a backslash?

Use following code to perform if-else conditioning in python: Here, I am checking the length of the string. If the length is less than 3 then do nothing, if more then 3 then I check the last 3 characters. If last 3 characters are "ing" then I add "ly" at the end otherwise I add "ing" at the end.

Code-

if (len(s)<=3):
    return s
elif s[-3:]=="ing":
    return s+"ly"
else: return s + "ing"

What is the difference between CloseableHttpClient and HttpClient in Apache HttpClient API?

Had the same question. The other answers don't seem to address why close() is really necessary? Also, Op seemed to be struggling to figure out the preferred way to work with HttpClient, et al.


According to Apache:

// The underlying HTTP connection is still held by the response object
// to allow the response content to be streamed directly from the network socket.
// In order to ensure correct deallocation of system resources
// the user MUST call CloseableHttpResponse#close() from a finally clause.

In addition, the relationships go as follows:

HttpClient (interface)

implemented by:

CloseableHttpClient - ThreadSafe.

DefaultHttpClient - ThreadSafe BUT deprecated, use HttpClientBuilder instead.

HttpClientBuilder - NOT ThreadSafe, BUT creates ThreadSafe CloseableHttpClient.

  • Use to create CUSTOM CloseableHttpClient.

HttpClients - NOT ThreadSafe, BUT creates ThreadSafe CloseableHttpClient.

  • Use to create DEFAULT or MINIMAL CloseableHttpClient.

The preferred way according to Apache:

CloseableHttpClient httpclient = HttpClients.createDefault();

The example they give does httpclient.close() in the finally clause, and also makes use of ResponseHandler as well.


As an alternative, the way mkyong does it is a bit interesting, as well:

HttpClient client = HttpClientBuilder.create().build();

He doesn't show a client.close() call but I would think it is necessary, since client is still an instance of CloseableHttpClient.

Android eclipse DDMS - Can't access data/data/ on phone to pull files

On rooted device you can do this:

  1. Open cmd
  2. Type adb shell
  3. su
  4. Press 'Allow' on device
  5. chmod 777 /data /data/data /data/data/com.application.package/data/data/com.application.package/*
  6. Go to the DDMS view in Eclipse

After this you should be able to browse the files on the device.

To get the databases:

  1. chmod 777 /data/data/com.application.package/databases /data/data/com.application.package/databases/*

If it returns permission denied on su

Go to Settings > Developer Options > Root access > Apps and ADB

How to get previous month and year relative to today, using strtotime and date?

ehh, its not a bug as one person mentioned. that is the expected behavior as the number of days in a month is often different. The easiest way to get the previous month using strtotime would probably be to use -1 month from the first of this month.

$date_string = date('Y-m', strtotime('-1 month', strtotime(date('Y-m-01'))));

Python-Requests close http connection

I came to this question looking to solve the "too many open files" error, but I am using requests.session() in my code. A few searches later and I came up with an answer on the Python Requests Documentation which suggests to use the with block so that the session is closed even if there are unhandled exceptions:

with requests.Session() as s:
    s.get('http://google.com')

If you're not using Session you can actually do the same thing: https://2.python-requests.org/en/master/user/advanced/#session-objects

with requests.get('http://httpbin.org/get', stream=True) as r:
    # Do something

How to pass multiple parameters in a querystring

Try like this.It should work

Response.Redirect(String.Format("yourpage.aspx?strId={0}&strName={1}&strDate{2}", Server.UrlEncode(strId), Server.UrlEncode(strName),Server.UrlEncode(strDate)));

Comma separated results in SQL

Use FOR XML PATH('') - which is converting the entries to a comma separated string and STUFF() -which is to trim the first comma- as follows Which gives you the same comma separated result

SELECT  STUFF((SELECT  ',' + INSTITUTIONNAME
            FROM EDUCATION EE
            WHERE  EE.STUDENTNUMBER=E.STUDENTNUMBER
            ORDER BY sortOrder
        FOR XML PATH('')), 1, 1, '') AS listStr

FROM EDUCATION E
GROUP BY E.STUDENTNUMBER

Here is the FIDDLE

SQL Row_Number() function in Where Clause

WITH MyCte AS 
(
    select 
       employee_id,
       RowNum = row_number() OVER (order by employee_id)
    from V_EMPLOYEE 
)
SELECT  employee_id
FROM    MyCte
WHERE   RowNum > 0
ORDER BY employee_id

Best way to define private methods for a class in Objective-C

While I am no Objective-C expert, I personally just define the method in the implementation of my class. Granted, it must be defined before (above) any methods calling it, but it definitely takes the least amount of work to do.