Programs & Examples On #Smartxls

Why is the Android emulator so slow? How can we speed up the Android emulator?

Gone were those days, when we used to run projects on slow Android Emulators. Today, Android Emulators are on steroids.. Yeah you heard me. No other emulators are as fast as Android Emulators. You can go to my blog for more details:

http://androidveteran.blogspot.in/2016/01/android-emulator-multi-touch.html

I have explained in details about new Android Emulators. Check it out.

Believe me they are as fast as your real device works.

How to enable PHP short tags?

This can be done by enabling short_open_tag in php.ini:

1.To locate php.ini file,on comment line execute

 php --ini

you will get some thing like this,

Configuration File (php.ini) Path: /etc
Loaded Configuration File:         /etc/php.ini
Scan for additional .ini files in: /etc/php.d
Additional .ini files parsed:      /etc/php.d/curl.ini,
/etc/php.d/fileinfo.ini,
/etc/php.d/gd.ini,
/etc/php.d/json.ini,
/etc/php.d/mcrypt.ini,
/etc/php.d/mysql.ini,
/etc/php.d/mysqli.ini,
/etc/php.d/pdo.ini,
/etc/php.d/pdo_mysql.ini,
/etc/php.d/pdo_sqlite.ini,
/etc/php.d/phar.ini,
/etc/php.d/sqlite3.ini,
/etc/php.d/zip.ini

See 2nd line from the comment output.The file will be in the mentioned path.

2.Open php.ini file and find short_open_tag. By default it is in off change it to on.

3.Restart the server,execute this comment

service httpd restart

Thanks

How to start an application using android ADB tools?

We can as well start an application by knowing application type and feeding it with data:

adb shell am start -d "file:///sdcard/sample.3gp" -t "video/3gp" -a android.intent.action.VIEW

This command displays available Video Players to play sample.3gp file

HTTP POST using JSON in Java

It's probably easiest to use HttpURLConnection.

http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139

You'll use JSONObject or whatever to construct your JSON, but not to handle the network; you need to serialize it and then pass it to an HttpURLConnection to POST.

Error running android: Gradle project sync failed. Please fix your project and try again

Go to

file->settings->build,execution,deployment->gradle.

(and set gradle home path from your directory)

@Value annotation type casting to Integer from String

Assuming you have a properties file on your classpath that contains

api.orders.pingFrequency=4

I tried inside a @Controller

@Controller
public class MyController {     
    @Value("${api.orders.pingFrequency}")
    private Integer pingFrequency;
    ...
}

With my servlet context containing :

<context:property-placeholder location="classpath:myprops.properties" />

It worked perfectly.

So either your property is not an integer type, you don't have the property placeholder configured correctly, or you are using the wrong property key.

I tried running with an invalid property value, 4123;. The exception I got is

java.lang.NumberFormatException: For input string: "4123;"

which makes me think the value of your property is

api.orders.pingFrequency=(java.lang.Integer)${api.orders.pingFrequency}

How to read values from properties file?

I'll recommend reading this link https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html from SpringBoot docs about injecting external configs. They didn't only talk about retrieving from a properties file but also YAML and even JSON files. I found it helpful. I hope you do too.

Proper way of checking if row exists in table in PL/SQL block

select nvl(max(1), 0) from mytable;

This statement yields 0 if there are no rows, 1 if you have at least one row in that table. It's way faster than doing a select count(*). The optimizer "sees" that only a single row needs to be fetched to answer the question.

Here's a (verbose) little example:

declare
  YES constant      signtype := 1;
  NO  constant      signtype := 0;
  v_table_has_rows  signtype;
begin

  select nvl(max(YES), NO)
    into v_table_has_rows
    from mytable -- where ...
  ;

  if v_table_has_rows = YES then
    DBMS_OUTPUT.PUT_LINE ('mytable has at least one row');
  end if;

end;

Error in styles_base.xml file - android app - No resource found that matches the given name 'android:Widget.Material.ActionButton'

Go to your Android SDK installed directory then extras > android > support > v7 > appcompat.

in my case : D:\Software\adt-bundle-windows-x86-20140702\sdk\extras\android\support\v7\appcompat

once you are in appcompat folder ,check for project.properties file then change the value from default 19 to 21 as :

target=android-21.

Save the file and then refresh your project.

Then clean the project: In project tab , select clean option then select your project and clean...

This will resolve the error. If not, make sure your project also targets API 21 or higher (same steps as before, and easily forgotten when upgrading a project which targets an older version). Enjoy coding...

Authentication failed to bitbucket

Tools > Options > Use System Git , then select the git.exe file

enter image description here

The credentials will be required again, and the problem will be solved.

How do I use the new computeIfAbsent function?

Recently I was playing with this method too. I wrote a memoized algorithm to calcualte Fibonacci numbers which could serve as another illustration on how to use the method.

We can start by defining a map and putting the values in it for the base cases, namely, fibonnaci(0) and fibonacci(1):

private static Map<Integer,Long> memo = new HashMap<>();
static {
   memo.put(0,0L); //fibonacci(0)
   memo.put(1,1L); //fibonacci(1)
}

And for the inductive step all we have to do is redefine our Fibonacci function as follows:

public static long fibonacci(int x) {
   return memo.computeIfAbsent(x, n -> fibonacci(n-2) + fibonacci(n-1));
}

As you can see, the method computeIfAbsent will use the provided lambda expression to calculate the Fibonacci number when the number is not present in the map. This represents a significant improvement over the traditional, tree recursive algorithm.

How do you run a crontab in Cygwin on Windows?

You have two options:

  1. Install cron as a windows service, using cygrunsrv:

    cygrunsrv -I cron -p /usr/sbin/cron -a -n
    
    net start cron
    

    Note, in (very) old versions of cron you need to use -D instead of -n

  2. The 'non .exe' files are probably bash scripts, so you can run them via the windows scheduler by invoking bash to run the script, e.g.:

    C:\cygwin\bin\bash.exe -l -c "./full-path/to/script.sh"
    

High-precision clock in Python

The original question specifically asked for Unix but multiple answers have touched on Windows, and as a result there is misleading information on windows. The default timer resolution on windows is 15.6ms you can verify here.

Using a slightly modified script from cod3monk3y I can show that windows timer resolution is ~15milliseconds by default. I'm using a tool available here to modify the resolution.

Script:

import time

# measure the smallest time delta by spinning until the time changes
def measure():
    t0 = time.time()
    t1 = t0
    while t1 == t0:
        t1 = time.time()
    return t1-t0

samples = [measure() for i in range(30)]

for s in samples:
    print(f'time delta: {s:.4f} seconds') 

enter image description here

enter image description here

These results were gathered on windows 10 pro 64-bit running python 3.7 64-bit.

Enable/Disable a dropdownbox in jquery

$("#chkdwn2").change(function() { 
    if (this.checked) $("#dropdown").prop("disabled",'disabled');
}) 

How do I display images from Google Drive on a website?

Use the 'Get Link' option in Google Drive to get the URL.

Use <img> tag in HTML and paste the link in there.

Change Open? in the URL to uc?.

How to define an empty object in PHP

to access data in a stdClass in similar fashion you do with an asociative array just use the {$var} syntax.

$myObj = new stdClass;
$myObj->Prop1 = "Something";
$myObj->Prop2 = "Something else";

// then to acces it directly

echo $myObj->{'Prop1'};
echo $myObj->{'Prop2'};

// or what you may want

echo $myObj->{$myStringVar};

Adding items in a Listbox with multiple columns

By using the List property.

ListBox1.AddItem "foo"
ListBox1.List(ListBox1.ListCount - 1, 1) = "bar"

How to change Angular CLI favicon

What really works for me was putting my favicon into assets folder and apear automatically in the browser.

  1. change location to assets folder inside src folder.
  2. change index.html like this <link rel="icon" type="image/x-icon" href="assets/favicon.png">

How to change UINavigationBar background color from the AppDelegate

In Swift 4.2 and Xcode 10.1

You can change your navigation bar colour from your AppDelegate directly to your entire project.

In didFinishLaunchingWithOptions launchOptions: write below to lines of code

UINavigationBar.appearance().tintColor = UIColor.white
UINavigationBar.appearance().barTintColor = UIColor(red: 2/255, green: 96/255, blue: 130/255, alpha: 1.0)

Here

tintColor is for to set background images like back button & menu lines images etc. (See below left and right menu image)

barTintColor is for navigation bar background colour

If you want to set specific view controller navigation bar colour, write below code in viewDidLoad()

//Add navigation bar colour
navigationController?.navigationBar.barTintColor = UIColor(red: 2/255, green: 96/255, blue: 130/255, alpha: 1.0)
navigationController?.navigationBar.tintColor = UIColor.white

enter image description here

8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE

No Need to manually start an application every time at time of development to implements changes use 'spring-boot-devtool' maven dependency.

Automatic Restart : To use the module you simply need to add it as a dependency in your Maven POM:

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
    </dependency>

When you have the spring-boot-devtools module included, any classpath file changes will automatically trigger an application restart. We do some tricks to try and keep restarts fast, so for many microservice style applications this technique might be good enough.

explicit casting from super class to subclass

In order to avoid this kind of ClassCastException, if you have:

class A
class B extends A

You can define a constructor in B that takes an object of A. This way we can do the "cast" e.g.:

public B(A a) {
    super(a.arg1, a.arg2); //arg1 and arg2 must be, at least, protected in class A
    // If B class has more attributes, then you would initilize them here
}

how to install Lex and Yacc in Ubuntu?

Use the synaptic packet manager in order to install yacc / lex. If you are feeling more comfortable doing this on the console just do:

sudo apt-get install bison flex

There are some very nice articles on the net on how to get started with those tools. I found the article from CodeProject to be quite good and helpful (see here). But you should just try and search for "introduction to lex", there are plenty of good articles showing up.

Delete all lines starting with # or ; in Notepad++

Its possible, but not directly.

In short, go to the search, use your regex, check "mark line" and click "Find all". It results in bookmarks for all those lines.

In the search menu there is a point "delete bookmarked lines" voila.

I found the answer here (the correct answer is the second one, not the accepted!): How to delete specific lines on Notepad++?

How to enable native resolution for apps on iPhone 6 and 6 Plus?

Note that iPhone 6 will use the 320pt (640px) resolution if you have enabled the 'Display Zoom' in iPhone > Settings > Display & Brightness > View.

How to escape special characters of a string with single backslashes

This is one way to do it (in Python 3.x):

escaped = a_string.translate(str.maketrans({"-":  r"\-",
                                          "]":  r"\]",
                                          "\\": r"\\",
                                          "^":  r"\^",
                                          "$":  r"\$",
                                          "*":  r"\*",
                                          ".":  r"\."}))

For reference, for escaping strings to use in regex:

import re
escaped = re.escape(a_string)

How to emulate a do-while loop in Python?

The way I've done this is as follows...

condition = True
while condition:
     do_stuff()
     condition = (<something that evaluates to True or False>)

This seems to me to be the simplistic solution, I'm surprised I haven't seen it here already. This can obviously also be inverted to

while not condition:

etc.

Storing an object in state of a React component?

  1. this.setState({ abc.xyz: 'new value' }); syntax is not allowed. You have to pass the whole object.

    this.setState({abc: {xyz: 'new value'}});
    

    If you have other variables in abc

    var abc = this.state.abc;
    abc.xyz = 'new value';
    this.setState({abc: abc});
    
  2. You can have ordinary variables, if they don't rely on this.props and this.state.

How to get the HTML's input element of "file" type to only accept pdf files?

To get the HTML file input form element to only accept PDFs, you can use the accept attribute in modern browsers such as Firefox 9+, Chrome 16+, Opera 11+ and IE10+ like such:

<input name="file1" type="file" accept="application/pdf">

You can string together multiple mime types with a comma.

The following string will accept JPG, PNG, GIF, PDF, and EPS files:

<input name="foo" type="file" accept="image/jpeg,image/gif,image/png,application/pdf,image/x-eps">

In older browsers the native OS file dialog cannot be restricted – you'd have to use Flash or a Java applet or something like that to handle the file transfer.

And of course it goes without saying that this doesn't do anything to verify the validity of the file type. You'll do that on the server-side once the file has uploaded.

A little update – with javascript and the FileReader API you could do more validation client-side before uploading huge files to your server and checking them again.

How to start working with GTest and CMake

I decided to throw something generic together real quick demonstrating a different way of doing it than the answers previously posted, in hope that it might help someone. The following worked for me on my mac. Firstly I ran setup commands for gtests. I just used a script I found to setup everything.

#!/usr/bin/env bash

# install gtests script on mac
# https://gist.github.com/butuzov/e7df782c31171f9563057871d0ae444a

#usage
# chmod +x ./gtest_installer.sh
# sudo ./gtest_installer.sh

# Current directory
__THIS_DIR=$(pwd)


# Downloads the 1.8.0 to disc
function dl {
    printf "\n  Downloading Google Test Archive\n\n"
    curl -LO https://github.com/google/googletest/archive/release-1.8.0.tar.gz
    tar xf release-1.8.0.tar.gz
}

# Unpack and Build
function build {
    printf "\n  Building GTest and Gmock\n\n"
    cd googletest-release-1.8.0
    mkdir build 
    cd $_
    cmake -Dgtest_build_samples=OFF -Dgtest_build_tests=OFF ../
    make
}

# Install header files and library
function install {
    printf "\n  Installing GTest and Gmock\n\n"

    USR_LOCAL_INC="/usr/local/include"
    GTEST_DIR="/usr/local/Cellar/gtest/"
    GMOCK_DIR="/usr/local/Cellar/gmock/"

    mkdir $GTEST_DIR

    cp googlemock/gtest/*.a $GTEST_DIR
    cp -r ../googletest/include/gtest/  $GTEST_DIR
    ln -snf $GTEST_DIR $USR_LOCAL_INC/gtest
    ln -snf $USR_LOCAL_INC/gtest/libgtest.a /usr/local/lib/libgtest.a
    ln -snf $USR_LOCAL_INC/gtest/libgtest_main.a /usr/local/lib/libgtest_main.a

    mkdir $GMOCK_DIR
    cp googlemock/*.a   $GMOCK_DIR
    cp -r ../googlemock/include/gmock/  $GMOCK_DIR
    ln -snf $GMOCK_DIR $USR_LOCAL_INC/gmock
    ln -snf $USR_LOCAL_INC/gmock/libgmock.a /usr/local/lib/libgmock.a
    ln -snf $USR_LOCAL_INC/gmock/libgmock_main.a /usr/local/lib/libgmock_main.a
}

# Final Clean up.
function cleanup {
    printf "\n  Running Cleanup\n\n"

    cd $__THIS_DIR
    rm -rf $(pwd)/googletest-release-1.8.0
    unlink $(pwd)/release-1.8.0.tar.gz
}

dl && build && install && cleanup 

Next, I made a simple folder structure and wrote some quick classes

utils/
  cStringUtils.cpp
  cStringUtils.h
  CMakeLists.txt
utils/tests/
    gtestsMain.cpp
    cStringUtilsTest.cpp
    CMakeLists.txt

I made a top level CMakeLists.txt for the utils folder, and a CMakeLists.txt for the tests folder

cmake_minimum_required(VERSION 2.6)

project(${GTEST_PROJECT} C CXX)

set(CMAKE_C_STANDARD 98)
set(CMAKE_CXX_STANDARD 98)

#include .h and .cpp files in util folder
include_directories("${CMAKE_CURRENT_SOURCE_DIR}")

##########
# GTests
#########
add_subdirectory(tests)

This is the CMakeLists.txt in the tests folder

cmake_minimum_required(VERSION 2.6)

set(GTEST_PROJECT gtestProject)

enable_testing()

message("Gtest Cmake")

find_package(GTest REQUIRED)

# The utils, test, and gtests directories
include_directories("${CMAKE_CURRENT_SOURCE_DIR}")
include_directories("/usr/local/Cellar/gtest/include")
include_directories("/usr/local/Cellar/gtest/lib")

set(SOURCES
  gtestsMain.cpp
  ../cStringUtils.cpp
  cStringUtilsTest.cpp
)

set(HEADERS
  ../cStringUtils.h
)

add_executable(${GTEST_PROJECT} ${SOURCES})
target_link_libraries(${GTEST_PROJECT} PUBLIC
  gtest
  gtest_main
)

add_test(${GTEST_PROJECT} ${GTEST_PROJECT})

Then all that's left is to write a sample gtest and gtest main

sample gtest

#include "gtest/gtest.h"
#include "cStringUtils.h"

namespace utils
{

class cStringUtilsTest : public ::testing::Test {

 public:

  cStringUtilsTest() : m_function_param(10) {}
  ~cStringUtilsTest(){}

 protected:
  virtual void SetUp() 
  {
    // declare pointer 
    pFooObject = new StringUtilsC();    
  }

  virtual void TearDown() 
  {
    // Code here will be called immediately after each test
    // (right before the destructor).
    if (pFooObject != NULL)
    {
      delete pFooObject;
      pFooObject = NULL;
    }
  }


  StringUtilsC fooObject;              // declare object
  StringUtilsC *pFooObject;
  int m_function_param;                // this value is used to test constructor
};

TEST_F(cStringUtilsTest, testConstructors){
    EXPECT_TRUE(1);

  StringUtilsC fooObject2 = fooObject; // use copy constructor


  fooObject.fooFunction(m_function_param);
  pFooObject->fooFunction(m_function_param);
  fooObject2.fooFunction(m_function_param);
}

} // utils end

sample gtest main

#include "gtest/gtest.h"
#include "cStringUtils.h"

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv); 
  return RUN_ALL_TESTS();
}

I can then compile and run gtests with the following commands from the utils folder

cmake .
make 
./tests/gtestProject

How do I initialize a dictionary of empty lists in Python?

Passing [] as second argument to dict.fromkeys() gives a rather useless result – all values in the dictionary will be the same list object.

In Python 2.7 or above, you can use a dicitonary comprehension instead:

data = {k: [] for k in range(2)}

In earlier versions of Python, you can use

data = dict((k, []) for k in range(2))

How to do date/time comparison

The following solved my problem of converting string into date

package main

import (
    "fmt"
    "time"
)

func main() {
    value  := "Thu, 05/19/11, 10:47PM"
    // Writing down the way the standard time would look like formatted our way
    layout := "Mon, 01/02/06, 03:04PM"
    t, _ := time.Parse(layout, value)
    fmt.Println(t)
}

// => "Thu May 19 22:47:00 +0000 2011"

Thanks to paul adam smith

Tools: replace not replacing in Android manifest

I also went through this problem and changed that:

<application  android:debuggable="true" android:icon="@drawable/app_icon" android:label="@string/app_name" android:supportsRtl="true" android:allowBackup="false" android:fullBackupOnly="false" android:theme="@style/UnityThemeSelector">

to

 <application tools:replace="android:allowBackup" android:debuggable="true" android:icon="@drawable/app_icon" android:label="@string/app_name" android:supportsRtl="true" android:allowBackup="false" android:fullBackupOnly="false" android:theme="@style/UnityThemeSelector">

Kill a postgresql session/connection

OSX, Postgres 9.2 (installed with homebrew)

$ launchctl unload -w ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
$ pg_ctl restart -D /usr/local/var/postgres
$ launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist


If your datadir is elsewhere you can find out where it is by examining the output of ps aux | grep postgres

Reference - What does this regex mean?

The Stack Overflow Regular Expressions FAQ

See also a lot of general hints and useful links at the tag details page.


Online tutorials

Quantifiers

Character Classes

Escape Sequences

Anchors

(Also see "Flavor-Specific Information ? Java ? The functions in Matcher")

Groups

Lookarounds

Modifiers

Other:

Common Tasks

Advanced Regex-Fu

Flavor-Specific Information

(Except for those marked with *, this section contains non-Stack Overflow links.)

General information

(Links marked with * are non-Stack Overflow links.)

Examples of regex that can cause regex engine to fail

Tools: Testers and Explainers

(This section contains non-Stack Overflow links.)

How to download videos from youtube on java?

ytd2 is a fully functional YouTube video downloader. Check out its source code if you want to see how it's done.

Alternatively, you can also call an external process like youtube-dl to do the job. This is probably the easiest solution but it isn't in "pure" Java.

JavaScript getElementByID() not working

Because when the script executes the browser has not yet parsed the <body>, so it does not know that there is an element with the specified id.

Try this instead:

<html>
<head>
    <title></title>
    <script type="text/javascript">
        window.onload = (function () {
            var refButton = document.getElementById("btnButton");

            refButton.onclick = function() {
                alert('Dhoor shala!');
            };
        });
    </script>
    </head>
<body>
    <form id="form1">
    <div>
        <input id="btnButton" type="button" value="Click me"/>
    </div>
</form>
</body>
</html>

Note that you may as well use addEventListener instead of window.onload = ... to make that function only execute after the whole document has been parsed.

How to catch curl errors in PHP

If CURLOPT_FAILONERROR is false, http errors will not trigger curl errors.

<?php
if (@$_GET['curl']=="yes") {
  header('HTTP/1.1 503 Service Temporarily Unavailable');
} else {
  $ch=curl_init($url = "http://".$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']."?curl=yes");
  curl_setopt($ch, CURLOPT_FAILONERROR, true);
  $response=curl_exec($ch);
  $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  $curl_errno= curl_errno($ch);
  if ($http_status==503)
    echo "HTTP Status == 503 <br/>";
  echo "Curl Errno returned $curl_errno <br/>";
}

How to make a browser display a "save as dialog" so the user can save the content of a string to a file on his system?

Using execComand:

<input type="button" name="save" value="Save" onclick="javascript:document.execCommand('SaveAs','true','your_file.txt')">

In the next link: execCommand

Change Spinner dropdown icon

I have had a lot of difficulty with this as I have a custom spinner, if I setBackground then the Drawable would stretch. My solution to this was to add a drawable to the right of the Spinner TextView. Heres a code snippet from my Custom Spinner. The trick is to Override getView and customize the Textview as you wish.

public class NoTextSpinnerArrayAdapter extends ArrayAdapter<String> {

    private String text = "0";

    public NoTextSpinnerArrayAdapter(Context context, int textViewResourceId, List<String> objects) {
        super(context, textViewResourceId, objects);
    }

    public void updateText(String text){
        this.text = text;
        notifyDataSetChanged();
    }

    public String getText(){
        return text;
    }

    @NonNull
    public View getView(int position, View convertView, @NonNull ViewGroup parent) {
        View view = super.getView(position, convertView, parent);
        TextView textView = view.findViewById(android.R.id.text1);
        textView.setCompoundDrawablePadding(16);
        textView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_menu_white_24dp, 0);

        textView.setGravity(Gravity.END);
        textView.setText(text);
        return view;
    }
}

You also need to set the Spinner background to transparent:

<lifeunlocked.valueinvestingcheatsheet.views.SelectAgainSpinner
            android:id="@+id/saved_tickers_spinner"
            android:background="@android:color/transparent"
            android:layout_width="60dp"
            android:layout_height="match_parent"
            tools:layout_editor_absoluteX="248dp"
            tools:layout_editor_absoluteY="16dp" />

and my custom spinner if you want it....

public class SelectAgainSpinner extends android.support.v7.widget.AppCompatSpinner {
    public SelectAgainSpinner(Context context) {
        super(context);
    }

    public SelectAgainSpinner(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SelectAgainSpinner(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void setPopupBackgroundDrawable(Drawable background) {
        super.setPopupBackgroundDrawable(background);
    }

    @Override
    public void setSelection(int position, boolean animate) {
        boolean sameSelected = position == getSelectedItemPosition();
        super.setSelection(position, animate);
        if (sameSelected) {
            // Spinner does not call the OnItemSelectedListener if the same item is selected, so do it manually now
            if (getOnItemSelectedListener() != null) {
                getOnItemSelectedListener().onItemSelected(this, getSelectedView(), position, getSelectedItemId());
            }
        }
    }

    @Override
    public void setSelection(int position) {
        boolean sameSelected = position == getSelectedItemPosition();
        super.setSelection(position);
        if (sameSelected) {
            // Spinner does not call the OnItemSelectedListener if the same item is selected, so do it manually now
            if (getOnItemSelectedListener() != null) {
                getOnItemSelectedListener().onItemSelected(this, getSelectedView(), position, getSelectedItemId());
            }
        }
    }
}

Why do I have to run "composer dump-autoload" command to make migrations work in laravel?

Short answer: classmaps are static while PSR autoloading is dynamic.

If you don't want to use classmaps, use PSR autoloading instead.

ORA-12154: TNS:could not resolve the connect identifier specified (PLSQL Developer)

I had an issue at work. The oracle server was "patched" and one of the databases I use could not be connect via the TNSNames entry but via Basic connection. The Database was up and admin could see it was up and running.

Addionally any application that used TNS for connecting to the database would not work either.

The problem found was that the database name was not correct in the TNS file but for some reason it's been working for years. Correcting the name fixed it for us. I did find that Oracle SQL Developer kept using the old TNS entry even after I updated it and I don't feel like reinstalling it for just one DB Connection. It appears that when the database was created it was given a smaller name then the others and via some cut and paste action within the TNSNames file it got mixed up. No one is sure how its worked as we're investigating it but the oracle patch ensured that the name had to be correct

An example of the name was it was down as "DBName.Part1.Part2" but in fact the DB name was "DBName"

Change size of axes title and labels in ggplot2

If you are creating many graphs, you could be tired of typing for each graph the lines of code controlling for the size of the titles and texts. What I typically do is creating an object (of class "theme" "gg") that defines the desired theme characteristics. You can do that at the beginning of your code.

My_Theme = theme(
  axis.title.x = element_text(size = 16),
  axis.text.x = element_text(size = 14),
  axis.title.y = element_text(size = 16))

Next, all you will have to do is adding My_Theme to your graphs.

g + My_Theme
if you have another graph, g1, just write:
g1 + My_Theme 
and so on.

How to upgrade docker container after its image changed

Update

This is mainly to query the container not to update as building images is the way to be done

I had the same issue so I created docker-run, a very simple command-line tool that runs inside a docker container to update packages in other running containers.

It uses docker-py to communicate with running docker containers and update packages or run any arbitrary single command

Examples:

docker run --rm -v /var/run/docker.sock:/tmp/docker.sock itech/docker-run exec

by default this will run date command in all running containers and return results but you can issue any command e.g. docker-run exec "uname -a"

To update packages (currently only using apt-get):

docker run --rm -v /var/run/docker.sock:/tmp/docker.sock itech/docker-run update

You can create and alias and use it as a regular command line e.g.

alias docker-run='docker run --rm -v /var/run/docker.sock:/tmp/docker.sock itech/docker-run'

Using OpenGl with C#?

You can OpenGL without a wrapper and use it natively in C#. Just as Jeff Mc said, you would have to import all the functions you need with DllImport.

What he left out is having to create context before you can use any of the OpenGL functions. It's not hard, but there are few other not-so-intuitive DllImports that need to be done.

I have created an example C# project in VS2012 with almost the bare minimum necessary to get OpenGL running on Windows box. It only paints the window blue, but it should be enough to get you started. The example can be found at http://www.glinos-labs.org/?q=programming-opengl-csharp. Look for the No Wrapper example at the bottom.

Android : change button text and background color

Just complementing @Jonsmoke's answer.

For API level 21 and above you can use :

android:backgroundTint="@android:color/white"

in XML for the button layout.

For API level below 21 use an AppCompatButton using app namespace instead of android for backgroundTint.

For example:

<android.support.v7.widget.AppCompatButton
    android:id="@+id/my_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="My Button"
    app:backgroundTint="@android:color/white" />

Where does git config --global get written to?

When is the global .gitconfig file created?

First off, git doesn't automatically create the global config file (.gitconfig) during its installation. The file is not created until it is written to for the first time. If you have never set a system variable, it will not be on your file system. I'm guessing that might be the source of the problem.

One way to ask Git to create it is to request an edit. Doing so will force the file's creation.

git config --global --edit

If you monitor the user's home folder when you issue this command, you will see the .gitconfig file magically appear.

Where is git configuration stored?

Here's a quick rundown of the the name and location of the configuration files associated with the three Git scopes, namely system, global and local:

  • System Git configuration: File named gitconfig located in -git-install-location-/ming<32>/etc
  • Global Git configuraiton: File named .gitconfig located in the user's home folder (C:\Users\git user)
  • Local Git configuration: File named config in the .git folder of the local repo

Of course, seeing is believing, so here's an image showing each file and each location. I pulled the image from an article I wrote on the topic.

Windows Git configuration file locations (TheServerSide.com)

Location of Git configuration files

How to set up Android emulator proxy settings

Sometime even after setting all it may not work. I have tried all the methods like

  1. Setting the proxy in Emulator APN
  2. Setting it thru eclipse preferences --> Android --> Launch

Nothing worked. Then I did the following which worked instantly.

Goto eclipse Run --> run configurations. Under Android Applications you can see you application. Now, on the right hand side click on the Target tab. Under the 'Additional Emulator Command line options' add the following.

-dns-server <DNS servers from your local machine upto three> -http-proxy http://<your proxy>:<your proxy port>

The catch here is that the DNS Server setting should be from your local system. Goto cmd prompt and run ipconfig to check your DNS servers. Same with the proxy server and port. Whatever works for your browser should be put in here.

Google Maps V3 marker with label

If you just want to show label below the marker, then you can extend google maps Marker to add a setter method for label and you can define the label object by extending google maps overlayView like this..

<script type="text/javascript">
    var point = { lat: 22.5667, lng: 88.3667 };
    var markerSize = { x: 22, y: 40 };


    google.maps.Marker.prototype.setLabel = function(label){
        this.label = new MarkerLabel({
          map: this.map,
          marker: this,
          text: label
        });
        this.label.bindTo('position', this, 'position');
    };

    var MarkerLabel = function(options) {
        this.setValues(options);
        this.span = document.createElement('span');
        this.span.className = 'map-marker-label';
    };

    MarkerLabel.prototype = $.extend(new google.maps.OverlayView(), {
        onAdd: function() {
            this.getPanes().overlayImage.appendChild(this.span);
            var self = this;
            this.listeners = [
            google.maps.event.addListener(this, 'position_changed', function() { self.draw();    })];
        },
        draw: function() {
            var text = String(this.get('text'));
            var position = this.getProjection().fromLatLngToDivPixel(this.get('position'));
            this.span.innerHTML = text;
            this.span.style.left = (position.x - (markerSize.x / 2)) - (text.length * 3) + 10 + 'px';
            this.span.style.top = (position.y - markerSize.y + 40) + 'px';
        }
    });
    function initialize(){
        var myLatLng = new google.maps.LatLng(point.lat, point.lng);
        var gmap = new google.maps.Map(document.getElementById('map_canvas'), {
            zoom: 5,
            center: myLatLng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });
        var myMarker = new google.maps.Marker({
            map: gmap,
            position: myLatLng,
            label: 'Hello World!',
            draggable: true
        });
    }
</script>
<style>
    .map-marker-label{
        position: absolute;
    color: blue;
    font-size: 16px;
    font-weight: bold;
    }
</style>

This will work.

CSS Transition doesn't work with top, bottom, left, right

In my case div position was fixed , adding left position was not enough it started working only after adding display block

left:0; display:block;

How to set JVM parameters for Junit Unit Tests?

Parameters can be set on the fly also.

mvn test -DargLine="-Dsystem.test.property=test"

See http://www.cowtowncoder.com/blog/archives/2010/04/entry_385.html

C# function to return array

return Labels; should do the trick!

public static ArtworkData[] GetDataRecords(int UsersID)
{
    ArtworkData[] Labels;
    Labels = new ArtworkData[3];

    return Labels;
}

c# write text on bitmap

Bitmap bmp = new Bitmap("filename.bmp");

RectangleF rectf = new RectangleF(70, 90, 90, 50);

Graphics g = Graphics.FromImage(bmp);

g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.DrawString("yourText", new Font("Tahoma",8), Brushes.Black, rectf);

g.Flush();

image.Image=bmp;

Solution for "Fatal error: Maximum function nesting level of '100' reached, aborting!" in PHP

I had this issue with WordPress on cloud9. It turns out it was the W3 Caching plugin. I disabled the plugin and it worked fine.

How to select rows in a DataFrame between two values, in Python Pandas?

Consider also series between:

df = df[df['closing_price'].between(99, 101)]

How to kill zombie process

Found it at http://www.linuxquestions.org/questions/suse-novell-60/howto-kill-defunct-processes-574612/

2) Here a great tip from another user (Thxs Bill Dandreta): Sometimes

kill -9 <pid>

will not kill a process. Run

ps -xal

the 4th field is the parent process, kill all of a zombie's parents and the zombie dies!

Example

4 0 18581 31706 17 0 2664 1236 wait S ? 0:00 sh -c /usr/bin/gcc -fomit-frame-pointer -O -mfpmat
4 0 18582 18581 17 0 2064 828 wait S ? 0:00 /usr/i686-pc-linux-gnu/gcc-bin/3.3.6/gcc -fomit-fr
4 0 18583 18582 21 0 6684 3100 - R ? 0:00 /usr/lib/gcc-lib/i686-pc-linux-gnu/3.3.6/cc1 -quie

18581, 18582, 18583 are zombies -

kill -9 18581 18582 18583

has no effect.

kill -9 31706

removes the zombies.

Java: Reading a file into an array

You should be able to use forward slashes in Java to refer to file locations.

The BufferedReader class is used for wrapping other file readers whos read method may not be very efficient. A more detailed description can be found in the Java APIs.

Toolkit's use of BufferedReader is probably what you need.

I can not find my.cnf on my windows computer

Here is my answer:

  1. Win+R (shortcut for 'run'), type services.msc, Enter
  2. You should find an entry like 'MySQL56', right click on it, select properties
  3. You should see something like "D:/Program Files/MySQL/MySQL Server 5.6/bin\mysqld" --defaults-file="D:\ProgramData\MySQL\MySQL Server 5.6\my.ini" MySQL56

Full answer here: https://stackoverflow.com/a/20136523/1316649

What is a Subclass

If you have the following:

public class A
{
}

public class B extends A
{
}

then B is a subclass of A, B inherits from A. The opposite would be superclass.

Delete all files of specific type (extension) recursively down a directory using a batch file

I don't have enough reputation to add comment, so I posted this as an answer. But for original issue with this command:

@echo off
FOR %%p IN (C:\Users\vexe\Pictures\sample) DO FOR %%t IN (*.jpg) DO del /s %%p\%%t

The first For is lacking recursive syntax, it should be:

@echo off
FOR /R %%p IN (C:\Users\vexe\Pictures\sample) DO FOR %%t IN (*.jpg) DO del /s %%p\%%t

You can just do:

FOR %%p IN (C:\Users\0300092544\Downloads\Ces_Sce_600) DO @ECHO %%p

to show the actual output.

How do you get a query string on Flask?

The full URL is available as request.url, and the query string is available as request.query_string.decode().

Here's an example:

from flask import request

@app.route('/adhoc_test/')
def adhoc_test():

    return request.query_string

To access an individual known param passed in the query string, you can use request.args.get('param'). This is the "right" way to do it, as far as I know.

ETA: Before you go further, you should ask yourself why you want the query string. I've never had to pull in the raw string - Flask has mechanisms for accessing it in an abstracted way. You should use those unless you have a compelling reason not to.

How to check if a number is a power of 2

Improving the answer of @user134548, without bits arithmetic:

public static bool IsPowerOfTwo(ulong n)
{
    if (n % 2 != 0) return false;  // is odd (can't be power of 2)

    double exp = Math.Log(n, 2);
    if (exp != Math.Floor(exp)) return false;  // if exp is not integer, n can't be power
    return Math.Pow(2, exp) == n;
}

This works fine for:

IsPowerOfTwo(9223372036854775809)

How does OAuth 2 protect against things like replay attacks using the Security Token?

How OAuth 2.0 works in real life:

I was driving by Olaf's bakery on my way to work when I saw the most delicious donut in the window -- I mean, the thing was dripping chocolatey goodness. So I went inside and demanded "I must have that donut!". He said "sure that will be $30."

Yeah I know, $30 for one donut! It must be delicious! I reached for my wallet when suddenly I heard the chef yell "NO! No donut for you". I asked: why? He said he only accepts bank transfers.

Seriously? Yep, he was serious. I almost walked away right there, but then the donut called out to me: "Eat me, I'm delicious...". Who am I to disobey orders from a donut? I said ok.

He handed me a note with his name on it (the chef, not the donut): "Tell them Olaf sent you". His name was already on the note, so I don't know what the point of saying that was, but ok.

I drove an hour and a half to my bank. I handed the note to the teller; I told her Olaf sent me. She gave me one of those looks, the kind that says, "I can read".

She took my note, asked for my id, asked me how much money was ok to give him. I told her $30 dollars. She did some scribbling and handed me another note. This one had a bunch of numbers on it, I guessed that's how they keep track of the notes.

At that point I'm starving. I rushed out of there, an hour and a half later I was back, standing in front of Olaf with my note extended. He took it, looked it over and said, "I'll be back".

I thought he was getting my donut, but after 30 minutes I started to get suspicious. So I asked the guy behind the counter "Where's Olaf?". He said "He went to get money". "What do you mean?". "He take note to bank".

Huh... so Olaf took the note that the bank gave me and went back to the bank to get money out of my account. Since he had the note the bank gave me, the bank knew he was the guy I was talking about, and because I spoke with the bank they knew to only give him $30.

It must have taken me a long time to figure that out because by the time I looked up, Olaf was standing in front of me finally handing me my donut. Before I left I had to ask, "Olaf, did you always sell donuts this way?". "No, I used to do it different."

Huh. As I was walking back to my car my phone rang. I didn't bother answering, it was probably my job calling to fire me, my boss is such a ***. Besides, I was caught up thinking about the process I just went through.

I mean think about it: I was able to let Olaf take $30 out of my bank account without having to give him my account information. And I didn't have to worry that he would take out too much money because I already told the bank he was only allowed to take $30. And the bank knew he was the right guy because he had the note they gave me to give to Olaf.

Ok, sure I would rather hand him $30 from my pocket. But now that he had that note I could just tell the bank to let him take $30 every week, then I could just show up at the bakery and I didn't have to go to the bank anymore. I could even order the donut by phone if I wanted to.

Of course I'd never do that -- that donut was disgusting.

I wonder if this approach has broader applications. He mentioned this was his second approach, I could call it Olaf 2.0. Anyway I better get home, I gotta start looking for a new job. But not before I get one of those strawberry shakes from that new place across town, I need something to wash away the taste of that donut.

How do you post to the wall on a facebook page (not profile)

If your blog outputs an RSS feed you can use Facebook's "RSS Graffiti" application to post that feed to your wall in Facebook. There are other RSS Facebook apps as well; just search "Facebook for RSS apps"...

SQL how to increase or decrease one for a int column in one command

The single-step answer to the first question is to use something like:

update TBL set CLM = CLM + 1 where key = 'KEY'

That's very much a single-instruction way of doing it.

As for the second question, you shouldn't need to resort to DBMS-specific SQL gymnastics (like UPSERT) to get the result you want. There's a standard method to do update-or-insert that doesn't require a specific DBMS.

try:
    insert into TBL (key,val) values ('xyz',0)
catch:
    do nothing
update TBL set val = val + 1 where key = 'xyz'

That is, you try to do the creation first. If it's already there, ignore the error. Otherwise you create it with a 0 value.

Then do the update which will work correctly whether or not:

  • the row originally existed.
  • someone updated it between your insert and update.

It's not a single instruction and yet, surprisingly enough, it's how we've been doing it successfully for a long long time.

Find the IP address of the client in an SSH session

You could use the command:

server:~# pinky

that will give to you somehting like this:

Login      Name                 TTY    Idle   When                 Where 

root       root                 pts/0         2009-06-15 13:41     192.168.1.133

How to copy and paste code without rich text formatting?

Just to summarize the available options:

Tools

Browsers

  • To copy plain text from a browser: Copy As Plain Text or CopyPlainText (suggested by cori) - Firefox extensions
  • To paste without formatting to a browser (Firefox/Chrome at least): CTRL+? Shift+V on Windows/Linux, see below for Mac OS X.

Other

  • Under Mac OS X, you can ? Shift+? Alt+? Command+V to paste with the "current" format (Edit -> Paste and Match Style); or ? Command+? Shift+V to paste without formatting (by Kamafeather)
  • Paste to Notepad (or other text editor), and then copy from Notepad and paste again
  • For single-line text: paste to any non-rich text field (browser URL, textarea, search/find inputs, etc.)

Please feel free to edit/add new items

"Application tried to present modally an active controller"?

I had same problem.I solve it. You can try This code:

[tabBarController setSelectedIndex:1];
[self dismissModalViewControllerAnimated:YES];

How to POST JSON data with Python Requests?

Starting with Requests version 2.4.2, you can use the json= parameter (which takes a dictionary) instead of data= (which takes a string) in the call:

>>> import requests
>>> r = requests.post('http://httpbin.org/post', json={"key": "value"})
>>> r.status_code
200
>>> r.json()
{'args': {},
 'data': '{"key": "value"}',
 'files': {},
 'form': {},
 'headers': {'Accept': '*/*',
             'Accept-Encoding': 'gzip, deflate',
             'Connection': 'close',
             'Content-Length': '16',
             'Content-Type': 'application/json',
             'Host': 'httpbin.org',
             'User-Agent': 'python-requests/2.4.3 CPython/3.4.0',
             'X-Request-Id': 'xx-xx-xx'},
 'json': {'key': 'value'},
 'origin': 'x.x.x.x',
 'url': 'http://httpbin.org/post'}

Turn Pandas Multi-Index into column

This doesn't really apply to your case but could be helpful for others (like myself 5 minutes ago) to know. If one's multindex have the same name like this:

                         value
Trial        Trial
    1              0        13
                   1         3
                   2         4
    2              0       NaN
                   1        12
    3              0        34 

df.reset_index(inplace=True) will fail, cause the columns that are created cannot have the same names.

So then you need to rename the multindex with df.index = df.index.set_names(['Trial', 'measurement']) to get:

                           value
Trial    measurement       

    1              0        13
    1              1         3
    1              2         4
    2              0       NaN
    2              1        12
    3              0        34 

And then df.reset_index(inplace=True) will work like a charm.

I encountered this problem after grouping by year and month on a datetime-column(not index) called live_date, which meant that both year and month were named live_date.

Get all directories within directory nodejs

Fully async version with ES6, only native packages, fs.promises and async/await, does file operations in parallel:

const fs = require('fs');
const path = require('path');

async function listDirectories(rootPath) {
    const fileNames = await fs.promises.readdir(rootPath);
    const filePaths = fileNames.map(fileName => path.join(rootPath, fileName));
    const filePathsAndIsDirectoryFlagsPromises = filePaths.map(async filePath => ({path: filePath, isDirectory: (await fs.promises.stat(filePath)).isDirectory()}))
    const filePathsAndIsDirectoryFlags = await Promise.all(filePathsAndIsDirectoryFlagsPromises);
    return filePathsAndIsDirectoryFlags.filter(filePathAndIsDirectoryFlag => filePathAndIsDirectoryFlag.isDirectory)
        .map(filePathAndIsDirectoryFlag => filePathAndIsDirectoryFlag.path);
}

Tested, it works nicely.

Create a hidden field in JavaScript

You can use jquery for create element on the fly

$('#form').append('<input type="hidden" name="fieldname" value="fieldvalue" />');

or other way

$('<input>').attr({
    type: 'hidden',
    id: 'fieldId',
    name: 'fieldname'
}).appendTo('form')

How can I pause setInterval() functions?

My simple way:

function Timer (callback, delay) {
  let callbackStartTime
  let remaining = 0

  this.timerId = null
  this.paused = false

  this.pause = () => {
    this.clear()
    remaining -= Date.now() - callbackStartTime
    this.paused = true
  }
  this.resume = () => {
    window.setTimeout(this.setTimeout.bind(this), remaining)
    this.paused = false
  }
  this.setTimeout = () => {
    this.clear()
    this.timerId = window.setInterval(() => {
      callbackStartTime = Date.now()
      callback()
    }, delay)
  }
  this.clear = () => {
    window.clearInterval(this.timerId)
  }

  this.setTimeout()
}

How to use:

_x000D_
_x000D_
let seconds = 0_x000D_
const timer = new Timer(() => {_x000D_
  seconds++_x000D_
  _x000D_
  console.log('seconds', seconds)_x000D_
_x000D_
  if (seconds === 8) {_x000D_
    timer.clear()_x000D_
_x000D_
    alert('Game over!')_x000D_
  }_x000D_
}, 1000)_x000D_
_x000D_
timer.pause()_x000D_
console.log('isPaused: ', timer.paused)_x000D_
_x000D_
setTimeout(() => {_x000D_
  timer.resume()_x000D_
  console.log('isPaused: ', timer.paused)_x000D_
}, 2500)_x000D_
_x000D_
_x000D_
function Timer (callback, delay) {_x000D_
  let callbackStartTime_x000D_
  let remaining = 0_x000D_
_x000D_
  this.timerId = null_x000D_
  this.paused = false_x000D_
_x000D_
  this.pause = () => {_x000D_
    this.clear()_x000D_
    remaining -= Date.now() - callbackStartTime_x000D_
    this.paused = true_x000D_
  }_x000D_
  this.resume = () => {_x000D_
    window.setTimeout(this.setTimeout.bind(this), remaining)_x000D_
    this.paused = false_x000D_
  }_x000D_
  this.setTimeout = () => {_x000D_
    this.clear()_x000D_
    this.timerId = window.setInterval(() => {_x000D_
      callbackStartTime = Date.now()_x000D_
      callback()_x000D_
    }, delay)_x000D_
  }_x000D_
  this.clear = () => {_x000D_
    window.clearInterval(this.timerId)_x000D_
  }_x000D_
_x000D_
  this.setTimeout()_x000D_
}
_x000D_
_x000D_
_x000D_

The code is written quickly and did not refactored, raise the rating of my answer if you want me to improve the code and give ES2015 version (classes).

How to convert JSON to XML or XML to JSON?

Here is the full c# code to convert xml to json

public static class JSon
{
public static string XmlToJSON(string xml)
{
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xml);

    return XmlToJSON(doc);
}
public static string XmlToJSON(XmlDocument xmlDoc)
{
    StringBuilder sbJSON = new StringBuilder();
    sbJSON.Append("{ ");
    XmlToJSONnode(sbJSON, xmlDoc.DocumentElement, true);
    sbJSON.Append("}");
    return sbJSON.ToString();
}

//  XmlToJSONnode:  Output an XmlElement, possibly as part of a higher array
private static void XmlToJSONnode(StringBuilder sbJSON, XmlElement node, bool showNodeName)
{
    if (showNodeName)
        sbJSON.Append("\"" + SafeJSON(node.Name) + "\": ");
    sbJSON.Append("{");
    // Build a sorted list of key-value pairs
    //  where   key is case-sensitive nodeName
    //          value is an ArrayList of string or XmlElement
    //  so that we know whether the nodeName is an array or not.
    SortedList<string, object> childNodeNames = new SortedList<string, object>();

    //  Add in all node attributes
    if (node.Attributes != null)
        foreach (XmlAttribute attr in node.Attributes)
            StoreChildNode(childNodeNames, attr.Name, attr.InnerText);

    //  Add in all nodes
    foreach (XmlNode cnode in node.ChildNodes)
    {
        if (cnode is XmlText)
            StoreChildNode(childNodeNames, "value", cnode.InnerText);
        else if (cnode is XmlElement)
            StoreChildNode(childNodeNames, cnode.Name, cnode);
    }

    // Now output all stored info
    foreach (string childname in childNodeNames.Keys)
    {
        List<object> alChild = (List<object>)childNodeNames[childname];
        if (alChild.Count == 1)
            OutputNode(childname, alChild[0], sbJSON, true);
        else
        {
            sbJSON.Append(" \"" + SafeJSON(childname) + "\": [ ");
            foreach (object Child in alChild)
                OutputNode(childname, Child, sbJSON, false);
            sbJSON.Remove(sbJSON.Length - 2, 2);
            sbJSON.Append(" ], ");
        }
    }
    sbJSON.Remove(sbJSON.Length - 2, 2);
    sbJSON.Append(" }");
}

//  StoreChildNode: Store data associated with each nodeName
//                  so that we know whether the nodeName is an array or not.
private static void StoreChildNode(SortedList<string, object> childNodeNames, string nodeName, object nodeValue)
{
    // Pre-process contraction of XmlElement-s
    if (nodeValue is XmlElement)
    {
        // Convert  <aa></aa> into "aa":null
        //          <aa>xx</aa> into "aa":"xx"
        XmlNode cnode = (XmlNode)nodeValue;
        if (cnode.Attributes.Count == 0)
        {
            XmlNodeList children = cnode.ChildNodes;
            if (children.Count == 0)
                nodeValue = null;
            else if (children.Count == 1 && (children[0] is XmlText))
                nodeValue = ((XmlText)(children[0])).InnerText;
        }
    }
    // Add nodeValue to ArrayList associated with each nodeName
    // If nodeName doesn't exist then add it
    List<object> ValuesAL;

    if (childNodeNames.ContainsKey(nodeName))
    {
        ValuesAL = (List<object>)childNodeNames[nodeName];
    }
    else
    {
        ValuesAL = new List<object>();
        childNodeNames[nodeName] = ValuesAL;
    }
    ValuesAL.Add(nodeValue);
}

private static void OutputNode(string childname, object alChild, StringBuilder sbJSON, bool showNodeName)
{
    if (alChild == null)
    {
        if (showNodeName)
            sbJSON.Append("\"" + SafeJSON(childname) + "\": ");
        sbJSON.Append("null");
    }
    else if (alChild is string)
    {
        if (showNodeName)
            sbJSON.Append("\"" + SafeJSON(childname) + "\": ");
        string sChild = (string)alChild;
        sChild = sChild.Trim();
        sbJSON.Append("\"" + SafeJSON(sChild) + "\"");
    }
    else
        XmlToJSONnode(sbJSON, (XmlElement)alChild, showNodeName);
    sbJSON.Append(", ");
}

// Make a string safe for JSON
private static string SafeJSON(string sIn)
{
    StringBuilder sbOut = new StringBuilder(sIn.Length);
    foreach (char ch in sIn)
    {
        if (Char.IsControl(ch) || ch == '\'')
        {
            int ich = (int)ch;
            sbOut.Append(@"\u" + ich.ToString("x4"));
            continue;
        }
        else if (ch == '\"' || ch == '\\' || ch == '/')
        {
            sbOut.Append('\\');
        }
        sbOut.Append(ch);
    }
    return sbOut.ToString();
 }
}

To convert a given XML string to JSON, simply call XmlToJSON() function as below.

string xml = "<menu id=\"file\" value=\"File\"> " +
              "<popup>" +
                "<menuitem value=\"New\" onclick=\"CreateNewDoc()\" />" +
                "<menuitem value=\"Open\" onclick=\"OpenDoc()\" />" +
                "<menuitem value=\"Close\" onclick=\"CloseDoc()\" />" +
              "</popup>" +
            "</menu>";

string json = JSON.XmlToJSON(xml);
// json = { "menu": {"id": "file", "popup": { "menuitem": [ {"onclick": "CreateNewDoc()", "value": "New" }, {"onclick": "OpenDoc()", "value": "Open" }, {"onclick": "CloseDoc()", "value": "Close" } ] }, "value": "File" }}

Insert/Update/Delete with function in SQL Server

You can have a table variable as a return type and then update or insert on a table based on that output. In other words, you can set the variable output as the original table, make the modifications and then do an insert to the original table from function output. It is a little hack but if you insert the @output_table from the original table and then say for example: Insert into my_table select * from my_function

then you can achieve the result.

Get time of specific timezone

before you get too excited this was written in 2011

if I were to do this these days I would use Intl.DateTimeFormat. Here is a link to give you an idea of what type of support this had in 2011

original answer now (very) outdated

Date.getTimezoneOffset()

The getTimezoneOffset() method returns the time difference between Greenwich Mean Time (GMT) and local time, in minutes.

For example, If your time zone is GMT+2, -120 will be returned.

Note: This method is always used in conjunction with a Date object.

var d = new Date()
var gmtHours = -d.getTimezoneOffset()/60;
document.write("The local time zone is: GMT " + gmtHours);
//output:The local time zone is: GMT 11

How to debug a GLSL shader?

I am sharing a fragment shader example, how i actually debug.

#version 410 core

uniform sampler2D samp;
in VS_OUT
{
    vec4 color;
    vec2 texcoord;
} fs_in;

out vec4 color;

void main(void)
{
    vec4 sampColor;
    if( texture2D(samp, fs_in.texcoord).x > 0.8f)  //Check if Color contains red
        sampColor = vec4(1.0f, 1.0f, 1.0f, 1.0f);  //If yes, set it to white
    else
        sampColor = texture2D(samp, fs_in.texcoord); //else sample from original
    color = sampColor;

}

enter image description here

Incrementing in C++ - When to use x++ or ++x?

You explained the difference correctly. It just depends on if you want x to increment before every run through a loop, or after that. It depends on your program logic, what is appropriate.

An important difference when dealing with STL-Iterators (which also implement these operators) is, that it++ creates a copy of the object the iterator points to, then increments, and then returns the copy. ++it on the other hand does the increment first and then returns a reference to the object the iterator now points to. This is mostly just relevant when every bit of performance counts or when you implement your own STL-iterator.

Edit: fixed the mixup of prefix and suffix notation

pandas dataframe create new columns and fill with calculated values from same df

In [56]: df = pd.DataFrame(np.abs(randn(3, 4)), index=[1,2,3], columns=['A','B','C','D'])

In [57]: df.divide(df.sum(axis=1), axis=0)
Out[57]: 
          A         B         C         D
1  0.319124  0.296653  0.138206  0.246017
2  0.376994  0.326481  0.230464  0.066062
3  0.036134  0.192954  0.430341  0.340571

Convert data file to blob

As pointed in the comments, file is a blob:

file instanceof Blob; // true

And you can get its content with the file reader API https://developer.mozilla.org/en/docs/Web/API/FileReader

Read more: https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications

_x000D_
_x000D_
var input = document.querySelector('input[type=file]');
var textarea = document.querySelector('textarea');

function readFile(event) {
  textarea.textContent = event.target.result;
  console.log(event.target.result);
}

function changeFile() {
  var file = input.files[0];
  var reader = new FileReader();
  reader.addEventListener('load', readFile);
  reader.readAsText(file);
}

input.addEventListener('change', changeFile);
_x000D_
<input type="file">
<textarea rows="10" cols="50"></textarea>
_x000D_
_x000D_
_x000D_

How do I copy directories recursively with gulp?

The following works without flattening the folder structure:

gulp.src(['input/folder/**/*']).pipe(gulp.dest('output/folder'));

The '**/*' is the important part. That expression is a glob which is a powerful file selection tool. For example, for copying only .js files use: 'input/folder/**/*.js'

How to get device make and model on iOS?

#import <sys/utsname.h>

#define HARDWARE @{@"i386": @"Simulator",@"x86_64": @"Simulator",@"iPod1,1": @"iPod Touch",@"iPod2,1": @"iPod Touch 2nd Generation",@"iPod3,1": @"iPod Touch 3rd Generation",@"iPod4,1": @"iPod Touch 4th Generation",@"iPhone1,1": @"iPhone",@"iPhone1,2": @"iPhone 3G",@"iPhone2,1": @"iPhone 3GS",@"iPhone3,1": @"iPhone 4",@"iPhone4,1": @"iPhone 4S",@"iPhone5,1": @"iPhone 5",@"iPhone5,2": @"iPhone 5",@"iPhone5,3": @"iPhone 5c",@"iPhone5,4": @"iPhone 5c",@"iPhone6,1": @"iPhone 5s",@"iPhone6,2": @"iPhone 5s",@"iPad1,1": @"iPad",@"iPad2,1": @"iPad 2",@"iPad3,1": @"iPad 3rd Generation ",@"iPad3,4": @"iPad 4th Generation ",@"iPad2,5": @"iPad Mini",@"iPad4,4": @"iPad Mini 2nd Generation - Wifi",@"iPad4,5": @"iPad Mini 2nd Generation - Cellular",@"iPad4,1": @"iPad Air 5th Generation - Wifi",@"iPad4,2": @"iPad Air 5th Generation - Cellular"}

@interface ViewController ()
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    struct utsname systemInfo;
    uname(&systemInfo);
    NSLog(@"hardware: %@",[HARDWARE objectForKey:[NSString stringWithCString: systemInfo.machine encoding:NSUTF8StringEncoding]]);
}

How to use Python to login to a webpage and retrieve cookies for later usage?

import urllib, urllib2, cookielib

username = 'myuser'
password = 'mypassword'

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://www.example.com/login.php', login_data)
resp = opener.open('http://www.example.com/hiddenpage.php')
print resp.read()

resp.read() is the straight html of the page you want to open, and you can use opener to view any page using your session cookie.

How to Apply Mask to Image in OpenCV?

Well, this question appears on top of search results, so I believe we need code example here. Here's the Python code:

import cv2

def apply_mask(frame, mask):
    """Apply binary mask to frame, return in-place masked image."""
    return cv2.bitwise_and(frame, frame, mask=mask)

Mask and frame must be the same size, so pixels remain as-is where mask is 1 and are set to zero where mask pixel is 0.

And for C++ it's a little bit different:

cv::Mat inFrame; // Original (non-empty) image
cv::Mat mask; // Original (non-empty) mask

// ...

cv::Mat outFrame;  // Result output
inFrame.copyTo(outFrame, mask);

ORA-29283: invalid file operation ORA-06512: at "SYS.UTL_FILE", line 536

Assume file is already created in the predefined directory with name "table.txt"

  • 1) change the ownership for file :

    sudo chown username:username table.txt
    
  • 2) change the mode of the file

    sudo chmod 777 table.txt
    

Now, try it should work!

How do I hide a menu item in the actionbar?

The best way to hide all items in a menu with just one command is to use "group" on your menu xml. Just add all menu items that will be in your overflow menu inside the same group.

In this example we have two menu items that will always show (regular item and search) and three overflow items:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/someItemNotToHide1"
        android:title="ITEM"
        app:showAsAction="always" />

    <item
        android:id="@+id/someItemNotToHide2"
        android:icon="@android:drawable/ic_menu_search"
        app:showAsAction="collapseActionView|ifRoom"
        app:actionViewClass="android.support.v7.widget.SearchView"
        android:title="Search"/>

    <group android:id="@+id/overFlowItemsToHide">
    <item android:id="@+id/someID" 
    android:orderInCategory="1" app:showAsAction="never" />
    <item android:id="@+id/someID2" 
    android:orderInCategory="1" app:showAsAction="never" />
    <item android:id="@+id/someID3" 
    android:orderInCategory="1" app:showAsAction="never" />
    </group>
</menu>

Then, on your activity (preferable at onCreateOptionsMenu), use command setGroupVisible to set all menu items visibility to false or true.

public boolean onCreateOptionsMenu(Menu menu) {
   menu.setGroupVisible(R.id.overFlowItems, false); // Or true to be visible
}

If you want to use this command anywhere else on your activity, be sure to save menu class to local, and always check if menu is null, because you can execute before createOptionsMenu:

Menu menu;

public boolean onCreateOptionsMenu(Menu menu) {
       this.menu = menu;

}

public void hideMenus() {
       if (menu != null) menu.setGroupVisible(R.id.overFlowItems, false); // Or true to be visible       
}

How to activate a specific worksheet in Excel?

I would recommend you to use worksheet's index instead of using worksheet's name, in this way you can also loop through sheets "dynamically"

for i=1 to thisworkbook.sheets.count
 sheets(i).activate
'You can add more code 
with activesheet
 'Code...
end with
next i

It will also, improve performance.

How to build and run Maven projects after importing into Eclipse IDE

Dependencies can be updated by using "Maven --> Update Project.." in Eclipse using m2e plugin, after pom.xml file modification. Maven Project Update based on changes on pom.xml

Print the address or pointer for value in C

I believe this would be most correct.

printf("%p", (void *)emp1);
printf("%p", (void *)*emp1);

printf() is a variadic function and must be passed arguments of the right types. The standard says %p takes void *.

"inconsistent use of tabs and spaces in indentation"

Sublime Text 3

In Sublime Text, WHILE editing a Python file:

Sublime Text menu > Preferences > Settings - Syntax Specific :

Python.sublime-settings

{
    "tab_size": 4,
    "translate_tabs_to_spaces": true
}

Deleting all records in a database table

BlogPost.find_each(&:destroy)

Android camera intent

try this code

Intent photo= new Intent("android.media.action.IMAGE_CAPTURE");
                    startActivityForResult(photo, CAMERA_PIC_REQUEST);

Not Equal to This OR That in Lua

Your problem stems from a misunderstanding of the or operator that is common to people learning programming languages like this. Yes, your immediate problem can be solved by writing x ~= 0 and x ~= 1, but I'll go into a little more detail about why your attempted solution doesn't work.

When you read x ~=(0 or 1) or x ~= 0 or 1 it's natural to parse this as you would the sentence "x is not equal to zero or one". In the ordinary understanding of that statement, "x" is the subject, "is not equal to" is the predicate or verb phrase, and "zero or one" is the object, a set of possibilities joined by a conjunction. You apply the subject with the verb to each item in the set.

However, Lua does not parse this based on the rules of English grammar, it parses it in binary comparisons of two elements based on its order of operations. Each operator has a precedence which determines the order in which it will be evaluated. or has a lower precedence than ~=, just as addition in mathematics has a lower precedence than multiplication. Everything has a lower precedence than parentheses.

As a result, when evaluating x ~=(0 or 1), the interpreter will first compute 0 or 1 (because of the parentheses) and then x ~= the result of the first computation, and in the second example, it will compute x ~= 0 and then apply the result of that computation to or 1.

The logical operator or "returns its first argument if this value is different from nil and false; otherwise, or returns its second argument". The relational operator ~= is the inverse of the equality operator ==; it returns true if its arguments are different types (x is a number, right?), and otherwise compares its arguments normally.

Using these rules, x ~=(0 or 1) will decompose to x ~= 0 (after applying the or operator) and this will return 'true' if x is anything other than 0, including 1, which is undesirable. The other form, x ~= 0 or 1 will first evaluate x ~= 0 (which may return true or false, depending on the value of x). Then, it will decompose to one of false or 1 or true or 1. In the first case, the statement will return 1, and in the second case, the statement will return true. Because control structures in Lua only consider nil and false to be false, and anything else to be true, this will always enter the if statement, which is not what you want either.

There is no way that you can use binary operators like those provided in programming languages to compare a single variable to a list of values. Instead, you need to compare the variable to each value one by one. There are a few ways to do this. The simplest way is to use De Morgan's laws to express the statement 'not one or zero' (which can't be evaluated with binary operators) as 'not one and not zero', which can trivially be written with binary operators:

if x ~= 1 and x ~= 0 then
    print( "X must be equal to 1 or 0" )
    return
end

Alternatively, you can use a loop to check these values:

local x_is_ok = false
for i = 0,1 do 
    if x == i then
        x_is_ok = true
    end
end
if not x_is_ok then
    print( "X must be equal to 1 or 0" )
    return
end

Finally, you could use relational operators to check a range and then test that x was an integer in the range (you don't want 0.5, right?)

if not (x >= 0 and x <= 1 and math.floor(x) == x) then
    print( "X must be equal to 1 or 0" )
    return
end

Note that I wrote x >= 0 and x <= 1. If you understood the above explanation, you should now be able to explain why I didn't write 0 <= x <= 1, and what this erroneous expression would return!

What is the difference between utf8mb4 and utf8 charsets in MySQL?

MySQL added this utf8mb4 code after 5.5.3, Mb4 is the most bytes 4 meaning, specifically designed to be compatible with four-byte Unicode. Fortunately, UTF8MB4 is a superset of UTF8, except that there is no need to convert the encoding to UTF8MB4. Of course, in order to save space, the general use of UTF8 is enough.

The original UTF-8 format uses one to six bytes and can encode 31 characters maximum. The latest UTF-8 specification uses only one to four bytes and can encode up to 21 bits, just to represent all 17 Unicode planes. UTF8 is a character set in Mysql that supports only a maximum of three bytes of UTF-8 characters, which is the basic multi-text plane in Unicode.

To save 4-byte-long UTF-8 characters in Mysql, you need to use the UTF8MB4 character set, but only 5.5. After 3 versions are supported (View version: Select version ();). I think that in order to get better compatibility, you should always use UTF8MB4 instead of UTF8. For char type data, UTF8MB4 consumes more space and, according to Mysql's official recommendation, uses VARCHAR instead of char.

In MariaDB utf8mb4 as the default CHARSET when it not set explicitly in the server config, hence COLLATE utf8mb4_unicode_ci is used.

Refer MariaDB CHARSET & COLLATE Click

CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

"Invalid signature file" when attempting to run a .jar

I've recently started using IntelliJ on my projects. However, some of my colleagues still use Eclipse on the same projects. Today, I've got the very same error after executing the jar-file created by my IntelliJ. While all the solutions in here talking about almost the same thing, none of them worked for me easily (possibly because I don't use ANT, maven build gave me other errors which referred me to http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException, and also I couldn't figure out what are the signed jars by myself!)

Finally, this helped me

zip -d demoSampler.jar 'META-INF/*.SF' 'META-INF/*.RSA' 'META-INF/*SF'

Guess what's been removed from my jar file?!

deleting: META-INF/ECLIPSE_.SF 
deleting: META-INF/ECLIPSE_.RSA

It seems that the issue was relevant to some eclipse-relevant files.

How to correctly link php-fpm and Nginx Docker containers?

Don't hardcode ip of containers in nginx config, docker link adds the hostname of the linked machine to the hosts file of the container and you should be able to ping by hostname.

EDIT: Docker 1.9 Networking no longer requires you to link containers, when multiple containers are connected to the same network, their hosts file will be updated so they can reach each other by hostname.

Every time a docker container spins up from an image (even stop/start-ing an existing container) the containers get new ip's assigned by the docker host. These ip's are not in the same subnet as your actual machines.

see docker linking docs (this is what compose uses in the background)

but more clearly explained in the docker-compose docs on links & expose

links

links:
 - db
 - db:database
 - redis

An entry with the alias' name will be created in /etc/hosts inside containers for this service, e.g:

172.17.2.186  db
172.17.2.186  database
172.17.2.187  redis

expose

Expose ports without publishing them to the host machine - they'll only be accessible to linked services. Only the internal port can be specified.

and if you set up your project to get the ports + other credentials through environment variables, links automatically set a bunch of system variables:

To see what environment variables are available to a service, run docker-compose run SERVICE env.

name_PORT

Full URL, e.g. DB_PORT=tcp://172.17.0.5:5432

name_PORT_num_protocol

Full URL, e.g. DB_PORT_5432_TCP=tcp://172.17.0.5:5432

name_PORT_num_protocol_ADDR

Container's IP address, e.g. DB_PORT_5432_TCP_ADDR=172.17.0.5

name_PORT_num_protocol_PORT

Exposed port number, e.g. DB_PORT_5432_TCP_PORT=5432

name_PORT_num_protocol_PROTO

Protocol (tcp or udp), e.g. DB_PORT_5432_TCP_PROTO=tcp

name_NAME

Fully qualified container name, e.g. DB_1_NAME=/myapp_web_1/myapp_db_1

Access a JavaScript variable from PHP

JS ist browser-based, PHP is server-based. You have to generate some browser-based request/signal to get the data from the JS into the PHP. Take a look into Ajax.

jQuery send string as POST parameters

Not sure whether this is still actual.. just for future readers. If what you really want is to pass your parameters as part of the URL, you should probably use jQuery.param().

Remove Null Value from String array in java

Using Google's guava library

String[] firstArray = {"test1","","test2","test4","",null};

Iterable<String> st=Iterables.filter(Arrays.asList(firstArray),new Predicate<String>() {
    @Override
    public boolean apply(String arg0) {
        if(arg0==null) //avoid null strings 
            return false;
        if(arg0.length()==0) //avoid empty strings 
            return false;
        return true; // else true
    }
});

Accessing Object Memory Address

I know this is an old question but if you're still programming, in python 3 these days... I have actually found that if it is a string, then there is a really easy way to do this:

>>> spam.upper
<built-in method upper of str object at 0x1042e4830>
>>> spam.upper()
'YO I NEED HELP!'
>>> id(spam)
4365109296

string conversion does not affect location in memory either:

>>> spam = {437 : 'passphrase'}
>>> object.__repr__(spam)
'<dict object at 0x1043313f0>'
>>> str(spam)
"{437: 'passphrase'}"
>>> object.__repr__(spam)
'<dict object at 0x1043313f0>'

Copy Notepad++ text with formatting?

For those who do not see Plugins->NPPExport,

Download Plugin Manager from this. Extract contents and place under C/ProgramFile/NP++ installation, plugins & updater folder. Restart NP++. You should be able to see Plugins->Plugin Manager then. You can download any plugin, including NPPExport and install it to see the Copy command.

Store multiple values in single key in json

{
    "success": true,
    "data": {
        "BLR": {
            "origin": "JAI",
            "destination": "BLR",
            "price": 127,
            "transfers": 0,
            "airline": "LB",
            "flight_number": 655,
            "departure_at": "2017-06-03T18:20:00Z",
            "return_at": "2017-06-07T08:30:00Z",
            "expires_at": "2017-03-05T08:40:31Z"
        }
    }
};

how to break the _.each function in underscore.js

Update:

You can actually "break" by throwing an error inside and catching it outside: something like this:

try{
  _([1,2,3]).each(function(v){
    if (v==2) throw new Error('break');
  });
}catch(e){
  if(e.message === 'break'){
    //break successful
  }
}

This obviously has some implications regarding any other exceptions that your code trigger in the loop, so use with caution!

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

Hi I know this topic is old but there is a much better way to differentiate an Array in Node.js from any other Object have a look at the docs.

var util = require('util');

util.isArray([]); // true
util.isArray({}); // false

var obj = {};
typeof obj === "Object" // true

What underlies this JavaScript idiom: var self = this?

As others have explained, var self = this; allows code in a closure to refer back to the parent scope.

However, it's now 2018 and ES6 is widely supported by all major web browsers. The var self = this; idiom isn't quite as essential as it once was.

It's now possible to avoid var self = this; through the use of arrow functions.

In instances where we would have used var self = this:

function test() {
    var self = this;
    this.hello = "world";
    document.getElementById("test_btn").addEventListener("click", function() {
        console.log(self.hello); // logs "world"
    });
};

We can now use an arrow function without var self = this:

function test() {
    this.hello = "world";
    document.getElementById("test_btn").addEventListener("click", () => {
        console.log(this.hello); // logs "world"
    });
};

Arrow functions do not have their own this and simply assume the enclosing scope.

java: ArrayList - how can I check if an index exists?

Since java-9 there is a standard way of checking if an index belongs to the array - Objects#checkIndex() :

List<Integer> ints = List.of(1,2,3);
System.out.println(Objects.checkIndex(1,ints.size())); // 1
System.out.println(Objects.checkIndex(10,ints.size())); //IndexOutOfBoundsException

What are the main performance differences between varchar and nvarchar SQL Server data types?

I deal with this question at work often:

  • FTP feeds of inventory and pricing - Item descriptions and other text were in nvarchar when varchar worked fine. Converting these to varchar reduced file size almost in half and really helped with uploads.

  • The above scenario worked fine until someone put a special character in the item description (maybe trademark, can't remember)

I still do not use nvarchar every time over varchar. If there is any doubt or potential for special characters, I use nvarchar. I find I use varchar mostly when I am in 100% control of what is populating the field.

What is the maximum number of characters that nvarchar(MAX) will hold?

2^31-1 bytes. So, a little less than 2^31-1 characters for varchar(max) and half that for nvarchar(max).

nchar and nvarchar

How to detect a route change in Angular?

Angular 7, if you want to subscribe to router

import { Router, NavigationEnd } from '@angular/router';

import { filter } from 'rxjs/operators';

constructor(
  private router: Router
) {
  router.events.pipe(
    filter(event => event instanceof NavigationEnd)  
  ).subscribe((event: NavigationEnd) => {
    console.log(event.url);
  });
}

How to create PDFs in an Android app?

If you are developing for devices with API level 19 or higher you can use the built in PrintedPdfDocument: http://developer.android.com/reference/android/print/pdf/PrintedPdfDocument.html

// open a new document
PrintedPdfDocument document = new PrintedPdfDocument(context,
     printAttributes);

// start a page
Page page = document.startPage(0);

// draw something on the page
View content = getContentView();
content.draw(page.getCanvas());

// finish the page
document.finishPage(page);
. . .
// add more pages
. . .
// write the document content
document.writeTo(getOutputStream());

//close the document
document.close();

html5 input for money/currency

Using javascript's Number.prototype.toLocaleString:

_x000D_
_x000D_
var currencyInput = document.querySelector('input[type="currency"]')
var currency = 'GBP' // https://www.currency-iso.org/dam/downloads/lists/list_one.xml

 // format inital value
onBlur({target:currencyInput})

// bind event listeners
currencyInput.addEventListener('focus', onFocus)
currencyInput.addEventListener('blur', onBlur)


function localStringToNumber( s ){
  return Number(String(s).replace(/[^0-9.-]+/g,""))
}

function onFocus(e){
  var value = e.target.value;
  e.target.value = value ? localStringToNumber(value) : ''
}

function onBlur(e){
  var value = e.target.value

  var options = {
      maximumFractionDigits : 2,
      currency              : currency,
      style                 : "currency",
      currencyDisplay       : "symbol"
  }
  
  e.target.value = (value || value === 0) 
    ? localStringToNumber(value).toLocaleString(undefined, options)
    : ''
}
_x000D_
input{
  padding: 10px;
  font: 20px Arial;
  width: 70%;
}
_x000D_
<input type='currency' value="123" placeholder='Type a number & click outside' />
_x000D_
_x000D_
_x000D_

Here's a very simple demo illustrating the above method (HTML-only)


I've made a tiny React component if anyone's interested

Maven Jacoco Configuration - Exclude classes/packages from report not working

Though Andrew already answered question with details , i am giving code how to exclude it in pom

           <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>0.7.9</version>
                <configuration>
                    <excludes>
                        <exclude>**/*com/test/vaquar/khan/HealthChecker.class</exclude>
                    </excludes>
                </configuration>
                <executions>
                    <!-- prepare agent for measuring integration tests -->
                    <execution>
                        <id>jacoco-initialize</id>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>jacoco-site</id>
                        <phase>package</phase>
                        <goals>
                            <goal>report</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

For Springboot application

<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>sonar-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.sonarsource.scanner.maven</groupId>
                <artifactId>sonar-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                       <!-- Exclude class from test coverage -->
                        <exclude>**/*com/khan/vaquar/Application.class</exclude>
                        <!-- Exclude full package from test coverage -->
                        <exclude>**/*com/khan/vaquar/config/**</exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

How to convert an iterator to a stream?

Create Spliterator from Iterator using Spliterators class contains more than one function for creating spliterator, for example here am using spliteratorUnknownSize which is getting iterator as parameter, then create Stream using StreamSupport

Spliterator<Model> spliterator = Spliterators.spliteratorUnknownSize(
        iterator, Spliterator.NONNULL);
Stream<Model> stream = StreamSupport.stream(spliterator, false);

Event for Handling the Focus of the EditText

  1. Declare object of EditText on top of class:

     EditText myEditText;
    
  2. Find EditText in onCreate Function and setOnFocusChangeListener of EditText:

    myEditText = findViewById(R.id.yourEditTextNameInxml); 
    
    myEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View view, boolean hasFocus) {
                    if (!hasFocus) {
                         Toast.makeText(this, "Focus Lose", Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(this, "Get Focus", Toast.LENGTH_SHORT).show();
                    }
    
                }
            });
    

It works fine.

How to detect reliably Mac OS X, iOS, Linux, Windows in C preprocessor?

There are predefined macros that are used by most compilers, you can find the list here. GCC compiler predefined macros can be found here. Here is an example for gcc:

#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
   //define something for Windows (32-bit and 64-bit, this part is common)
   #ifdef _WIN64
      //define something for Windows (64-bit only)
   #else
      //define something for Windows (32-bit only)
   #endif
#elif __APPLE__
    #include <TargetConditionals.h>
    #if TARGET_IPHONE_SIMULATOR
         // iOS Simulator
    #elif TARGET_OS_IPHONE
        // iOS device
    #elif TARGET_OS_MAC
        // Other kinds of Mac OS
    #else
    #   error "Unknown Apple platform"
    #endif
#elif __linux__
    // linux
#elif __unix__ // all unices not caught above
    // Unix
#elif defined(_POSIX_VERSION)
    // POSIX
#else
#   error "Unknown compiler"
#endif

The defined macros depend on the compiler that you are going to use.

The _WIN64 #ifdef can be nested into the _WIN32 #ifdef because _WIN32 is even defined when targeting the Windows x64 version. This prevents code duplication if some header includes are common to both (also WIN32 without underscore allows IDE to highlight the right partition of code).

HTML table with horizontal scrolling (first column fixed)

Use jQuery DataTables plug-in, it supports fixed header and columns. This example adds fixed column support to the html table "example":

http://datatables.net/extensions/fixedcolumns/

For two fixed columns:

http://www.datatables.net/release-datatables/extensions/FixedColumns/examples/two_columns.html

Compiling and Running Java Code in Sublime Text 2

This is mine using sublime text 3. I needed the option to open the command prompt in a new window. Java compile is used with the -Xlint option to turn on full messages for warnings in Java.

I have saved the file in my user package folder as Java(Build).sublime-build

{
     "shell_cmd": "javac -Xlint \"${file}\"",
     "file_regex": "^(...*?):([0-9]*):?([0-9]*)",
     "working_dir": "${file_path}",
     "selector": "source.java",
     "variants":
     [
          {
               "name": "Run",
                "shell_cmd": "java \"${file_base_name}\"",
          },
          {
               "name": "Run (External CMD Window)",
               "shell_cmd": "start cmd /k java \"${file_base_name}\""
          }
     ]
}

What could cause java.lang.reflect.InvocationTargetException?

From the Javadoc of Method.invoke()

Throws: InvocationTargetException - if the underlying method throws an exception.

This exception is thrown if the method called threw an exception.

How to set an button align-right with Bootstrap?

This work for me in bootstrap 4:

    <div class="alert alert-info">
      <a href="#" class="alert-link">Summary:Its some description.......testtesttest</a>  
      <button type="button" class="btn btn-primary btn-lg float-right">Large button</button>
    </div>

Set Date in a single line

Calendar has a set() method that can set the year, month, and day-of-month in one call:

myCal.set( theYear, theMonth, theDay );

How to distinguish mouse "click" and "drag"

Another solution for class based vanilla JS using a distance threshold

private initDetectDrag(element) {
    let clickOrigin = { x: 0, y: 0 };
    const dragDistanceThreshhold = 20;

    element.addEventListener('mousedown', (event) => {
        this.isDragged = false
        clickOrigin = { x: event.clientX, y: event.clientY };
    });
    element.addEventListener('mousemove', (event) => {
        if (Math.sqrt(Math.pow(clickOrigin.y - event.clientY, 2) + Math.pow(clickOrigin.x - event.clientX, 2)) > dragDistanceThreshhold) {
            this.isDragged = true
        }
    });
}

Add inside the class (SOMESLIDER_ELEMENT can also be document to be global):

private isDragged: boolean;
constructor() {
    this.initDetectDrag(SOMESLIDER_ELEMENT);
    this.doSomeSlideStuff(SOMESLIDER_ELEMENT);
    element.addEventListener('click', (event) => {
        if (!this.sliderIsDragged) {
            console.log('was clicked');
        } else {
            console.log('was dragged, ignore click or handle this');
        }
    }, false);
}

What’s the best way to reload / refresh an iframe?

window.frames['frameNameOrIndex'].location.reload();

NOT IN vs NOT EXISTS

I always default to NOT EXISTS.

The execution plans may be the same at the moment but if either column is altered in the future to allow NULLs the NOT IN version will need to do more work (even if no NULLs are actually present in the data) and the semantics of NOT IN if NULLs are present are unlikely to be the ones you want anyway.

When neither Products.ProductID or [Order Details].ProductID allow NULLs the NOT IN will be treated identically to the following query.

SELECT ProductID,
       ProductName
FROM   Products p
WHERE  NOT EXISTS (SELECT *
                   FROM   [Order Details] od
                   WHERE  p.ProductId = od.ProductId) 

The exact plan may vary but for my example data I get the following.

Neither NULL

A reasonably common misconception seems to be that correlated sub queries are always "bad" compared to joins. They certainly can be when they force a nested loops plan (sub query evaluated row by row) but this plan includes an anti semi join logical operator. Anti semi joins are not restricted to nested loops but can use hash or merge (as in this example) joins too.

/*Not valid syntax but better reflects the plan*/ 
SELECT p.ProductID,
       p.ProductName
FROM   Products p
       LEFT ANTI SEMI JOIN [Order Details] od
         ON p.ProductId = od.ProductId 

If [Order Details].ProductID is NULL-able the query then becomes

SELECT ProductID,
       ProductName
FROM   Products p
WHERE  NOT EXISTS (SELECT *
                   FROM   [Order Details] od
                   WHERE  p.ProductId = od.ProductId)
       AND NOT EXISTS (SELECT *
                       FROM   [Order Details]
                       WHERE  ProductId IS NULL) 

The reason for this is that the correct semantics if [Order Details] contains any NULL ProductIds is to return no results. See the extra anti semi join and row count spool to verify this that is added to the plan.

One NULL

If Products.ProductID is also changed to become NULL-able the query then becomes

SELECT ProductID,
       ProductName
FROM   Products p
WHERE  NOT EXISTS (SELECT *
                   FROM   [Order Details] od
                   WHERE  p.ProductId = od.ProductId)
       AND NOT EXISTS (SELECT *
                       FROM   [Order Details]
                       WHERE  ProductId IS NULL)
       AND NOT EXISTS (SELECT *
                       FROM   (SELECT TOP 1 *
                               FROM   [Order Details]) S
                       WHERE  p.ProductID IS NULL) 

The reason for that one is because a NULL Products.ProductId should not be returned in the results except if the NOT IN sub query were to return no results at all (i.e. the [Order Details] table is empty). In which case it should. In the plan for my sample data this is implemented by adding another anti semi join as below.

Both NULL

The effect of this is shown in the blog post already linked by Buckley. In the example there the number of logical reads increase from around 400 to 500,000.

Additionally the fact that a single NULL can reduce the row count to zero makes cardinality estimation very difficult. If SQL Server assumes that this will happen but in fact there were no NULL rows in the data the rest of the execution plan may be catastrophically worse, if this is just part of a larger query, with inappropriate nested loops causing repeated execution of an expensive sub tree for example.

This is not the only possible execution plan for a NOT IN on a NULL-able column however. This article shows another one for a query against the AdventureWorks2008 database.

For the NOT IN on a NOT NULL column or the NOT EXISTS against either a nullable or non nullable column it gives the following plan.

Not EXists

When the column changes to NULL-able the NOT IN plan now looks like

Not In - Null

It adds an extra inner join operator to the plan. This apparatus is explained here. It is all there to convert the previous single correlated index seek on Sales.SalesOrderDetail.ProductID = <correlated_product_id> to two seeks per outer row. The additional one is on WHERE Sales.SalesOrderDetail.ProductID IS NULL.

As this is under an anti semi join if that one returns any rows the second seek will not occur. However if Sales.SalesOrderDetail does not contain any NULL ProductIDs it will double the number of seek operations required.

PHP Adding 15 minutes to Time value

Current date and time

$current_date_time = date('Y-m-d H:i:s');

15 min ago Date and time

$newTime = date("Y-m-d H:i:s",strtotime("+15 minutes", strtotime($current_date)));

Creating default object from empty value in PHP?

Your new environment may have E_STRICT warnings enabled in error_reporting for PHP versions <= 5.3.x, or simply have error_reporting set to at least E_WARNING with PHP versions >= 5.4. That error is triggered when $res is NULL or not yet initialized:

$res = NULL;
$res->success = false; // Warning: Creating default object from empty value

PHP will report a different error message if $res is already initialized to some value but is not an object:

$res = 33;
$res->success = false; // Warning: Attempt to assign property of non-object

In order to comply with E_STRICT standards prior to PHP 5.4, or the normal E_WARNING error level in PHP >= 5.4, assuming you are trying to create a generic object and assign the property success, you need to declare $res as an object of stdClass in the global namespace:

$res = new \stdClass();
$res->success = false;

Cannot change version of project facet Dynamic Web Module to 3.0?

In my case the web.xml was referenced by a dtd. After I changed this to xsd reference like the one posted by Sydney it worked.

Center the content inside a column in Bootstrap 4

_x000D_
_x000D_
.row>.col, .row>[class^=col-] {_x000D_
    padding-top: .75rem;_x000D_
    padding-bottom: .75rem;_x000D_
    background-color: rgba(86,61,124,.15);_x000D_
    border: 1px solid rgba(86,61,124,.2);_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="container">_x000D_
  <div class="row justify-content-md-center">_x000D_
    <div class="col col-lg-2">_x000D_
      1 of 3_x000D_
    </div>_x000D_
    <div class="col col-lg-2">_x000D_
      1 of 2_x000D_
    </div>_x000D_
    <div class="col col-lg-2">_x000D_
      3 of 3_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to Merge Two Eloquent Collections?

$users = User::all();
$associates = Associate::all();

$userAndAssociate = $users->merge($associates);

How to get the connection String from a database

SqlConnection con = new SqlConnection();
con.ConnectionString="Data Source=DOTNET-PC\\SQLEXPRESS;Initial Catalog=apptivator;Integrated Security=True";

Difference between xcopy and robocopy

The differences I could see is that Robocopy has a lot more options, but I didn't find any of them particularly helpful unless I'm doing something special.

I did some benchmarking of several copy routines and found XCOPY and ROBOCOPY to be the fastest, but to my surprise, XCOPY consistently edged out Robocopy.

It's ironic that robocopy retries a copy that fails, but it also failed a lot in my benchmark tests, where xcopy never did.

I did full file (byte by byte) file compares after my benchmark tests.

Here are the switches I used with robocopy in my tests:

 **"/E /R:1 /W:1 /NP /NFL /NDL"**.  

If anyone knows a faster combination (other than removing /E, which I need), I'd love to hear.

Another interesting/disappointing thing with robocopy is that if a copy does fail, by default it retries 1,000,000 times with a 30 second delay between each try. If you are running a long batch file unattended, you may be very disappointed when you come back after a few hours to find it's still trying to copy a particular file.

The /R and /W switches let you change this behavior.

  • With /R you can tell it how many times to retry,
  • /W let's you specify the wait time before retries.

If there's a way to attach files here, I can share my results.

  • My tests were all done on the same computer and
  • copied files from one external drive to another external,
  • both on USB 3.0 ports.

I also included FastCopy and Windows Copy in my tests and each test was run 10 times. Note, the differences were pretty significant. The 95% confidence intervals had no overlap.

What is the difference between MacVim and regular Vim?

unfortunately, with "mvim -v", ALT plus arrow windows still does not work. I have not found any way to enable it :-(

Better way to right align text in HTML Table

Use jquery to apply class to all tr unobtrusively.

$(”table td”).addClass(”right-align-class");

Use enhanced filters on td in case you want to select a particular td.

See jquery

Handler "ExtensionlessUrlHandler-Integrated-4.0" has a bad module "ManagedPipelineHandler" in its module list

Making this its own post because this had me going for hours.

I saw maybe a dozen of similar posts here and elsewhere about this problema and the aspnet_regiis fix. They weren't working for me, and aspnet_regiis was acting odd, just listing options etc.

As user ryan-anderson above indicated, you cannot enter .exe

For those less comfy with things outside IIS on the server, here's what you do in simple steps.

  1. Find aspnet_regiis in a folder similar to this path. c:\Windows\Microsoft.NET\Framework\v4.0.30319\

  2. Right-click command prompt in the start menu or wherever and tell it to run as administrator. Using the windows "Run" feature just won't work, or didn't for me.

  3. Go back to the aspnet_regiis executable. Click-drag it right into the command prompt or copy-paste the address into the command prompt.

  4. Remove, if it's there, the .exe at the end. This is key. Add the -i (space minus eye) at the end. Enter.

If you did this correctly, you will see that it starts to install asp.net, and then tells you it succeeded.

babel-loader jsx SyntaxError: Unexpected token

You can find a really good boilerplate made by Henrik Joreteg (ampersandjs) here: https://github.com/HenrikJoreteg/hjs-webpack

Then in your webpack.config.js

var getConfig = require('hjs-webpack')

module.exports = getConfig({
  in: 'src/index.js',
  out: 'public',
  clearBeforeBuild: true,
  https: process.argv.indexOf('--https') !== -1
})

Working copy XXX locked and cleanup failed in SVN

Spotlight is its usual rubbish self at finding the lock files recursively.

EasyFind on Mac App Store works

http://itunes.apple.com/gb/app/easyfind/id411673888?mt=12

search for 'lock'

Select all / Delete

How can I increase the size of a bootstrap button?

You can add your own css property for button size as follows:

.btn {
    min-width: 250px;
}

Saving timestamp in mysql table using php

Better is use datatype varchar(15).

How to place div in top right hand corner of page

Try css:

.topcorner{
    position:absolute;
    top:10px;
    right: 10px;
 }

you can play with the top and right properties.

If you want to float the div even when you scroll down, just change position:absolute; to position:fixed;.

Hope it helps.

using extern template (C++11)

The known problem with the templates is code bloating, which is consequence of generating the class definition in each and every module which invokes the class template specialization. To prevent this, starting with C++0x, one could use the keyword extern in front of the class template specialization

#include <MyClass>
extern template class CMyClass<int>;

The explicit instantion of the template class should happen only in a single translation unit, preferable the one with template definition (MyClass.cpp)

template class CMyClass<int>;
template class CMyClass<float>;

How to send json data in the Http request using NSURLRequest

Here's what I do (please note that the JSON going to my server needs to be a dictionary with one value (another dictionary) for key = question..i.e. {:question => { dictionary } } ):

NSArray *objects = [NSArray arrayWithObjects:[[NSUserDefaults standardUserDefaults]valueForKey:@"StoreNickName"],
  [[UIDevice currentDevice] uniqueIdentifier], [dict objectForKey:@"user_question"],     nil];
NSArray *keys = [NSArray arrayWithObjects:@"nick_name", @"UDID", @"user_question", nil];
NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

NSDictionary *jsonDict = [NSDictionary dictionaryWithObject:questionDict forKey:@"question"];

NSString *jsonRequest = [jsonDict JSONRepresentation];

NSLog(@"jsonRequest is %@", jsonRequest);

NSURL *url = [NSURL URLWithString:@"https://xxxxxxx.com/questions"];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
             cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];


NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];

[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestData];

NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
 receivedData = [[NSMutableData data] retain];
}

The receivedData is then handled by:

NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [jsonString JSONValue];
NSDictionary *question = [jsonDict objectForKey:@"question"];

This isn't 100% clear and will take some re-reading, but everything should be here to get you started. And from what I can tell, this is asynchronous. My UI is not locked up while these calls are made. Hope that helps.

No Exception while type casting with a null in java

You can cast null to any reference type. You can also call methods which handle a null as an argument, e.g. System.out.println(Object) does, but you cannot reference a null value and call a method on it.

BTW There is a tricky situation where it appears you can call static methods on null values.

Thread t = null;
t.yield(); // Calls static method Thread.yield() so this runs fine.

How do I remove blue "selected" outline on buttons?

You can remove the blue outline by using outline: none.

However, I would highly recommend styling your focus states too. This is to help users who are visually impaired.

Check out: http://www.w3.org/TR/2008/REC-WCAG20-20081211/#navigation-mechanisms-focus-visible. More reading here: http://outlinenone.com

Build fails with "Command failed with a nonzero exit code"

If you are using a TabbController and a storyboard references, make sure that you have a starting point for that storyboard.

Function to get yesterday's date in Javascript in format DD/MM/YYYY

The problem here seems to be that you're reassigning $today by assigning a string to it:

$today = $dd+'/'+$mm+'/'+$yyyy;

Strings don't have getDate.

Also, $today.getDate()-1 just gives you the day of the month minus one; it doesn't give you the full date of 'yesterday'. Try this:

$today = new Date();
$yesterday = new Date($today);
$yesterday.setDate($today.getDate() - 1); //setDate also supports negative values, which cause the month to rollover.

Then just apply the formatting code you wrote:

var $dd = $yesterday.getDate();
var $mm = $yesterday.getMonth()+1; //January is 0!

var $yyyy = $yesterday.getFullYear();
if($dd<10){$dd='0'+$dd} if($mm<10){$mm='0'+$mm} $yesterday = $dd+'/'+$mm+'/'+$yyyy;

Because of the last statement, $yesterday is now a String (not a Date) containing the formatted date.

How to enable multidexing with the new Android Multidex support library

Here is an up-to-date approach as of October 2020, with Android X. This comes from Android's documentation, "Enable multidex for apps with over 64K methods."

For minSdk >= 21

You do not need to do anything. All of these devices use the Android RunTime (ART) VM, which supports multidex natively.

For minSdk < 21

In your module-level build.gradle, ensure that the following configurations are populated:

android {
    defaultConfig {
        multiDexEnabled true
    }
}

dependencies {
    implementation 'androidx.multidex:multidex:2.0.1'
}

You need to install explicit multidex support. The documentation includes three methods to do so, and you have to pick one.

For example, in your src/main/AndroidManifest.xml, you can declare MultiDexApplication as the application:name:

<manifest package="com.your.package"
          xmlns:android="http://schemas.android.com/apk/res/android">
    <application android:name="androidx.multidex.MultiDexApplication" />
</manifest>

Manually Triggering Form Validation using jQuery

I'm not sure it's worth it for me to type this all up from scratch since this article published in A List Apart does a pretty good job explaining it. MDN also has a handy guide for HTML5 forms and validation (covering the API and also the related CSS).

How to Update Multiple Array Elements in mongodb

You can update all elements in MongoDB

db.collectioname.updateOne(
{ "key": /vikas/i },
{ $set: { 
 "arr.$[].status" : "completed"
} }
)

It will update all the "status" value to "completed" in the "arr" Array

If Only one document

db.collectioname.updateOne(
 { key:"someunique", "arr.key": "myuniq" },
 { $set: { 
   "arr.$.status" : "completed", 
   "arr.$.msgs":  {
                "result" : ""
        }
   
 } }
)

But if not one and also you don't want all the documents in the array to update then you need to loop through the element and inside the if block

db.collectioname.find({findCriteria })
  .forEach(function (doc) {
    doc.arr.forEach(function (singlearr) {
      if (singlearr check) {
        singlearr.handled =0
      }
    });
    db.collection.save(doc);
  });

ArrayList insertion and retrieval order

If you always add to the end, then each element will be added to the end and stay that way until you change it.

If you always insert at the start, then each element will appear in the reverse order you added them.

If you insert them in the middle, the order will be something else.

how to get text from textview

You have to do the following:

a=a.replace("\n"," ");
a=a.trim();
String b[]=a.split("+");
int k=Integer.ValueOf(b[0]);
int l=Integer.ValueOf(b[1]);
int sum=k+l;

Rails 4 Authenticity Token

Add authenticity_token: true to the form tag

AWS EFS vs EBS vs S3 (differences & when to use?)

One word answer: MONEY :D

1 GB to store in US-East-1: (Updated at 2016.dec.20)

  • Glacier: $0.004/Month (Note: Major price cut in 2016)
  • S3: $0.023/Month
  • S3-IA (announced in 2015.09): $0.0125/Month (+$0.01/gig retrieval charge)
  • EBS: $0.045-0.1/Month (depends on speed - SSD or not) + IOPS costs
  • EFS: $0.3/Month

Further storage options, which may be used for temporary storing data while/before processing it:

  • SNS
  • SQS
  • Kinesis stream
  • DynamoDB, SimpleDB

The costs above are just samples. There can be differences by region, and it can change at any point. Also there are extra costs for data transfer (out to the internet). However they show a ratio between the prices of the services.

There are a lot more differences between these services:

EFS is:

  • Generally Available (out of preview), but may not yet be available in your region
  • Network filesystem (that means it may have bigger latency but it can be shared across several instances; even between regions)
  • It is expensive compared to EBS (~10x more) but it gives extra features.
  • It's a highly available service.
  • It's a managed service
  • You can attach the EFS storage to an EC2 Instance
  • Can be accessed by multiple EC2 instances simultaneously
  • Since 2016.dec.20 it's possible to attach your EFS storage directly to on-premise servers via Direct Connect. ()

EBS is:

  • A block storage (so you need to format it). This means you are able to choose which type of file system you want.
  • As it's a block storage, you can use Raid 1 (or 0 or 10) with multiple block storages
  • It is really fast
  • It is relatively cheap
  • With the new announcements from Amazon, you can store up to 16TB data per storage on SSD-s.
  • You can snapshot an EBS (while it's still running) for backup reasons
  • But it only exists in a particular region. Although you can migrate it to another region, you cannot just access it across regions (only if you share it via the EC2; but that means you have a file server)
  • You need an EC2 instance to attach it to
  • New feature (2017.Feb.15): You can now increase volume size, adjust performance, or change the volume type while the volume is in use. You can continue to use your application while the change takes effect.

S3 is:

  • An object store (not a file system).
  • You can store files and "folders" but can't have locks, permissions etc like you would with a traditional file system
  • This means, by default you can't just mount S3 and use it as your webserver
  • But it's perfect for storing your images and videos for your website
  • Great for short term archiving (e.g. a few weeks). It's good for long term archiving too, but Glacier is more cost efficient.
  • Great for storing logs
  • You can access the data from every region (extra costs may apply)
  • Highly Available, Redundant. Basically data loss is not possible (99.999999999% durability, 99.9 uptime SLA)
  • Much cheaper than EBS.
  • You can serve the content directly to the internet, you can even have a full (static) website working direct from S3, without an EC2 instance

Glacier is:

  • Long term archive storage
  • Extremely cheap to store
  • Potentially very expensive to retrieve
  • Takes up to 4 hours to "read back" your data (so only store items you know you won't need to retrieve for a long time)

As it got mentioned in JDL's comment, there are several interesting aspects in terms of pricing. For example Glacier, S3, EFS allocates the storage for you based on your usage, while at EBS you need to predefine the allocated storage. Which means, you need to over estimate. ( However it's easy to add more storage to your EBS volumes, it requires some engineering, which means you always "overpay" your EBS storage, which makes it even more expensive.)

Source: AWS Storage Update – New Lower Cost S3 Storage Option & Glacier Price Reduction

Creating SolidColorBrush from hex color value

If you don't want to deal with the pain of the conversion every time simply create an extension method.

public static class Extensions
{
    public static SolidColorBrush ToBrush(this string HexColorString)
    {
        return (SolidColorBrush)(new BrushConverter().ConvertFrom(HexColorString));
    }    
}

Then use like this: BackColor = "#FFADD8E6".ToBrush()

Alternately if you could provide a method to do the same thing.

public SolidColorBrush BrushFromHex(string hexColorString)
{
    return (SolidColorBrush)(new BrushConverter().ConvertFrom(hexColorString));
}

BackColor = BrushFromHex("#FFADD8E6");

Cannot get to $rootScope

I don't suggest you to use syntax like you did. AngularJs lets you to have different functionalities as you want (run, config, service, factory, etc..), which are more professional.In this function you don't even have to inject that by yourself like

MainCtrl.$inject = ['$scope', '$rootScope', '$location', 'socket', ...];

you can use it, as you know.

How to get files in a relative path in C#

string currentDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
string archiveFolder = Path.Combine(currentDirectory, "archive");
string[] files = Directory.GetFiles(archiveFolder, "*.zip");

The first parameter is the path. The second is the search pattern you want to use.

Difference between "enqueue" and "dequeue"

Enqueue and Dequeue tend to be operations on a queue, a data structure that does exactly what it sounds like it does.

You enqueue items at one end and dequeue at the other, just like a line of people queuing up for tickets to the latest Taylor Swift concert (I was originally going to say Billy Joel but that would date me severely).

There are variations of queues such as double-ended ones where you can enqueue and dequeue at either end but the vast majority would be the simpler form:

           +---+---+---+
enqueue -> | 3 | 2 | 1 | -> dequeue
           +---+---+---+

That diagram shows a queue where you've enqueued the numbers 1, 2 and 3 in that order, without yet dequeuing any.


By way of example, here's some Python code that shows a simplistic queue in action, with enqueue and dequeue functions. Were it more serious code, it would be implemented as a class but it should be enough to illustrate the workings:

import random

def enqueue(lst, itm):
    lst.append(itm)        # Just add item to end of list.
    return lst             # And return list (for consistency with dequeue).

def dequeue(lst):
    itm = lst[0]           # Grab the first item in list.
    lst = lst[1:]          # Change list to remove first item.
    return (itm, lst)      # Then return item and new list.

# Test harness. Start with empty queue.

myList = []

# Enqueue or dequeue a bit, with latter having probability of 10%.

for _ in range(15):
    if random.randint(0, 9) == 0 and len(myList) > 0:
        (itm, myList) = dequeue(myList)
        print(f"Dequeued {itm} to give {myList}")
    else:
        itm = 10 * random.randint(1, 9)
        myList = enqueue(myList, itm)
        print(f"Enqueued {itm} to give {myList}")

# Now dequeue remainder of list.

print("========")
while len(myList) > 0:
    (itm, myList) = dequeue(myList)
    print(f"Dequeued {itm} to give {myList}")

A sample run of that shows it in operation:

Enqueued 70 to give [70]
Enqueued 20 to give [70, 20]
Enqueued 40 to give [70, 20, 40]
Enqueued 50 to give [70, 20, 40, 50]
Dequeued 70 to give [20, 40, 50]
Enqueued 20 to give [20, 40, 50, 20]
Enqueued 30 to give [20, 40, 50, 20, 30]
Enqueued 20 to give [20, 40, 50, 20, 30, 20]
Enqueued 70 to give [20, 40, 50, 20, 30, 20, 70]
Enqueued 20 to give [20, 40, 50, 20, 30, 20, 70, 20]
Enqueued 20 to give [20, 40, 50, 20, 30, 20, 70, 20, 20]
Dequeued 20 to give [40, 50, 20, 30, 20, 70, 20, 20]
Enqueued 80 to give [40, 50, 20, 30, 20, 70, 20, 20, 80]
Dequeued 40 to give [50, 20, 30, 20, 70, 20, 20, 80]
Enqueued 90 to give [50, 20, 30, 20, 70, 20, 20, 80, 90]
========
Dequeued 50 to give [20, 30, 20, 70, 20, 20, 80, 90]
Dequeued 20 to give [30, 20, 70, 20, 20, 80, 90]
Dequeued 30 to give [20, 70, 20, 20, 80, 90]
Dequeued 20 to give [70, 20, 20, 80, 90]
Dequeued 70 to give [20, 20, 80, 90]
Dequeued 20 to give [20, 80, 90]
Dequeued 20 to give [80, 90]
Dequeued 80 to give [90]
Dequeued 90 to give []

Change the color of a bullet in a html list?

This was impossible in 2008, but it's becoming possible soon (hopefully)!

According to The W3C CSS3 specification, you can have full control over any number, glyph, or other symbol generated before a list item with the ::marker pseudo-element. To apply this to the most voted answer's solution:

<ul>
  <li>item #1</li>
  <li>item #2</li>
  <li>item #3</li>
</ul>

li::marker {
  color: red; /* bullet color */
}
li {
  color: black /* text color */
}

JSFiddle Example

Note, though, that as of July 2016, this solution is only a part of the W3C Working Draft and does not work in any major browsers, yet.

If you want this feature, do these:

How to create a file in Linux from terminal window?

Depending on what you want the file to contain:

  • touch /path/to/file for an empty file
  • somecommand > /path/to/file for a file containing the output of some command.

      eg: grep --help > randomtext.txt
          echo "This is some text" > randomtext.txt
    
  • nano /path/to/file or vi /path/to/file (or any other editor emacs,gedit etc)
    It either opens the existing one for editing or creates & opens the empty file to enter, if it doesn't exist


Create the file using cat

$ cat > myfile.txt

Now, just type whatever you want in the file:

Hello World!

CTRL-D to save and exit


There are several possible solutions:

Create an empty file

touch file

>file

echo -n > file

printf '' > file

The echo version will work only if your version of echo supports the -n switch to suppress newlines. This is a non-standard addition. The other examples will all work in a POSIX shell.

Create a file containing a newline and nothing else

echo '' > file

printf '\n' > file

This is a valid "text file" because it ends in a newline.

Write text into a file

"$EDITOR" file

echo 'text' > file

cat > file <<END \
text
END

printf 'text\n' > file

These are equivalent. The $EDITOR command assumes that you have an interactive text editor defined in the EDITOR environment variable and that you interactively enter equivalent text. The cat version presumes a literal newline after the \ and after each other line. Other than that these will all work in a POSIX shell.

Of course there are many other methods of writing and creating files, too.

How to create id with AUTO_INCREMENT on Oracle?

SYS_GUID returns a GUID-- a globally unique ID. A SYS_GUID is a RAW(16). It does not generate an incrementing numeric value.

If you want to create an incrementing numeric key, you'll want to create a sequence.

CREATE SEQUENCE name_of_sequence
  START WITH 1
  INCREMENT BY 1
  CACHE 100;

You would then either use that sequence in your INSERT statement

INSERT INTO name_of_table( primary_key_column, <<other columns>> )
  VALUES( name_of_sequence.nextval, <<other values>> );

Or you can define a trigger that automatically populates the primary key value using the sequence

CREATE OR REPLACE TRIGGER trigger_name
  BEFORE INSERT ON table_name
  FOR EACH ROW
BEGIN
  SELECT name_of_sequence.nextval
    INTO :new.primary_key_column
    FROM dual;
END;

If you are using Oracle 11.1 or later, you can simplify the trigger a bit

CREATE OR REPLACE TRIGGER trigger_name
  BEFORE INSERT ON table_name
  FOR EACH ROW
BEGIN
  :new.primary_key_column := name_of_sequence.nextval;
END;

If you really want to use SYS_GUID

CREATE TABLE table_name (
  primary_key_column raw(16) default sys_guid() primary key,
  <<other columns>>
)

how to align img inside the div to the right?

vertical-align:middle; text-align:right;

wamp server does not start: Windows 7, 64Bit

Follow these steps (taken from this Youtube video).

  1. Quit Skype
  2. Uninstall IIS
    • Go to control panel
    • Refer to PROGRAMS AND FEATURES
    • Go to TURN WINDOWS FEATURES ON OR OFF
    • Look for INTERNET information service
    • Uninstall

Convert multiple rows into one with comma as separator

A clean and flexible solution in MS SQL Server 2005/2008 is to create a CLR Agregate function.

You'll find quite a few articles (with code) on google.

It looks like this article walks you through the whole process using C#.

Adding a SVN repository in Eclipse

In my case was an access issue. I needed to change the protocol to svn+ssh instead of http.

For example, instead of http://svn.python.org/projects/peps/trunk

try svn+ssh://svn.python.org/projects/peps/trunk

Difference between Method and Function?

From Object-Oriented Programming Concept:

If you have a function that is accessing/muttating the fields of your class, it becomes method. Otherwise, it is a function.

It will not be a crime if you keep calling all the functions in Java/C++ classes as methods. The reason is that you are directly/indirectly accessing/mutating class properties. So why not all the functions in Java/C++ classes are methods?

How to install npm peer dependencies automatically?

The project npm-install-peers will detect peers and install them.

As of v1.0.1 it doesn't support writing back to the package.json automatically, which would essentially solve our need here.

Please add your support to issue in flight: https://github.com/spatie/npm-install-peers/issues/4

Concatenating variables in Bash

Try doing this, there's no special character to concatenate in bash :

mystring="${arg1}12${arg2}endoffile"

explanations

If you don't put brackets, you will ask to concatenate $arg112 + $argendoffile (I guess that's not what you asked) like in the following example :

mystring="$arg112$arg2endoffile"

The brackets are delimiters for the variables when needed. When not needed, you can use it or not.

another solution

(less portable : require bash > 3.1)

$ arg1=foo
$ arg2=bar
$ mystring="$arg1"
$ mystring+="12"
$ mystring+="$arg2"
$ mystring+="endoffile"
$ echo "$mystring"
foo12barendoffile

See http://mywiki.wooledge.org/BashFAQ/013

Get latitude and longitude automatically using php, API

I think allow_url_fopen on your apache server is disabled. you need to trun it on.

kindly change allow_url_fopen = 0 to allow_url_fopen = 1

Don't forget to restart your Apache server after changing it.

Chart.js v2 hide dataset labels

It's just as simple as adding this: legend: { display: false, }

// Or if you want you could use this other option which should also work:

Chart.defaults.global.legend.display = false;

Firebase Storage How to store and Retrieve images

Update (20160519): Firebase just released a new feature called Firebase Storage. This allows you to upload images and other non-JSON data to a dedicated storage service. We highly recommend that you use this for storing images, instead of storing them as base64 encoded data in the JSON database.

You certainly can! Depending on how big your images are, you have a couple options:

1. For smaller images (under 10mb)

We have an example project that does that here: https://github.com/firebase/firepano

The general approach is to load the file locally (using FileReader) so you can then store it in Firebase just as you would any other data. Since images are binary files, you'll want to get the base64-encoded contents so you can store it as a string. Or even more convenient, you can store it as a data: url which is then ready to plop in as the src of an img tag (this is what the example does)!

2. For larger images

Firebase does have a 10mb (of utf8-encoded string data) limit. If your image is bigger, you'll have to break it into 10mb chunks. You're right though that Firebase is more optimized for small strings that change frequently rather than multi-megabyte strings. If you have lots of large static data, I'd definitely recommend S3 or a CDN instead.

Converting String to "Character" array in Java

if you are working with JTextField then it can be helpfull..

public JTextField display;
String number=e.getActionCommand();

display.setText(display.getText()+number);

ch=number.toCharArray();
for( int i=0; i<ch.length; i++)
    System.out.println("in array a1= "+ch[i]);

Python Script execute commands in Terminal

The os.popen() is pretty simply to use, but it has been deprecated since Python 2.6. You should use the subprocess module instead.

Read here: reading a os.popen(command) into a string

ASP.NET: HTTP Error 500.19 – Internal Server Error 0x8007000d

I had the exact same error. It turned out that it was something was caused by something completely, though. It was missing write permissions in a cache folder. But IIS reported error 0x8007000d which is wildly confusing.

How to get changes from another branch

git fetch origin our-team

or

git pull origin our-team

but first you should make sure that you already on the branch you want to update to (featurex).

Push Notifications in Android Platform

You can use Pusher

It's a hosted service that makes it super-easy to add real-time data and functionality to web and mobile applications.
Pusher offers libraries to integrate into all the main runtimes and frameworks.

PHP, Ruby, Python, Java, .NET, Go and Node on the server
JavaScript, Objective-C (iOS) and Java (Android) on the client.

How can I put a database under git (version control)?

Check out Refactoring Databases (http://databaserefactoring.com/) for a bunch of good techniques for maintaining your database in tandem with code changes.

Suffice to say that you're asking the wrong questions. Instead of putting your database into git you should be decomposing your changes into small verifiable steps so that you can migrate/rollback schema changes with ease.

If you want to have full recoverability you should consider archiving your postgres WAL logs and use the PITR (point in time recovery) to play back/forward transactions to specific known good states.

How do I declare a model class in my Angular 2 component using TypeScript?

create model.ts in your component directory as below

export module DataModel {
       export interface DataObjectName {
         propertyName: type;
        }
       export interface DataObjectAnother {
         propertyName: type;
        }
    }

then in your component import above as, import {DataModel} from './model';

export class YourComponent {
   public DataObject: DataModel.DataObjectName;
}

your DataObject should have all the properties from DataObjectName.

Get String in YYYYMMDD format from JS date object?

If using AngularJs (up to 1.5) you can use the date filter:

var formattedDate = $filter('date')(myDate, 'yyyyMMdd')

Checking if a character is a special character in Java

What I would do:

char c;
int cint;
for(int n = 0; n < str.length(); n ++;)
{
    c = str.charAt(n);
    cint = (int)c;
    if(cint <48 || (cint > 57 && cint < 65) || (cint > 90 && cint < 97) || cint > 122)
    {
        specialCharacterCount++
    }
}

That is a simple way to do things, without having to import any special classes. Stick it in a method, or put it straight into the main code.

ASCII chart: http://www.gophoto.it/view.php?i=http://i.msdn.microsoft.com/dynimg/IC102418.gif#.UHsqxFEmG08

Call an angular function inside html

Yep, just add parenthesis (calling the function). Make sure the function is in scope and actually returns something.

<ul class="ui-listview ui-radiobutton" ng-repeat="meter in meters">
  <li class = "ui-divider">
    {{ meter.DESCRIPTION }}
    {{ htmlgeneration() }}
  </li>
</ul>

How do I keep Python print from adding newlines or spaces?

In python 2.6:

>>> print 'h','m','h'
h m h
>>> from __future__ import print_function
>>> print('h',end='')
h>>> print('h',end='');print('m',end='');print('h',end='')
hmh>>>
>>> print('h','m','h',sep='');
hmh
>>>

So using print_function from __future__ you can set explicitly the sep and end parameteres of print function.

Killing a process using Java

You can kill a (SIGTERM) a windows process that was started from Java by calling the destroy method on the Process object. You can also kill any child Processes (since Java 9).

The following code starts a batch file, waits for ten seconds then kills all sub-processes and finally kills the batch process itself.

ProcessBuilder pb = new ProcessBuilder("cmd /c my_script.bat"));
Process p = pb.start();
p.waitFor(10, TimeUnit.SECONDS);

p.descendants().forEach(ph -> {
    ph.destroy();
});

p.destroy();

How can I dynamically set the position of view in Android?

You can try to use the following methods, if you're using HoneyComb Sdk(API Level 11).

view.setX(float x);

Parameter x is the visual x position of this view.

view.setY(float y);

Parameter y is the visual y position of this view.

I hope it will be helpful to you. :)

Set the table column width constant regardless of the amount of text in its cells?

You need to write this inside the corresponding CSS

table-layout:fixed;

Is there a Java API that can create rich Word documents?

You can use a Java COM bridge like JACOB. If it is from client side, another option would be to use Javascript.

Convert Enum to String

For VB aficionados:

EnumStringValue = System.Enum.GetName(GetType(MyEnum), MyEnumValue)

AndroidStudio SDK directory does not exists

  1. Go to your project_folder/platform/android/
  2. Open local.properties in your text editor
  3. Change URL with your SDK URL sdk.dir = C:\Users/Pcesolutions/AppData/Local/Android/Sdk
  4. Now run your command in windows

Its worked for me. I think, it work's also in your PC.

Append Char To String in C?

To append a char to a string in C, you first have to ensure that the memory buffer containing the string is large enough to accomodate an extra character. In your example program, you'd have to allocate a new, additional, memory block because the given literal string cannot be modified.

Here's a sample:

#include <stdlib.h>

int main()
{
    char *str = "blablabla";
    char c = 'H';

    size_t len = strlen(str);
    char *str2 = malloc(len + 1 + 1 ); /* one for extra char, one for trailing zero */
    strcpy(str2, str);
    str2[len] = c;
    str2[len + 1] = '\0';

    printf( "%s\n", str2 ); /* prints "blablablaH" */

    free( str2 );
}

First, use malloc to allocate a new chunk of memory which is large enough to accomodate all characters of the input string, the extra char to append - and the final zero. Then call strcpy to copy the input string into the new buffer. Finally, change the last two bytes in the new buffer to tack on the character to add as well as the trailing zero.

label or @html.Label ASP.net MVC 4

When it comes to labels, I would say it's up to you what you prefer. Some examples when it can be useful with HTML helper tags are, for instance

  • When dealing with hyperlinks, since the HTML helper simplifies routing
  • When you bind to your model, using @Html.LabelFor, @Html.TextBoxFor, etc
  • When you use the @Html.EditorFor, as you can assign specific behavior och looks in a editor view

How do I shut down a python simpleHTTPserver?

MYPORT=8888; 
kill -9 `ps -ef |grep SimpleHTTPServer |grep $MYPORT |awk '{print $2}'`

That is it!

Explain command line :

  • ps -ef : list all process.

  • grep SimpleHTTPServer : filter process which belong to "SimpleHTTPServer"

  • grep $MYPORT : filter again process belong to "SimpleHTTPServer" where port is MYPORT (.i.e: MYPORT=8888)

  • awk '{print $2}' : print second column of result which is the PID (Process ID)

  • kill -9 <PID> : Force Kill process with the appropriate PID.

Is there any sed like utility for cmd.exe?

You could try powershell. There are get-content and set-content commandlets build in that you could use.

Multiple bluetooth connection

Two UE Boom Bluetooth speakers can form a stereo, which means the phone can stream simultaneously to two Bluetooth devices. The reason is Bluetooth 4.0 can support up to two synchronous connection oriented (SCO) links on the same piconet, and A2DP is based on SCO link.

Your demand "bluetooth chat" is based on SPP profile, and SPP is based on RFCOMM protocol. Luckily even Bluetooth 2.1 can support multiple RFCOMM channels, so yes, you can have multiple bluetooth connection to chat with each other.

How do you find the first key in a dictionary?

On a Python version where dicts actually are ordered, you can do

my_dict = {'foo': 'bar', 'spam': 'eggs'}
next(iter(my_dict)) # outputs 'foo'

For dicts to be ordered, you need Python 3.7+, or 3.6+ if you're okay with relying on the technically-an-implementation-detail ordered nature of dicts on Python 3.6.

For earlier Python versions, there is no "first key".

Java web start - Unable to load resource

changing java proxy settings to direct connection did not fix my issue.

What worked for me:

  1. Run "Configure Java" as administrator.
  2. Go to Advanced
  3. Scroll to bottom
  4. Under: "Advanced Security Settings" uncheck "Use SSL 2.0 compatible ClientHello format"
  5. Save

Convert float64 column to int64 in Pandas

consider using

df['column name'].astype('Int64')

nan will be changed to NaN

IE6/IE7 css border on select element

It solves to me, for my purposes:

.select-container {
  position:relative;
  width:200px;
  height:18px;
  overflow:hidden;
  border:1px solid white !important
}
.select-container select {
  position:relative;
  left:-2px;
  top:-2px
}

To put more style will be necessary to use nested divs .

What is the use of System.in.read()?

import java.io.IOException;

class ExamTest{

    public static void main(String args[]) throws IOException{
        int sn=System.in.read();
        System.out.println(sn);
    }
}

If you want get char input you have to cast like this: char sn=(char) System.in.read()

The value byte is returned as int in the range 0 to 255. However, unlike in other languages’ methods, System.in.read() reads only a byte at a time.