SyntaxFix.com - Programming Questions & Answers Hub For Beginners


Some Of The Best Answers From Latest Asked Questions

Bootstrap 3 Horizontal Divider (not in a dropdown)

Currently it only works for the .dropdown-menu:

.dropdown-menu .divider {
  height: 1px;
  margin: 9px 0;
  overflow: hidden;
  background-color: #e5e5e5;
}

If you want it for other use, in your own css, following the bootstrap.css create another one:

.divider {
  height: 1px;
  width:100%;
  display:block; /* for use on default inline elements like span */
  margin: 9px 0;
  overflow: hidden;
  background-color: #e5e5e5;
}

Resource u'tokenizers/punkt/english.pickle' not found

Just make sure you are using Jupyter Notebook and in a notebook, do the following:

import nltk

nltk.download()

Then one popup window will appear (showing info https://raw.githubusercontent.com/nltk/nltk_data/gh-pages/index.xml) From that you have to download everything.

Then rerun your code.

Error in installation a R package

In my case, I had to close R session and reinstall all packages. In that session I worked with large tables, I suspect this might have had the effect.

How to get file name from file path in android

Old thread but thought I would update;

 File theFile = .......
 String theName = theFile.getName();  // Get the file name
 String thePath = theFile.getAbsolutePath(); // Get the full

More info can be found here; Android File Class

How do you create a UIImage View Programmatically - Swift

Swift 4:

First create an outlet for your UIImageView

@IBOutlet var infoImage: UIImageView!

Then use the image property in UIImageView

infoImage.image = UIImage(named: "icons8-info-white")

How to replace multiple patterns at once with sed?

May be a simpler approach for single pattern occurrence you can try as below: echo 'abbc' | sed 's/ab/bc/;s/bc/ab/2'

My output:

 ~# echo 'abbc' | sed 's/ab/bc/;s/bc/ab/2'
 bcab

For multiple occurrences of pattern:

sed 's/\(ab\)\(bc\)/\2\1/g'

Example

~# cat try.txt
abbc abbc abbc
bcab abbc bcab
abbc abbc bcab

~# sed 's/\(ab\)\(bc\)/\2\1/g' try.txt
bcab bcab bcab
bcab bcab bcab
bcab bcab bcab

Hope this helps !!

Get input value from TextField in iOS alert in Swift

Swift 3/4

You can use the below extension for your convenience.

Usage inside a ViewController:

showInputDialog(title: "Add number",
                subtitle: "Please enter the new number below.",
                actionTitle: "Add",
                cancelTitle: "Cancel",
                inputPlaceholder: "New number",
                inputKeyboardType: .numberPad)
{ (input:String?) in
    print("The new number is \(input ?? "")")
}

The extension code:

extension UIViewController {
    func showInputDialog(title:String? = nil,
                         subtitle:String? = nil,
                         actionTitle:String? = "Add",
                         cancelTitle:String? = "Cancel",
                         inputPlaceholder:String? = nil,
                         inputKeyboardType:UIKeyboardType = UIKeyboardType.default,
                         cancelHandler: ((UIAlertAction) -> Swift.Void)? = nil,
                         actionHandler: ((_ text: String?) -> Void)? = nil) {

        let alert = UIAlertController(title: title, message: subtitle, preferredStyle: .alert)
        alert.addTextField { (textField:UITextField) in
            textField.placeholder = inputPlaceholder
            textField.keyboardType = inputKeyboardType
        }
        alert.addAction(UIAlertAction(title: actionTitle, style: .default, handler: { (action:UIAlertAction) in
            guard let textField =  alert.textFields?.first else {
                actionHandler?(nil)
                return
            }
            actionHandler?(textField.text)
        }))
        alert.addAction(UIAlertAction(title: cancelTitle, style: .cancel, handler: cancelHandler))

        self.present(alert, animated: true, completion: nil)
    }
}

Wait until page is loaded with Selenium WebDriver for Python

Solution for ajax pages that continuously load data. The previews methods stated do not work. What we can do instead is grab the page dom and hash it and compare old and new hash values together over a delta time.

import time
from selenium import webdriver

def page_has_loaded(driver, sleep_time = 2):
    '''
    Waits for page to completely load by comparing current page hash values.
    '''

    def get_page_hash(driver):
        '''
        Returns html dom hash
        '''
        # can find element by either 'html' tag or by the html 'root' id
        dom = driver.find_element_by_tag_name('html').get_attribute('innerHTML')
        # dom = driver.find_element_by_id('root').get_attribute('innerHTML')
        dom_hash = hash(dom.encode('utf-8'))
        return dom_hash

    page_hash = 'empty'
    page_hash_new = ''
    
    # comparing old and new page DOM hash together to verify the page is fully loaded
    while page_hash != page_hash_new: 
        page_hash = get_page_hash(driver)
        time.sleep(sleep_time)
        page_hash_new = get_page_hash(driver)
        print('<page_has_loaded> - page not loaded')

    print('<page_has_loaded> - page loaded: {}'.format(driver.current_url))

Invariant Violation: _registerComponent(...): Target container is not a DOM element

I ran into the same error. It turned out to be caused by a simple typo after changing my code from:

document.getElementById('root')

to

document.querySelector('root')

Notice the missing '#' It should have been

document.querySelector('#root')

Just posting in case it helps anyone else solve this error.

How to set Apache Spark Executor memory

Since you are running Spark in local mode, setting spark.executor.memory won't have any effect, as you have noticed. The reason for this is that the Worker "lives" within the driver JVM process that you start when you start spark-shell and the default memory used for that is 512M. You can increase that by setting spark.driver.memory to something higher, for example 5g. You can do that by either:

  • setting it in the properties file (default is $SPARK_HOME/conf/spark-defaults.conf),

    spark.driver.memory              5g
    
  • or by supplying configuration setting at runtime

    $ ./bin/spark-shell --driver-memory 5g
    

Note that this cannot be achieved by setting it in the application, because it is already too late by then, the process has already started with some amount of memory.

The reason for 265.4 MB is that Spark dedicates spark.storage.memoryFraction * spark.storage.safetyFraction to the total amount of storage memory and by default they are 0.6 and 0.9.

512 MB * 0.6 * 0.9 ~ 265.4 MB

So be aware that not the whole amount of driver memory will be available for RDD storage.

But when you'll start running this on a cluster, the spark.executor.memory setting will take over when calculating the amount to dedicate to Spark's memory cache.

How to detect a docker daemon port

Reference docs of docker: https://docs.docker.com/install/linux/linux-postinstall/#configure-where-the-docker-daemon-listens-for-connections

There are 2 ways in configuring the docker daemon port

1) Configuring at /etc/default/docker file:

DOCKER_OPTS="-H tcp://127.0.0.1:5000 -H unix:///var/run/docker.sock"

2) Configuring at /etc/docker/daemon.json:

{
"debug": true,
"hosts": ["tcp://127.0.0.1:5000", "unix:///var/run/docker.sock"]
}

If the docker default socket is not configured Docker will wait for infinite period.i.e

Waiting for /var/run/docker.sock
Waiting for /var/run/docker.sock
Waiting for /var/run/docker.sock
Waiting for /var/run/docker.sock
Waiting for /var/run/docker.sock

NOTE : BUT DON'T CONFIGURE IN BOTH THE CONFIGURATION FILES, the following error may occur :

Waiting for /var/run/docker.sock
unable to configure the Docker daemon with file /etc/docker/daemon.json: the following directives are specified both as a flag and in the configuration file: hosts: (from flag: [tcp://127.0.0.1:5000 unix:///var/run/docker.sock], from file: tcp://127.0.0.1:5000)

The reason for adding both the user port[ tcp://127.0.0.1:5000] and default docker socket[unix:///var/run/docker.sock] is that the user port enables the access to the docker APIs whereas the default socket enables the CLI. In case the default port[unix:///var/run/docker.sock] is not mentioned in /etc/default/docker file the following error may occur:

# docker ps
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

This error is not because that the docker is not running, but because of default docker socket is not enabled.

Once the configuration is enabled restart the docker service and verify the docker port is enabled or not:

# netstat -tunlp | grep -i 5000
tcp        0      0 127.0.0.1:5000          0.0.0.0:*               LISTEN      31661/dockerd 

Applicable for Docker Version 17.04, may vary with different versions of docker.

Outlets cannot be connected to repeating content iOS

As most people have pointed out that subclassing UITableViewCell solves this issue. But the reason this not allowed because the prototype cell(UITableViewCell) is defined by Apple and you cannot add any of your own outlets to it.

Error inflating class android.support.v7.widget.Toolbar?

Sorry Guys. I have solved this Issue long ago. I did a lot of changes. So I can't figure out which one does the trick.

  1. I have changed the id as suggested by Jared Burrows.

  2. Removed my support library and cleaned my project and Re added it.

  3. Go to File -> Invalidate Caches/Restart.

Hope it works.

This is how my code looks now

activity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include
        android:id="@+id/toolbar_actionbar"
        layout="@layout/toolbar_default"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <android.support.v4.widget.DrawerLayout
        android:id="@+id/drawer"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/toolbar_actionbar">

        <FrameLayout
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

        <fragment
            android:id="@+id/fragment_drawer"
            android:name="com.arul.anahy.drawer.NavigationDrawerFragment"
            android:layout_width="@dimen/navigation_drawer_width"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            app:layout="@layout/fragment_navigation_drawer"/>
    </android.support.v4.widget.DrawerLayout>
</RelativeLayout>

toolbar_default.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    style="@style/ToolBarStyle"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:minHeight="@dimen/abc_action_bar_default_height_material"/>

ToolBarStyle

<style name="ToolBarStyle" parent="">
        <item name="popupTheme">@style/ThemeOverlay.AppCompat.Light</item>
        <item name="theme">@style/ThemeOverlay.AppCompat.Dark.ActionBar</item>
 </style>

Change the background color of CardView programmatically

Use the property card_view:cardBackgroundColor:

<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_width="fill_parent"
    android:layout_height="150dp"
    android:layout_gravity="center"
    card_view:cardCornerRadius="4dp"
    android:layout_margin="10dp"
    card_view:cardBackgroundColor="#fff"
    >

Python Binomial Coefficient

I recommend using dynamic programming (DP) for computing binomial coefficients. In contrast to direct computation, it avoids multiplication and division of large numbers. In addition to recursive solution, it stores previously solved overlapping sub-problems in a table for fast look-up. The code below shows bottom-up (tabular) DP and top-down (memoized) DP implementations for computing binomial coefficients.

def binomial_coeffs1(n, k):
    #top down DP
    if (k == 0 or k == n):
        return 1
    if (memo[n][k] != -1):
        return memo[n][k]

    memo[n][k] = binomial_coeffs1(n-1, k-1) + binomial_coeffs1(n-1, k)
    return memo[n][k]

def binomial_coeffs2(n, k):
    #bottom up DP
    for i in range(n+1):
        for j in range(min(i,k)+1):
            if (j == 0 or j == i):
                memo[i][j] = 1
            else:
                memo[i][j] = memo[i-1][j-1] + memo[i-1][j]
            #end if
        #end for
    #end for
    return memo[n][k]

def print_array(memo):
    for i in range(len(memo)):
        print('\t'.join([str(x) for x in memo[i]]))

#main
n = 5
k = 2

print("top down DP")
memo = [[-1 for i in range(6)] for j in range(6)]
nCk = binomial_coeffs1(n, k)
print_array(memo)
print("C(n={}, k={}) = {}".format(n,k,nCk))

print("bottom up DP")
memo = [[-1 for i in range(6)] for j in range(6)]
nCk = binomial_coeffs2(n, k)
print_array(memo)
print("C(n={}, k={}) = {}".format(n,k,nCk))

Note: the size of the memo table is set to a small value (6) for display purposes, it should be increased if you are computing binomial coefficients for large n and k.

Undefined symbols for architecture x86_64 on Xcode 6.1

I just had this error when I opened a (quite) old project, created in Xcode 4~ish, in Xcode 6.4. While the linked Frameworks were visible in the Project sidebar, I overlooked that there were no linked libraries in the Target Build Phases tab. Once I fixed that, it compiled fine.

Command failed due to signal: Segmentation fault: 11

I'm using Xcode 8.3/Swift 3

I used @Ron B.'s answer to go through all the code and comment out different functions until I got a successful build. It turns out it was async trailing closures that was causing my error:

My trailing closures:

let firstTask = DispatchWorkItem{
     //self.doSomthing()
}
let secondTask = DispatchWorkItem{
     //self.doSomthingElse()
}

//trailing closure #1
DispatchQueue.main.asyncAfter(deadline: .now() + 10){firstTask}

//trailing closure #2 
DispatchQueue.main.asyncAfter(deadline: .now() + 20){secondTask}

Once I used the autocomplete syntax the Segmentation fault: 11 was Gone

//autocomplete syntax closure #1
DispatchQueue.main.asyncAfter(deadline: .now() + 10, execute: firstTask)

//autocomplete syntax closure #2
DispatchQueue.main.asyncAfter(deadline: .now() + 20, execute: secondTask)

React "after render" code?

You can change the state and then do your calculations in the setState callback. According to the React documentation, this is "guaranteed to fire after the update has been applied".

This should be done in componentDidMount or somewhere else in the code (like on a resize event handler) rather than in the constructor.

This is a good alternative to window.requestAnimationFrame and it does not have the issues some users have mentioned here (needing to combine it with setTimeout or call it multiple times). For example:

class AppBase extends React.Component {
    state = {
        showInProcess: false,
        size: null
    };

    componentDidMount() {
        this.setState({ showInProcess: true }, () => {
            this.setState({
                showInProcess: false,
                size: this.calculateSize()
            });
        });
    }

    render() {
        const appStyle = this.state.showInProcess ? { visibility: 'hidden' } : null;

        return (
            <div className="wrapper">
                ...
                <div className="app-content" style={appStyle}>
                    <List items={items} />
                </div>
                ...
            </div>
        );
    }
}

Change Toolbar color in Appcompat 21

You can set a custom toolbar item color dynamically by creating a custom toolbar class:

package view;

import android.app.Activity;
import android.content.Context;
import android.graphics.ColorFilter;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.support.v7.internal.view.menu.ActionMenuItemView;
import android.support.v7.widget.ActionMenuView;
import android.support.v7.widget.Toolbar;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

public class CustomToolbar extends Toolbar{

    public CustomToolbar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        // TODO Auto-generated constructor stub
    }

    public CustomToolbar(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    public CustomToolbar(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        ctxt = context;
    }

    int itemColor;
    Context ctxt;

    @Override 
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        Log.d("LL", "onLayout");
        super.onLayout(changed, l, t, r, b);
        colorizeToolbar(this, itemColor, (Activity) ctxt);
    } 

    public void setItemColor(int color){
        itemColor = color;
        colorizeToolbar(this, itemColor, (Activity) ctxt);
    }



    /**
     * Use this method to colorize toolbar icons to the desired target color
     * @param toolbarView toolbar view being colored
     * @param toolbarIconsColor the target color of toolbar icons
     * @param activity reference to activity needed to register observers
     */
    public static void colorizeToolbar(Toolbar toolbarView, int toolbarIconsColor, Activity activity) {
        final PorterDuffColorFilter colorFilter
                = new PorterDuffColorFilter(toolbarIconsColor, PorterDuff.Mode.SRC_IN);

        for(int i = 0; i < toolbarView.getChildCount(); i++) {
            final View v = toolbarView.getChildAt(i);

            doColorizing(v, colorFilter, toolbarIconsColor);
        }

      //Step 3: Changing the color of title and subtitle.
        toolbarView.setTitleTextColor(toolbarIconsColor);
        toolbarView.setSubtitleTextColor(toolbarIconsColor);
    }

    public static void doColorizing(View v, final ColorFilter colorFilter, int toolbarIconsColor){
        if(v instanceof ImageButton) {
            ((ImageButton)v).getDrawable().setAlpha(255);
            ((ImageButton)v).getDrawable().setColorFilter(colorFilter);
        }

        if(v instanceof ImageView) {
            ((ImageView)v).getDrawable().setAlpha(255);
            ((ImageView)v).getDrawable().setColorFilter(colorFilter);
        }

        if(v instanceof AutoCompleteTextView) {
            ((AutoCompleteTextView)v).setTextColor(toolbarIconsColor);
        }

        if(v instanceof TextView) {
            ((TextView)v).setTextColor(toolbarIconsColor);
        }

        if(v instanceof EditText) {
            ((EditText)v).setTextColor(toolbarIconsColor);
        }

        if (v instanceof ViewGroup){
            for (int lli =0; lli< ((ViewGroup)v).getChildCount(); lli ++){
                doColorizing(((ViewGroup)v).getChildAt(lli), colorFilter, toolbarIconsColor);
            }
        }

        if(v instanceof ActionMenuView) {
            for(int j = 0; j < ((ActionMenuView)v).getChildCount(); j++) {

                //Step 2: Changing the color of any ActionMenuViews - icons that
                //are not back button, nor text, nor overflow menu icon.
                final View innerView = ((ActionMenuView)v).getChildAt(j);

                if(innerView instanceof ActionMenuItemView) {
                    int drawablesCount = ((ActionMenuItemView)innerView).getCompoundDrawables().length;
                    for(int k = 0; k < drawablesCount; k++) {
                        if(((ActionMenuItemView)innerView).getCompoundDrawables()[k] != null) {
                            final int finalK = k;

                            //Important to set the color filter in seperate thread, 
                            //by adding it to the message queue
                            //Won't work otherwise. 
                            //Works fine for my case but needs more testing

                            ((ActionMenuItemView) innerView).getCompoundDrawables()[finalK].setColorFilter(colorFilter);

//                              innerView.post(new Runnable() {
//                                  @Override
//                                  public void run() {
//                                      ((ActionMenuItemView) innerView).getCompoundDrawables()[finalK].setColorFilter(colorFilter);
//                                  }
//                              });
                        }
                    }
                }
            }
        }
    }



}

then refer to it in your layout file. Now you can set a custom color using

toolbar.setItemColor(Color.Red);

Sources:

I found the information to do this here: How to dynamicaly change Android Toolbar icons color

and then I edited it, improved upon it, and posted it here: GitHub:AndroidDynamicToolbarItemColor

How to present UIAlertController when not in a view controller?

@agilityvision's answer is so good. I have sense used in swift projects so I thought I would share my take on his answer using swift 3.0

fileprivate class MyUIAlertController: UIAlertController {

  typealias Handler = () -> Void

  struct AssociatedKeys {
    static var alertWindowKey = "alertWindowKey"
  }

  dynamic var _alertWindow: UIWindow?

  var alertWindow: UIWindow? {
    return objc_getAssociatedObject(self, &AssociatedKeys.alertWindowKey) as? UIWindow
  }


  func setAlert(inWindow window: UIWindow) {
    objc_setAssociatedObject(self, &AssociatedKeys.alertWindowKey, _alertWindow, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  }

  func show(completion: Handler? = nil) {
    show(animated: true, completion: completion)
  }

  func show(animated: Bool, completion: Handler? =  nil) {
    _alertWindow = UIWindow(frame: UIScreen.main.bounds)
    _alertWindow?.rootViewController = UIViewController()

    if let delegate: UIApplicationDelegate = UIApplication.shared.delegate, let window = delegate.window {
      _alertWindow?.tintColor = window?.tintColor

    }

    let topWindow = UIApplication.shared.windows.last
    _alertWindow?.windowLevel = topWindow?.windowLevel ?? 0 + 1
    _alertWindow?.makeKeyAndVisible()
    _alertWindow?.rootViewController?.present(self, animated: animated, completion: completion)
  }

  fileprivate override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
    _alertWindow?.isHidden = true
    _alertWindow = nil
  }
}

Using Mysql in the command line in osx - command not found?

You can just modified the .bash_profile by adding the MySQL $PATH as the following:
export PATH=$PATH:/usr/local/mysql/bin.

I did the following:

1- Open Terminal then $ nano .bash_profile or $ vim .bash_profile

2- Add the following PATH code to the .bash_profile

# Set architecture flags
export ARCHFLAGS="-arch x86_64"
# Ensure user-installed binaries take precedence
export PATH=/usr/local/mysql/bin:$PATH
# Load .bashrc if it exists
test -f ~/.bashrc && source ~/.bashrc 

3- Save the file.

4- Refresh Terminal using $ source ~/.bash_profile

5- To verify, type in Terminal $ mysql --version

6- It should print the output something like this:

$ mysql Ver 14.14 Distrib 5.7.17, for macos10.12 (x86_64)

The Terminal is now configured to read the MySQL commands from $PATH which is placed in the .bash_profile .

Xcode 6.1 Missing required architecture X86_64 in file

If you are building a universal library and need to support the Simulator (x86_64) then build the framework for all platforms by setting Build Active Architecture Only to No. enter image description here

Spring: Returning empty HTTP Responses with ResponseEntity<Void> doesn't work

Personally, to deal with empty responses, I use in my Integration Tests the MockMvcResponse object like this :

MockMvcResponse response = RestAssuredMockMvc.given()
                .webAppContextSetup(webApplicationContext)
                .when()
                .get("/v1/ticket");

    assertThat(response.mockHttpServletResponse().getStatus()).isEqualTo(HttpStatus.NO_CONTENT.value());

and in my controller I return empty response in a specific case like this :

return ResponseEntity.noContent().build();

When use ResponseEntity<T> and @RestController for Spring RESTful applications

ResponseEntity is meant to represent the entire HTTP response. You can control anything that goes into it: status code, headers, and body.

@ResponseBody is a marker for the HTTP response body and @ResponseStatus declares the status code of the HTTP response.

@ResponseStatus isn't very flexible. It marks the entire method so you have to be sure that your handler method will always behave the same way. And you still can't set the headers. You'd need the HttpServletResponse or a HttpHeaders parameter.

Basically, ResponseEntity lets you do more.

org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

I had same issue. adding this to the application.properties solved the issue:

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect

Are vectors passed to functions by value or by reference in C++

If I had to guess, I'd say that you're from a Java background. This is C++, and things are passed by value unless you specify otherwise using the &-operator (note that this operator is also used as the 'address-of' operator, but in a different context). This is all well documented, but I'll re-iterate anyway:

void foo(vector<int> bar); // by value
void foo(vector<int> &bar); // by reference (non-const, so modifiable inside foo)
void foo(vector<int> const &bar); // by const-reference

You can also choose to pass a pointer to a vector (void foo(vector<int> *bar)), but unless you know what you're doing and you feel that this is really is the way to go, don't do this.

Also, vectors are not the same as arrays! Internally, the vector keeps track of an array of which it handles the memory management for you, but so do many other STL containers. You can't pass a vector to a function expecting a pointer or array or vice versa (you can get access to (pointer to) the underlying array and use this though). Vectors are classes offering a lot of functionality through its member-functions, whereas pointers and arrays are built-in types. Also, vectors are dynamically allocated (which means that the size may be determined and changed at runtime) whereas the C-style arrays are statically allocated (its size is constant and must be known at compile-time), limiting their use.

I suggest you read some more about C++ in general (specifically array decay), and then have a look at the following program which illustrates the difference between arrays and pointers:

void foo1(int *arr) { cout << sizeof(arr) << '\n'; }
void foo2(int arr[]) { cout << sizeof(arr) << '\n'; }
void foo3(int arr[10]) { cout << sizeof(arr) << '\n'; }
void foo4(int (&arr)[10]) { cout << sizeof(arr) << '\n'; }

int main()
{
    int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    foo1(arr);
    foo2(arr);
    foo3(arr);
    foo4(arr);
}

NumPy array is not JSON serializable

Here is an implementation that work for me and removed all nans (assuming these are simple object (list or dict)):

from numpy import isnan

def remove_nans(my_obj, val=None):
    if isinstance(my_obj, list):
        for i, item in enumerate(my_obj):
            if isinstance(item, list) or isinstance(item, dict):
                my_obj[i] = remove_nans(my_obj[i], val=val)

            else:
                try:
                    if isnan(item):
                        my_obj[i] = val
                except Exception:
                    pass

    elif isinstance(my_obj, dict):
        for key, item in my_obj.iteritems():
            if isinstance(item, list) or isinstance(item, dict):
                my_obj[key] = remove_nans(my_obj[key], val=val)

            else:
                try:
                    if isnan(item):
                        my_obj[key] = val
                except Exception:
                    pass

    return my_obj

Pandas groupby month and year

You can use either resample or Grouper (which resamples under the hood).

First make sure that the datetime column is actually of datetimes (hit it with pd.to_datetime). It's easier if it's a DatetimeIndex:

In [11]: df1
Out[11]:
            abc  xyz
Date
2013-06-01  100  200
2013-06-03  -20   50
2013-08-15   40   -5
2014-01-20   25   15
2014-02-21   60   80

In [12]: g = df1.groupby(pd.Grouper(freq="M"))  # DataFrameGroupBy (grouped by Month)

In [13]: g.sum()
Out[13]:
            abc  xyz
Date
2013-06-30   80  250
2013-07-31  NaN  NaN
2013-08-31   40   -5
2013-09-30  NaN  NaN
2013-10-31  NaN  NaN
2013-11-30  NaN  NaN
2013-12-31  NaN  NaN
2014-01-31   25   15
2014-02-28   60   80

In [14]: df1.resample("M", how='sum')  # the same
Out[14]:
            abc  xyz
Date
2013-06-30   40  125
2013-07-31  NaN  NaN
2013-08-31   40   -5
2013-09-30  NaN  NaN
2013-10-31  NaN  NaN
2013-11-30  NaN  NaN
2013-12-31  NaN  NaN
2014-01-31   25   15
2014-02-28   60   80

Note: Previously pd.Grouper(freq="M") was written as pd.TimeGrouper("M"). The latter is now deprecated since 0.21.


I had thought the following would work, but it doesn't (due to as_index not being respected? I'm not sure.). I'm including this for interest's sake.

If it's a column (it has to be a datetime64 column! as I say, hit it with to_datetime), you can use the PeriodIndex:

In [21]: df
Out[21]:
        Date  abc  xyz
0 2013-06-01  100  200
1 2013-06-03  -20   50
2 2013-08-15   40   -5
3 2014-01-20   25   15
4 2014-02-21   60   80

In [22]: pd.DatetimeIndex(df.Date).to_period("M")  # old way
Out[22]:
<class 'pandas.tseries.period.PeriodIndex'>
[2013-06, ..., 2014-02]
Length: 5, Freq: M

In [23]: per = df.Date.dt.to_period("M")  # new way to get the same

In [24]: g = df.groupby(per)

In [25]: g.sum()  # dang not quite what we want (doesn't fill in the gaps)
Out[25]:
         abc  xyz
2013-06   80  250
2013-08   40   -5
2014-01   25   15
2014-02   60   80

To get the desired result we have to reindex...

Pandas join issue: columns overlap but no suffix specified

The error indicates that the two tables have the 1 or more column names that have the same column name.

Anyone with the same error who doesn't want to provide a suffix can rename the columns instead. Also make sure the index of both DataFrames match in type and value if you don't want to provide the on='mukey' setting.

# rename example
df_a = df_a.rename(columns={'a_old': 'a_new', 'a2_old': 'a2_new'})
# set the index
df_a = df_a.set_index(['mukus'])
df_b = df_b.set_index(['mukus'])

df_a.join(df_b)

VBA using ubound on a multidimensional array

[This is a late answer addressing the title of the question (since that is what people would encounter when searching) rather than the specifics of OP's question which has already been answered adequately]

Ubound is a bit fragile in that it provides no way to know how many dimensions an array has. You can use error trapping to determine the full layout of an array. The following returns a collection of arrays, one for each dimension. The count property can be used to determine the number of dimensions and their lower and upper bounds can be extracted as needed:

Function Bounds(A As Variant) As Collection
    Dim C As New Collection
    Dim v As Variant, i As Long

    On Error GoTo exit_function
    i = 1
    Do While True
        v = Array(LBound(A, i), UBound(A, i))
        C.Add v
        i = i + 1
    Loop
exit_function:
    Set Bounds = C
End Function

Used like this:

Sub test()
    Dim i As Long
    Dim A(1 To 10, 1 To 5, 4 To 10) As Integer
    Dim B(1 To 5) As Variant
    Dim C As Variant
    Dim sizes As Collection

    Set sizes = Bounds(A)
    Debug.Print "A has " & sizes.Count & " dimensions:"
    For i = 1 To sizes.Count
        Debug.Print sizes(i)(0) & " to " & sizes(i)(1)
    Next i

    Set sizes = Bounds(B)
    Debug.Print vbCrLf & "B has " & sizes.Count & " dimensions:"
    For i = 1 To sizes.Count
        Debug.Print sizes(i)(0) & " to " & sizes(i)(1)
    Next i

    Set sizes = Bounds(C)
    Debug.Print vbCrLf & "C has " & sizes.Count & " dimensions:"
    For i = 1 To sizes.Count
        Debug.Print sizes(i)(0) & " to " & sizes(i)(1)
    Next i
End Sub

Output:

A has 3 dimensions:
1 to 10
1 to 5
4 to 10

B has 1 dimensions:
1 to 5

C has 0 dimensions:

How do I split a string in Rust?

There are three simple ways:

  1. By separator:

     s.split("separator")  |  s.split('/')  |  s.split(char::is_numeric)
    
  2. By whitespace:

     s.split_whitespace()
    
  3. By newlines:

     s.lines()
    
  4. By regex: (using regex crate)

     Regex::new(r"\s").unwrap().split("one two three")
    

The result of each kind is an iterator:

let text = "foo\r\nbar\n\nbaz\n";
let mut lines = text.lines();

assert_eq!(Some("foo"), lines.next());
assert_eq!(Some("bar"), lines.next());
assert_eq!(Some(""), lines.next());
assert_eq!(Some("baz"), lines.next());

assert_eq!(None, lines.next());

How to change button text in Swift Xcode 6?

swift 4 work as well as 3

libero.setTitle("---", for: .normal)

where libero is a uibutton

How do I get the name of the rows from the index of a data frame?

this seems to work fine :

dataframe.axes[0].tolist()

Write variable to a file in Ansible

Unless you are writing very small files, you should probably use templates.

Example:

- name: copy upstart script
  template: 
    src: myCompany-service.conf.j2 
    dest: "/etc/init/myCompany-service.conf"

How to check a Long for null in java

Primitive data types cannot be null. Only Object data types can be null.

int, long, etc... can't be null.

If you use Long (wrapper class for long) then you can check for null's:

Long longValue = null;

if(longValue == null)

How to convert a date to milliseconds

tl;dr

LocalDateTime.parse(           // Parse into an object representing a date with a time-of-day but without time zone and without offset-from-UTC.
    "2014/10/29 18:10:45"      // Convert input string to comply with standard ISO 8601 format.
    .replace( " " , "T" )      // Replace SPACE in the middle with a `T`.
    .replace( "/" , "-" )      // Replace SLASH in the middle with a `-`.
)
.atZone(                       // Apply a time zone to provide the context needed to determine an actual moment.
    ZoneId.of( "Europe/Oslo" ) // Specify the time zone you are certain was intended for that input.
)                              // Returns a `ZonedDateTime` object.
.toInstant()                   // Adjust into UTC.
.toEpochMilli()                // Get the number of milliseconds since first moment of 1970 in UTC, 1970-01-01T00:00Z.

1414602645000

Time Zone

The accepted answer is correct, except that it ignores the crucial issue of time zone. Is your input string 6:10 PM in Paris or Montréal? Or UTC?

Use a proper time zone name. Usually a continent plus city/region. For example, "Europe/Oslo". Avoid the 3 or 4 letter codes which are neither standardized nor unique.

java.time

The modern approach uses the java.time classes.

Alter your input to conform with the ISO 8601 standard. Replace the SPACE in the middle with a T. And replace the slash characters with hyphens. The java.time classes use these standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.

String input = "2014/10/29 18:10:45".replace( " " , "T" ).replace( "/" , "-" ) ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;

A LocalDateTime, like your input string, lacks any concept of time zone or offset-from-UTC. Without the context of a zone/offset, a LocalDateTime has no real meaning. Is it 6:10 PM in India, Europe, or Canada? Each of those places experience 6:10 PM at different moments, at different points on the timeline. So you must specify which you have in mind if you want to determine a specific point on the timeline.

ZoneId z = ZoneId.of( "Europe/Oslo" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;  

Now we have a specific moment, in that ZonedDateTime. Convert to UTC by extracting a Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = zdt.toInstant() ;

Now we can get your desired count of milliseconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00Z.

long millisSinceEpoch = instant.toEpochMilli() ; 

Be aware of possible data loss. The Instant object is capable of carrying microseconds or nanoseconds, finer than milliseconds. That finer fractional part of a second will be ignored when getting a count of milliseconds.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


Joda-Time

Update: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. I will leave this section intact for history.

Below is the same kind of code but using the Joda-Time 2.5 library and handling time zone.

The java.util.Date, .Calendar, and .SimpleDateFormat classes are notoriously troublesome, confusing, and flawed. Avoid them. Use either Joda-Time or the java.time package (inspired by Joda-Time) built into Java 8.

ISO 8601

Your string is almost in ISO 8601 format. The slashes need to be hyphens and the SPACE in middle should be replaced with a T. If we tweak that, then the resulting string can be fed directly into constructor without bothering to specify a formatter. Joda-Time uses ISO 8701 formats as it's defaults for parsing and generating strings.

Example Code

String inputRaw = "2014/10/29 18:10:45";
String input = inputRaw.replace( "/", "-" ).replace( " ", "T" );
DateTimeZone zone = DateTimeZone.forID( "Europe/Oslo" ); // Or DateTimeZone.UTC
DateTime dateTime = new DateTime( input, zone );
long millisecondsSinceUnixEpoch = dateTime.getMillis();

How to insert a line break <br> in markdown

I know this post is about adding a single line break but I thought I would mention that you can create multiple line breaks with the backslash (\) character:

Hello
\
\
\
World!

This would result in 3 new lines after "Hello". To clarify, that would mean 2 empty lines between "Hello" and "World!". It would display like this:


Hello



World!



Personally I find this cleaner for a large number of line breaks compared to using <br>.

Note that backslashes are not recommended for compatibility reasons. So this may not be supported by your Markdown parser but it's handy when it is.

Press TAB and then ENTER key in Selenium WebDriver

In javascript (node.js) this works for me:

describe('UI', function() {

describe('gets results from Bing', function() {
    this.timeout(10000);

    it('makes a search', function(done) {
        var driver = new webdriver.Builder().
        withCapabilities(webdriver.Capabilities.chrome()).
        build();


        driver.get('http://bing.com');
        var input = driver.findElement(webdriver.By.name('q'));
        input.sendKeys('something');
        input.sendKeys(webdriver.Key.ENTER);

        driver.wait(function() {
            driver.findElement(webdriver.By.className('sb_count')).
                getText().
                then(function(result) {
                  console.log('result: ', result);
                  done();
            });
        }, 8000);


    });
  });
});

For tab use webdriver.Key.TAB

Darken CSS background image?

You can use the CSS3 Linear Gradient property along with your background-image like this:

#landing-wrapper {
    display:table;
    width:100%;
    background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5) ), url('landingpagepic.jpg');
    background-position:center top;
    height:350px;
}

Here's a demo:

_x000D_
_x000D_
#landing-wrapper {_x000D_
  display: table;_x000D_
  width: 100%;_x000D_
  background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('http://placehold.it/350x150');_x000D_
  background-position: center top;_x000D_
  height: 350px;_x000D_
  color: white;_x000D_
}
_x000D_
<div id="landing-wrapper">Lorem ipsum dolor ismet.</div>
_x000D_
_x000D_
_x000D_

ng-change get new value and original value

You can always do:

... ng-model="file.PLIK_STATUS" ng-change="file.PLIK_STATUS = setFileStatus(file.PLIK_ID,file.PLIK_STATUS,'{{file.PLIK_STATUS}}')" ...

and in controller:

$scope.setFileStatus = function (plik_id, new_status, old_status) {
    var answer = confirm('Czy na pewno zmienic status dla pliku ?');
    if (answer) {
        podasysService.setFileStatus(plik_id, new_status).then(function (result) {
            return new_status;
        });
    }else{
        return old_status;
    }
};

Display a RecyclerView in Fragment

I faced same problem. And got the solution when I use this code to call context. I use Grid Layout. If you use another one you can change.

   recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),1));

if you have adapter to set. So you can follow this. Just call the getContext

  adapter = new Adapter(getContext(), myModelList);

If you have Toast to show, use same thing above

   Toast.makeText(getContext(), "Error in "+e, Toast.LENGTH_SHORT).show();

Hope this will work.

HappyCoding

Git: Installing Git in PATH with GitHub client for Windows

To get this to work I had to combine many of the above answers, to anyone who this might help here is my much simpler process.

If you have Windows 10 just start typing "edit environmental..." and it'll pop up right away. Click path and Edit… then paste the ;C:\Program Files\Git\bin\git.exe;C:\Program Files\Git\cmd at the end of the path already there, don't forget the ; to separate your new github path from the current path.

You do not need the guid but if you want to know how to find it open bash, type git --man-path

How do you change the launcher logo of an app in Android Studio?

Here are my steps for the task:

  1. Create PNG image file of size 512x512 pixels
  2. In Android Studio, in project view, highlight a mipmap directory
  3. In menu, go to File>New>Image Asset
  4. Click Image Button in Asset type button row
  5. Click on 3 Dot Box at right of Path Box.
  6. Drag image to source asset box
  7. Click Next (Note: Existing launcher files will be overwritten)
  8. Click Finish

React Checkbox not sending onChange

To get the checked state of your checkbox the path would be:

this.refs.complete.state.checked

The alternative is to get it from the event passed into the handleChange method:

event.target.checked

"Please try running this command again as Root/Administrator" error when trying to install LESS

I kept having this problem because windows was setting my node_modules folder to Readonly. Make sure you uncheck this.

enter image description here

Can dplyr join on multiple columns or composite key?

Updating to use tibble()

You can pass a named vector of length greater than 1 to the by argument of left_join():

library(dplyr)

d1 <- tibble(
  x = letters[1:3],
  y = LETTERS[1:3],
  a = rnorm(3)
  )

d2 <- tibble(
  x2 = letters[3:1],
  y2 = LETTERS[3:1],
  b = rnorm(3)
  )

left_join(d1, d2, by = c("x" = "x2", "y" = "y2"))

MAVEN_HOME, MVN_HOME or M2_HOME

I have solved same issue with following:

export M2_HOME=/usr/share/maven

How to enable multidexing with the new Android Multidex support library

Edit:

Android 5.0 (API level 21) and higher uses ART which supports multidexing. Therefore, if your minSdkVersion is 21 or higher, the multidex support library is not needed.


Modify your build.gradle:

android {
    compileSdkVersion 22
    buildToolsVersion "23.0.0"

         defaultConfig {
             minSdkVersion 14 //lower than 14 doesn't support multidex
             targetSdkVersion 22

             // Enabling multidex support.
             multiDexEnabled true
         }
}

dependencies {
    implementation 'com.android.support:multidex:1.0.3'
}

If you are running unit tests, you will want to include this in your Application class:

public class YouApplication extends Application {

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

}

Or just make your application class extend MultiDexApplication

public class Application extends MultiDexApplication {

}

For more info, this is a good guide.

Array formula on Excel for Mac

CTRL+SHIFT+ENTER, ARRAY FORMULA EXCEL 2016 MAC. So I arrive late into the game, but maybe someone else will. This almost drove me nuts. No matter what I searched for in Google I came up empty. Whatever I tried, no solution seemed to be in sight. Switched to Excel 2016 quite some time ago and today I needed to do some array formulas. Also sitting on a MacBook Pro 15 Touch Bar 2016. Not that it really matters, but still, since the solution was published on Youtube in 2013. The reason why, for me anyway, nothing worked, is in the Mac OS, the control key by default, for me anyway, is set to manage Mission control, which, at least for me, disabled the control button in Excel. In order to enable the key to actually control functions in Excel, you need to go to System preferences > Mission Control, and disable shortcuts for Mission control. So, let's see how long this solution will last. Probably be back to square one after the coffee break. Have a good one!

Jquery Ajax, return success/error from mvc.net controller

When you return value from server to jQuery's Ajax call you can also use the below code to indicate a server error:

return StatusCode(500, "My error");

Or

return StatusCode((int)HttpStatusCode.InternalServerError, "My error");

Or

Response.StatusCode = (int)HttpStatusCode.InternalServerError;
return Json(new { responseText = "my error" });

Codes other than Http Success codes (e.g. 200[OK]) will trigger the function in front of error: in client side (ajax).

you can have ajax call like:

$.ajax({
        type: "POST",
        url: "/General/ContactRequestPartial",
        data: {
            HashId: id
        },
       success: function (response)  {
            console.log("Custom message : " + response.responseText);
        }, //Is Called when Status Code is 200[OK] or other Http success code
        error: function (jqXHR, textStatus, errorThrown)  {
            console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);
        }, //Is Called when Status Code is 500[InternalServerError] or other Http Error code
        })

Additionally you can handle different HTTP errors from jQuery side like:

$.ajax({
        type: "POST",
        url: "/General/ContactRequestPartial",
        data: {
            HashId: id
        },
        statusCode: {
            500: function (jqXHR, textStatus, errorThrown)  {
                console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);
            501: function (jqXHR, textStatus, errorThrown)  {
                console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);
            }
        })

statusCode: is useful when you want to call different functions for different status codes that you return from server.

You can see list of different Http Status codes here:Wikipedia

Additional resources:

  1. Returning Server-Side Errors from AJAX Calls
  2. Returning a JsonResult within the Error function of JQuery Ajax
  3. Handling Ajax errors with jQuery

URL for public Amazon S3 bucket

The URL structure you're referring to is called the REST endpoint, as opposed to the Web Site Endpoint.


Note: Since this answer was originally written, S3 has rolled out dualstack support on REST endpoints, using new hostnames, while leaving the existing hostnames in place. This is now integrated into the information provided, below.


If your bucket is really in the us-east-1 region of AWS -- which the S3 documentation formerly referred to as the "US Standard" region, but was subsequently officially renamed to the "U.S. East (N. Virginia) Region" -- then http://s3-us-east-1.amazonaws.com/bucket/ is not the correct form for that endpoint, even though it looks like it should be. The correct format for that region is either http://s3.amazonaws.com/bucket/ or http://s3-external-1.amazonaws.com/bucket/

The format you're using is applicable to all the other S3 regions, but not US Standard US East (N. Virginia) [us-east-1].

S3 now also has dual-stack endpoint hostnames for the REST endpoints, and unlike the original endpoint hostnames, the names of these have a consistent format across regions, for example s3.dualstack.us-east-1.amazonaws.com. These endpoints support both IPv4 and IPv6 connectivity and DNS resolution, but are otherwise functionally equivalent to the existing REST endpoints.

If your permissions and configuration are set up such that the web site endpoint works, then the REST endpoint should work, too.

However... the two endpoints do not offer the same functionality.

Roughly speaking, the REST endpoint is better-suited for machine access and the web site endpoint is better suited for human access, since the web site endpoint offers friendly error messages, index documents, and redirects, while the REST endpoint doesn't. On the other hand, the REST endpoint offers HTTPS and support for signed URLs, while the web site endpoint doesn't.

Choose the correct type of endpoint (REST or web site) for your application:

http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteEndpoints.html#WebsiteRestEndpointDiff


¹ s3-external-1.amazonaws.com has been referred to as the "Northern Virginia endpoint," in contrast to the "Global endpoint" s3.amazonaws.com. It was unofficially possible to get read-after-write consistency on new objects in this region if the "s3-external-1" hostname was used, because this would send you to a subset of possible physical endpoints that could provide that functionality. This behavior is now officially supported on this endpoint, so this is probably the better choice in many applications. Previously, s3-external-2 had been referred to as the "Pacific Northwest endpoint" for US-Standard, though it is now a CNAME in DNS for s3-external-1 so s3-external-2 appears to have no purpose except backwards-compatibility.

How to achieve ripple animation using support library?

sometimes will b usable this line on any layout or components.

 android:background="?attr/selectableItemBackground"

Like as.

 <RelativeLayout
                android:id="@+id/relative_ticket_checkin"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="?attr/selectableItemBackground">

Default fetch type for one-to-one, many-to-one and one-to-many in Hibernate

It depends on whether you are using JPA or Hibernate.

From the JPA 2.0 spec, the defaults are:

OneToMany: LAZY
ManyToOne: EAGER
ManyToMany: LAZY
OneToOne: EAGER

And in hibernate, all is Lazy

UPDATE:

The latest version of Hibernate aligns with the above JPA defaults.

How to create User/Database in script for Docker Postgres

You can now put .sql files inside the init directory:

From the docs

If you would like to do additional initialization in an image derived from this one, add one or more *.sql or *.sh scripts under /docker-entrypoint-initdb.d (creating the directory if necessary). After the entrypoint calls initdb to create the default postgres user and database, it will run any *.sql files and source any *.sh scripts found in that directory to do further initialization before starting the service.

So copying your .sql file in will work.

How to get content body from a httpclient call?

The way you are using await/async is poor at best, and it makes it hard to follow. You are mixing await with Task'1.Result, which is just confusing. However, it looks like you are looking at a final task result, rather than the contents.

I've rewritten your function and function call, which should fix your issue:

async Task<string> GetResponseString(string text)
{
    var httpClient = new HttpClient();

    var parameters = new Dictionary<string, string>();
    parameters["text"] = text;

    var response = await httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters));
    var contents = await response.Content.ReadAsStringAsync();

    return contents;
}

And your final function call:

Task<string> result = GetResponseString(text);
var finalResult = result.Result;

Or even better:

var finalResult = await GetResponseString(text);

Seaborn plots not showing up

I come to this question quite regularly and it always takes me a while to find what I search:

import seaborn as sns
import matplotlib.pyplot as plt

plt.show()  # <--- This is what you are looking for

Please note: In Python 2, you can also use sns.plt.show(), but not in Python 3.

Complete Example

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Visualize C_0.99 for all languages except the 10 with most characters."""

import seaborn as sns
import matplotlib.pyplot as plt

l = [41, 44, 46, 46, 47, 47, 48, 48, 49, 51, 52, 53, 53, 53, 53, 55, 55, 55,
     55, 56, 56, 56, 56, 56, 56, 57, 57, 57, 57, 57, 57, 57, 57, 58, 58, 58,
     58, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60, 60, 60, 60, 60, 60, 60, 61,
     61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 62, 62, 62, 62, 62, 62, 62, 62,
     62, 63, 63, 63, 63, 63, 63, 63, 63, 63, 64, 64, 64, 64, 64, 64, 64, 65,
     65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 66, 66, 66, 66, 66, 66, 66,
     67, 67, 67, 67, 67, 67, 67, 67, 68, 68, 68, 68, 68, 69, 69, 69, 70, 70,
     70, 70, 71, 71, 71, 71, 71, 72, 72, 72, 72, 73, 73, 73, 73, 73, 73, 73,
     74, 74, 74, 74, 74, 75, 75, 75, 76, 77, 77, 78, 78, 79, 79, 79, 79, 80,
     80, 80, 80, 81, 81, 81, 81, 83, 84, 84, 85, 86, 86, 86, 86, 87, 87, 87,
     87, 87, 88, 90, 90, 90, 90, 90, 90, 91, 91, 91, 91, 91, 91, 91, 91, 92,
     92, 93, 93, 93, 94, 95, 95, 96, 98, 98, 99, 100, 102, 104, 105, 107, 108,
     109, 110, 110, 113, 113, 115, 116, 118, 119, 121]

sns.distplot(l, kde=True, rug=False)

plt.show()

Gives

enter image description here

Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\

mysqli_select_db() should have 2 parameters, the connection link and the database name -

mysqli_select_db($con, 'phpcadet') or die(mysqli_error($con));

Using mysqli_error in the die statement will tell you exactly what is wrong as opposed to a generic error message.

How to install Ruby 2.1.4 on Ubuntu 14.04

update ubuntu:

 sudo apt-get update
 sudo apt-get install git-core curl zlib1g-dev build-essential libssl-dev libreadline-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev libcurl4-openssl-dev python-software-properties libffi-dev

Install rvm, which manages the ruby versions:

to install rvm use the following command.

 \curl -sSL https://get.rvm.io | bash -s stable
 source ~/.bash_profile
 rvm install ruby-2.1.4

Check ruby versions installed and in use:

rvm list
rvm use --default ruby-2.1.4

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key country

I had a the same problem and I found the solution that I should put the code to retrieve the drop down list from database in the Edit Method. It worked for me. Solution for the similar problem

Mongodb: Failed to connect to 127.0.0.1:27017, reason: errno:10061

Try this, it worked for me.

mongod --storageEngine=mmpav1

How do I remove my IntelliJ license in 2019.3?

in linux/ubuntu you can do, run following commands

cd ~/.config/JetBrains/PyCharm2020.1
rm eval/PyCharm201.evaluation.key
sed -i '/evlsprt/d' options/other.xml
cd ~/.java/.userPrefs/jetbrains
rm -rf pycharm*

Laravel Mail::send() sending to multiple to or bcc addresses

I am using Laravel 5.6 and the Notifications Facade.

If I set a variable with comma separating the e-mails and try to send it, I get the error: "Address in mail given does not comply with RFC 2822, 3.6.2"

So, to solve the problem, I got the solution idea from @Toskan, coding the following.

        // Get data from Database
        $contacts = Contacts::select('email')
            ->get();

        // Create an array element
        $contactList = [];
        $i=0;

        // Fill the array element
        foreach($contacts as $contact){
            $contactList[$i] = $contact->email;
            $i++;
        }

        .
        .
        .

        \Mail::send('emails.template', ['templateTitle'=>$templateTitle, 'templateMessage'=>$templateMessage, 'templateSalutation'=>$templateSalutation, 'templateCopyright'=>$templateCopyright], function($message) use($emailReply, $nameReply, $contactList) {
                $message->from('[email protected]', 'Some Company Name')
                        ->replyTo($emailReply, $nameReply)
                        ->bcc($contactList, 'Contact List')
                        ->subject("Subject title");
            });

It worked for me to send to one or many recipients.

How to scanf only integer?

I know how this can be done using fgets and strtol, I would like to know how this can be done using scanf() (if possible).

As the other answers say, scanf isn't really suitable for this, fgets and strtol is an alternative (though fgets has the drawback that it's hard to detect a 0-byte in the input and impossible to tell what has been input after a 0-byte, if any).

For sake of completeness (and assuming valid input is an integer followed by a newline):

while(scanf("%d%1[\n]", &n, (char [2]){ 0 }) < 2)

Alternatively, use %n before and after %*1[\n] with assignment-suppression. Note, however (from the Debian manpage):

This is not a conversion, although it can be suppressed with the * assignment-suppression character. The C standard says: "Execution of a %n directive does not increment the assignment count returned at the completion of execution" but the Corrigendum seems to contradict this. Probably it is wise not to make any assumptions on the effect of %n conversions on the return value.

Cannot catch toolbar home button click event

This is how I do it to return to the right fragment otherwise if you have several fragments on the same level it would return to the first one if you don´t override the toolbar back button behavior.

toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            finish();
        }
    });

Summarizing count and conditional aggregate functions on the same factor

Assuming that your original dataset is similar to the one you created (i.e. with NA as character. You could specify na.strings while reading the data using read.table. But, I guess NAs would be detected automatically.

The price column is factor which needs to be converted to numeric class. When you use as.numeric, all the non-numeric elements (i.e. "NA", FALSE) gets coerced to NA) with a warning.

library(dplyr)
df %>%
     mutate(price=as.numeric(as.character(price))) %>%  
     group_by(company, year, product) %>%
     summarise(total.count=n(), 
               count=sum(is.na(price)), 
               avg.price=mean(price,na.rm=TRUE),
               max.price=max(price, na.rm=TRUE))

data

I am using the same dataset (except the ... row) that was showed.

df = tbl_df(data.frame(company=c("Acme", "Meca", "Emca", "Acme", "Meca","Emca"),
 year=c("2011", "2010", "2009", "2011", "2010", "2013"), product=c("Wrench", "Hammer",
 "Sonic Screwdriver", "Fairy Dust", "Kindness", "Helping Hand"), price=c("5.67",
 "7.12", "12.99", "10.99", "NA",FALSE)))

How to scroll to the bottom of a RecyclerView? scrollToPosition doesn't work

If none of these worked,

you should try to use :

ConstraintLayout targetView = (ConstraintLayout) recyclerView.findViewHolderForAdapterPosition(adapter.getItemCount()-1).itemView;
targetView.getParent().requestChildFocus(targetView, targetView);

By doing this, you are requesting a certain ConstraintLayout (Or whatever you have) to be displayed. The scroll is instant.

I works even with keyboard shown.

How to delete specific columns with VBA?

To answer the question How to delete specific columns in vba for excel. I use Array as below.

sub del_col()

dim myarray as variant
dim i as integer

myarray = Array(10, 9, 8)'Descending to Ascending
For i = LBound(myarray) To UBound(myarray)
    ActiveSheet.Columns(myarray(i)).EntireColumn.Delete
Next i

end sub

How do I create a sequence in MySQL?

Check out this article. I believe it should help you get what you are wanting. If your table already exists, and it has data in it already, the error you are getting may be due to the auto_increment trying to assign a value that already exists for other records.

In short, as others have already mentioned in comments, sequences, as they are thought of and handled in Oracle, do not exist in MySQL. However, you can likely use auto_increment to accomplish what you want.

Without additional details on the specific error, it is difficult to provide more specific help.

UPDATE

CREATE TABLE ORD (
  ORDID INT NOT NULL AUTO_INCREMENT,
  //Rest of table code
  PRIMARY KEY (ordid)
)
AUTO_INCREMENT = 622;

This link is also helpful for describing usage of auto_increment. Setting the AUTO_INCREMENT value appears to be a table option, and not something that is specified as a column attribute specifically.

Also, per one of the links from above, you can alternatively set the auto increment start value via an alter to your table.

ALTER TABLE ORD AUTO_INCREMENT = 622;

UPDATE 2 Here is a link to a working sqlfiddle example, using auto increment.
I hope this info helps.

How to test if a string contains one of the substrings in a list, in pandas?

Here is a one line lambda that also works:

df["TrueFalse"] = df['col1'].apply(lambda x: 1 if any(i in x for i in searchfor) else 0)

Input:

searchfor = ['og', 'at']

df = pd.DataFrame([('cat', 1000.0), ('hat', 2000000.0), ('dog', 1000.0), ('fog', 330000.0),('pet', 330000.0)], columns=['col1', 'col2'])

   col1  col2
0   cat 1000.0
1   hat 2000000.0
2   dog 1000.0
3   fog 330000.0
4   pet 330000.0

Apply Lambda:

df["TrueFalse"] = df['col1'].apply(lambda x: 1 if any(i in x for i in searchfor) else 0)

Output:

    col1    col2        TrueFalse
0   cat     1000.0      1
1   hat     2000000.0   1
2   dog     1000.0      1
3   fog     330000.0    1
4   pet     330000.0    0

The following classes could not be instantiated: - android.support.v7.widget.Toolbar

The solutions above didn't help me. I've tried 2 first steps from this link. Worked fine for me. But don't forget to

import com.melnykov.fab.FloatingActionButton; 

instead of

import android.support.design.widget.FloatingActionButton;

in your MainActivity.java

Can't install Scipy through pip

I face same problem when install Scipy under ubuntu.
I had to use command:

$ sudo apt-get install libatlas-base-dev gfortran
$ sudo pip3 install scipy

You can get more details here Installing SciPy with pip
Sorry don't know how to do it under OS X Yosemite.

Postman: sending nested JSON object

To post a nested object with the key-value interface you can use a similar method to sending arrays. Pass an object key in square brackets after the object index.

Passing a nested item with Postman

"Items": [
      {
        "sku": "9257",
        "Price": "100"
      }
 ]

What's the difference between Apache's Mesos and Google's Kubernetes

I like this short video here mesos learning material

with bare metal clusters, you would need to spawn stacks like HDFS, SPARK, MR etc... so if you launch tasks related to these using only bare metal cluster management, there will be a lot cold starting time.

with mesos, you can install these services on top of the bare metals and you can avoid the bring up time of those base services. This is something mesos does well. and can be utilised by kubernetes building on top of it.

How to perform update operations on columns of type JSONB in Postgres 9.4

This is coming in 9.5 in the form of jsonb_set by Andrew Dunstan based on an existing extension jsonbx that does work with 9.4

Installing tkinter on ubuntu 14.04

In Ubuntu 14.04.2 LTS:

  1. Go to Software Center and remove "IDLE(using Python-2.7)".

  2. Install "IDLE(using Python-3.4)".

Try again. This step worked for me.

Change status bar color with AppCompat ActionBarActivity

I don't think the status bar color has been implemented in AppCompat yet. These are the attributes which are available:

    <!-- ============= -->
    <!-- Color palette -->
    <!-- ============= -->

    <!-- The primary branding color for the app. By default, this is the color applied to the
         action bar background. -->
    <attr name="colorPrimary" format="color" />

    <!-- Dark variant of the primary branding color. By default, this is the color applied to
         the status bar (via statusBarColor) and navigation bar (via navigationBarColor). -->
    <attr name="colorPrimaryDark" format="color" />

    <!-- Bright complement to the primary branding color. By default, this is the color applied
         to framework controls (via colorControlActivated). -->
    <attr name="colorAccent" format="color" />

    <!-- The color applied to framework controls in their normal state. -->
    <attr name="colorControlNormal" format="color" />

    <!-- The color applied to framework controls in their activated (ex. checked) state. -->
    <attr name="colorControlActivated" format="color" />

    <!-- The color applied to framework control highlights (ex. ripples, list selectors). -->
    <attr name="colorControlHighlight" format="color" />

    <!-- The color applied to framework buttons in their normal state. -->
    <attr name="colorButtonNormal" format="color" />

    <!-- The color applied to framework switch thumbs in their normal state. -->
    <attr name="colorSwitchThumbNormal" format="color" />

(From \sdk\extras\android\support\v7\appcompat\res\values\attrs.xml)

How to filter an array of objects based on values in an inner array with jq?

Here is another solution which uses any/2

map(select(any(.Names[]; contains("data"))|not)|.Id)[]

with the sample data and the -r option it produces

cb94e7a42732b598ad18a8f27454a886c1aa8bbba6167646d8f064cd86191e2b
a4b7e6f5752d8dcb906a5901f7ab82e403b9dff4eaaeebea767a04bac4aada19

Query based on multiple where clauses in Firebase

ref.orderByChild("lead").startAt("Jack Nicholson").endAt("Jack Nicholson").listner....

This will work.

Spring Boot yaml configuration for a list of strings

Well, the only thing I can make it work is like so:

servers: >
    dev.example.com,
    another.example.com

@Value("${servers}")
private String[] array;

And dont forget the @Configuration above your class....

Without the "," separation, no such luck...

Works too (boot 1.5.8 versie)

servers: 
       dev.example.com,
       another.example.com

How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?

I had a similar problem but I came to a different solution that may help others. I used Spring Profiles to separate out test and app configuration classes.

  1. Create a TestConfig class with a specific profile and exclude any app configuration from component scan you wish here.

  2. In your test class set the profile to match the TestConfig and include it using the @ContextConfiguration annotation.

For example:

configuration:

@Profile("test")
@Configuration
@EnableWebMvc
@ComponentScan(
    basePackages="your.base.package",
    excludeFilters = {
            @Filter(type = ASSIGNABLE_TYPE,
                    value = {
                            ExcludedAppConfig1.class,
                            ExcludedAppConfig2.class
            })
    })
public class TestConfig { ...}

test:

@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestConfig.class)
@WebAppConfiguration
public class SomeTest{ ... }

Android Studio - Unable to find valid certification path to requested target

Go to The Gradle Console in bottom right and open it.Here you will be seeing some https/https calls click on the links and open them in web browser then try clean build it worked for me.

I think It is happening because studio is not able to get the response from the hit.

Fade In on Scroll Down, Fade Out on Scroll Up - based on element position in window

Sorry this is and old thread but some people would still need this I guess,

Note: I achieved this using Animate.css library for animating the fade.

I used your code and just added .hidden class (using bootstrap's hidden class) but you can still just define .hidden { opacity: 0; }

$(document).ready(function() {

/* Every time the window is scrolled ... */

$(window).scroll( function(){

/* Check the location of each desired element */
$('.hideme').each( function(i){

    var bottom_of_object = $(this).position().top + $(this).outerHeight();
    var bottom_of_window = $(window).scrollTop() + $(window).height();


    /* If the object is completely visible in the window, fade it it */
    if( bottom_of_window > bottom_of_object ){

        $(this).removeClass('hidden');
        $(this).addClass('animated fadeInUp');
    }    else {
            $(this).addClass('hidden');
               }

}); 
}); 
});

Another Note: Applying this to containers might cause it to be glitchy.

What is the difference between compileSdkVersion and targetSdkVersion?

My 2 cents: Compile against any version of the SDK but take care not to call any APIs that your "minimum SDK version" does not support. That means you "could" compile against the latest version of the SDK.

As for "target version" it simply refers to what you planned to target in the first place and have possibly tested against. If you haven't done the due diligence then this is the way to inform Android that it needs to perform some additional checks before it deploys your lets say "Lollipop" targeted app on "Oreo".

So the "target version" is obviously not lower than your "minimum SDK version" but it can't be higher than your "compiled version".

NLTK and Stopwords Fail #lookuperror

import nltk
nltk.download()

Click on download button when gui prompted. It worked for me.(nltk.download('stopwords') doesn't work for me)

Xcode project not showing list of simulators

I encountered this problem when I update my xcode to 8.2beta (with the app name xcode-beta.app), I found the answer above by Jeremy Huddleston Sequoia and tried to rename xcode-beta.app to xcode.app, it worked. I guess the name should be xcode.app to use the simulators, even if you didn't changed the name by yourself when you download the beta one.

Matplotlib: ValueError: x and y must have same first dimension

Changing your lists to numpy arrays will do the job!!

import matplotlib.pyplot as plt
from scipy import stats
import numpy as np 

x = np.array([0.46,0.59,0.68,0.99,0.39,0.31,1.09,0.77,0.72,0.49,0.55,0.62,0.58,0.88,0.78]) # x is a numpy array now
y = np.array([0.315,0.383,0.452,0.650,0.279,0.215,0.727,0.512,0.478,0.335,0.365,0.424,0.390,0.585,0.511]) # y is a numpy array now
xerr = [0.01]*15
yerr = [0.001]*15

plt.rc('font', family='serif', size=13)
m, b = np.polyfit(x, y, 1)
plt.plot(x,y,'s',color='#0066FF')
plt.plot(x, m*x + b, 'r-') #BREAKS ON THIS LINE
plt.errorbar(x,y,xerr=xerr,yerr=0,linestyle="None",color='black')
plt.xlabel('$\Delta t$ $(s)$',fontsize=20)
plt.ylabel('$\Delta p$ $(hPa)$',fontsize=20)
plt.autoscale(enable=True, axis=u'both', tight=False)
plt.grid(False)
plt.xlim(0.2,1.2)
plt.ylim(0,0.8)
plt.show()

enter image description here

How to get PID by process name?

For posix (Linux, BSD, etc... only need /proc directory to be mounted) it's easier to work with os files in /proc. It's pure python, no need to call shell programs outside.

Works on python 2 and 3 ( The only difference (2to3) is the Exception tree, therefore the "except Exception", which I dislike but kept to maintain compatibility. Also could've created a custom exception.)

#!/usr/bin/env python

import os
import sys


for dirname in os.listdir('/proc'):
    if dirname == 'curproc':
        continue

    try:
        with open('/proc/{}/cmdline'.format(dirname), mode='rb') as fd:
            content = fd.read().decode().split('\x00')
    except Exception:
        continue

    for i in sys.argv[1:]:
        if i in content[0]:
            print('{0:<12} : {1}'.format(dirname, ' '.join(content)))

Sample Output (it works like pgrep):

phoemur ~/python $ ./pgrep.py bash
1487         : -bash 
1779         : /bin/bash

How to check object is nil or not in swift?

The null check is really done nice with guard keyword in swift. It improves the code readability and the scope of the variables are still available after the nil checks if you want to use them.

func setXYX -> Void{

     guard a != nil  else {
        return;
    }

    guard  b != nil else {
        return;
    }

    print (" a and b is not null");
}

Material effect on button with background color

There are two approaches explained in the great tutorial be Alex Lockwood: http://www.androiddesignpatterns.com/2016/08/coloring-buttons-with-themeoverlays-background-tints.html:

Approach #1: Modifying the button’s background color w/ a ThemeOverlay

<!-- res/values/themes.xml -->
<style name="RedButtonLightTheme" parent="ThemeOverlay.AppCompat.Light">
    <item name="colorAccent">@color/googred500</item>
</style>

<Button
    style="@style/Widget.AppCompat.Button.Colored"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:theme="@style/RedButtonLightTheme"/>

Approach #2: Setting the AppCompatButton’s background tint

<!-- res/color/btn_colored_background_tint.xml -->
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Disabled state. -->
    <item android:state_enabled="false"
          android:color="?attr/colorButtonNormal"
          android:alpha="?android:attr/disabledAlpha"/>

    <!-- Enabled state. -->
    <item android:color="?attr/colorAccent"/>

</selector>

<android.support.v7.widget.AppCompatButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:backgroundTint="@color/btn_colored_background_tint"/>

TypeError: unsupported operand type(s) for -: 'list' and 'list'

The operations needed to be performed, require numpy arrays either created via

np.array()

or can be converted from list to an array via

np.stack()

As in the above mentioned case, 2 lists are inputted as operands it triggers the error.

What's the difference between map() and flatMap() methods in Java 8?

Map:- This method takes one Function as an argument and returns a new stream consisting of the results generated by applying the passed function to all the elements of the stream.

Let's imagine, I have a list of integer values ( 1,2,3,4,5 ) and one function interface whose logic is square of the passed integer. ( e -> e * e ).

List<Integer> intList = Arrays.asList(1, 2, 3, 4, 5);

List<Integer> newList = intList.stream().map( e -> e * e ).collect(Collectors.toList());

System.out.println(newList);

output:-

[1, 4, 9, 16, 25]

As you can see, an output is a new stream whose values are square of values of the input stream.

[1, 2, 3, 4, 5] -> apply e -> e * e -> [ 1*1, 2*2, 3*3, 4*4, 5*5 ] -> [1, 4, 9, 16, 25 ]

http://codedestine.com/java-8-stream-map-method/

FlatMap :- This method takes one Function as an argument, this function accepts one parameter T as an input argument and returns one stream of parameter R as a return value. When this function is applied to each element of this stream, it produces a stream of new values. All the elements of these new streams generated by each element are then copied to a new stream, which will be a return value of this method.

Let's image, I have a list of student objects, where each student can opt for multiple subjects.

List<Student> studentList = new ArrayList<Student>();

  studentList.add(new Student("Robert","5st grade", Arrays.asList(new String[]{"history","math","geography"})));
  studentList.add(new Student("Martin","8st grade", Arrays.asList(new String[]{"economics","biology"})));
  studentList.add(new Student("Robert","9st grade", Arrays.asList(new String[]{"science","math"})));

  Set<Student> courses = studentList.stream().flatMap( e -> e.getCourse().stream()).collect(Collectors.toSet());

  System.out.println(courses);

output:-

[economics, biology, geography, science, history, math]

As you can see, an output is a new stream whose values are a collection of all the elements of the streams return by each element of the input stream.

[ S1 , S2 , S3 ] -> [ {"history","math","geography"}, {"economics","biology"}, {"science","math"} ] -> take unique subjects -> [economics, biology, geography, science, history, math]

http://codedestine.com/java-8-stream-flatmap-method/

How do I get the position selected in a RecyclerView?

No need to have your ViewHolder implementing View.OnClickListener. You can get directly the clicked position by setting a click listener in the method onCreateViewHolder of RecyclerView.Adapter here is a sample of code :

public class ItemListAdapterRecycler extends RecyclerView.Adapter<ItemViewHolder>
{

    private final List<Item> items;

    public ItemListAdapterRecycler(List<Item> items)
    {
        this.items = items;
    }

    @Override
    public ItemViewHolder onCreateViewHolder(final ViewGroup parent, int viewType)
    {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row, parent, false);

        view.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                int currentPosition = getClickedPosition(view);
                Log.d("DEBUG", "" + currentPosition);
            }
        });

        return new ItemViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ItemViewHolder itemViewHolder, int position)
    {
        ...
    }

    @Override
    public int getItemCount()
    {
        return items.size();
    }

    private int getClickedPosition(View clickedView)
    {
        RecyclerView recyclerView = (RecyclerView) clickedView.getParent();
        ItemViewHolder currentViewHolder = (ItemViewHolder) recyclerView.getChildViewHolder(clickedView);
        return currentViewHolder.getAdapterPosition();
    }

}

How to convert a python numpy array to an RGB image with Opencv 2.4?

You don't need to convert NumPy array to Mat because OpenCV cv2 module can accept NumPyarray. The only thing you need to care for is that {0,1} is mapped to {0,255} and any value bigger than 1 in NumPy array is equal to 255. So you should divide by 255 in your code, as shown below.

img = numpy.zeros([5,5,3])

img[:,:,0] = numpy.ones([5,5])*64/255.0
img[:,:,1] = numpy.ones([5,5])*128/255.0
img[:,:,2] = numpy.ones([5,5])*192/255.0

cv2.imwrite('color_img.jpg', img)
cv2.imshow("image", img)
cv2.waitKey()

Convert Mat to Array/Vector in OpenCV

If the memory of the Mat mat is continuous (all its data is continuous), you can directly get its data to a 1D array:

std::vector<uchar> array(mat.rows*mat.cols*mat.channels());
if (mat.isContinuous())
    array = mat.data;

Otherwise, you have to get its data row by row, e.g. to a 2D array:

uchar **array = new uchar*[mat.rows];
for (int i=0; i<mat.rows; ++i)
    array[i] = new uchar[mat.cols*mat.channels()];

for (int i=0; i<mat.rows; ++i)
    array[i] = mat.ptr<uchar>(i);

UPDATE: It will be easier if you're using std::vector, where you can do like this:

std::vector<uchar> array;
if (mat.isContinuous()) {
  // array.assign(mat.datastart, mat.dataend); // <- has problems for sub-matrix like mat = big_mat.row(i)
  array.assign(mat.data, mat.data + mat.total()*mat.channels());
} else {
  for (int i = 0; i < mat.rows; ++i) {
    array.insert(array.end(), mat.ptr<uchar>(i), mat.ptr<uchar>(i)+mat.cols*mat.channels());
  }
}

p.s.: For cv::Mats of other types, like CV_32F, you should do like this:

std::vector<float> array;
if (mat.isContinuous()) {
  // array.assign((float*)mat.datastart, (float*)mat.dataend); // <- has problems for sub-matrix like mat = big_mat.row(i)
  array.assign((float*)mat.data, (float*)mat.data + mat.total()*mat.channels());
} else {
  for (int i = 0; i < mat.rows; ++i) {
    array.insert(array.end(), mat.ptr<float>(i), mat.ptr<float>(i)+mat.cols*mat.channels());
  }
}

UPDATE2: For OpenCV Mat data continuity, it can be summarized as follows:

  • Matrices created by imread(), clone(), or a constructor will always be continuous.
  • The only time a matrix will not be continuous is when it borrows data (except the data borrowed is continuous in the big matrix, e.g. 1. single row; 2. multiple rows with full original width) from an existing matrix (i.e. created out of an ROI of a big mat).

Please check out this code snippet for demonstration.

Multiple scenarios @RequestMapping produces JSON/XML together with Accept or ResponseEntity

All your problems are that you are mixing content type negotiation with parameter passing. They are things at different levels. More specific, for your question 2, you constructed the response header with the media type your want to return. The actual content negotiation is based on the accept media type in your request header, not response header. At the point the execution reaches the implementation of the method getPersonFormat, I am not sure whether the content negotiation has been done or not. Depends on the implementation. If not and you want to make the thing work, you can overwrite the request header accept type with what you want to return.

return new ResponseEntity<>(PersonFactory.createPerson(), httpHeaders, HttpStatus.OK);

Entity Framework Queryable async

The problem seems to be that you have misunderstood how async/await work with Entity Framework.

About Entity Framework

So, let's look at this code:

public IQueryable<URL> GetAllUrls()
{
    return context.Urls.AsQueryable();
}

and example of it usage:

repo.GetAllUrls().Where(u => <condition>).Take(10).ToList()

What happens there?

  1. We are getting IQueryable object (not accessing database yet) using repo.GetAllUrls()
  2. We create a new IQueryable object with specified condition using .Where(u => <condition>
  3. We create a new IQueryable object with specified paging limit using .Take(10)
  4. We retrieve results from database using .ToList(). Our IQueryable object is compiled to sql (like select top 10 * from Urls where <condition>). And database can use indexes, sql server send you only 10 objects from your database (not all billion urls stored in database)

Okay, let's look at first code:

public async Task<IQueryable<URL>> GetAllUrlsAsync()
{
    var urls = await context.Urls.ToListAsync();
    return urls.AsQueryable();
}

With the same example of usage we got:

  1. We are loading in memory all billion urls stored in your database using await context.Urls.ToListAsync();.
  2. We got memory overflow. Right way to kill your server

About async/await

Why async/await is preferred to use? Let's look at this code:

var stuff1 = repo.GetStuff1ForUser(userId);
var stuff2 = repo.GetStuff2ForUser(userId);
return View(new Model(stuff1, stuff2));

What happens here?

  1. Starting on line 1 var stuff1 = ...
  2. We send request to sql server that we want to get some stuff1 for userId
  3. We wait (current thread is blocked)
  4. We wait (current thread is blocked)
  5. .....
  6. Sql server send to us response
  7. We move to line 2 var stuff2 = ...
  8. We send request to sql server that we want to get some stuff2 for userId
  9. We wait (current thread is blocked)
  10. And again
  11. .....
  12. Sql server send to us response
  13. We render view

So let's look to an async version of it:

var stuff1Task = repo.GetStuff1ForUserAsync(userId);
var stuff2Task = repo.GetStuff2ForUserAsync(userId);
await Task.WhenAll(stuff1Task, stuff2Task);
return View(new Model(stuff1Task.Result, stuff2Task.Result));

What happens here?

  1. We send request to sql server to get stuff1 (line 1)
  2. We send request to sql server to get stuff2 (line 2)
  3. We wait for responses from sql server, but current thread isn't blocked, he can handle queries from another users
  4. We render view

Right way to do it

So good code here:

using System.Data.Entity;

public IQueryable<URL> GetAllUrls()
{
   return context.Urls.AsQueryable();
}

public async Task<List<URL>> GetAllUrlsByUser(int userId) {
   return await GetAllUrls().Where(u => u.User.Id == userId).ToListAsync();
}

Note, than you must add using System.Data.Entity in order to use method ToListAsync() for IQueryable.

Note, that if you don't need filtering and paging and stuff, you don't need to work with IQueryable. You can just use await context.Urls.ToListAsync() and work with materialized List<Url>.

How to check the exit status using an if statement

If you are writing a function, which is always preferred, you should propagate the error like this:

function() {
    if some_command; then
        echo worked
    else
        return $?
fi
}

This will propagate the error to the caller, so that he can do things like function && next as expected.

How to solve Notice: Undefined index: id in C:\xampp\htdocs\invmgt\manufactured_goods\change.php on line 21

Simply add this

$id = ''; 
if( isset( $_GET['id'])) {
    $id = $_GET['id']; 
} 

Get top most UIViewController

To find the visible viewController in Swift 3

if let viewControllers = window?.rootViewController?.childViewControllers {

     let prefs = UserDefaults.standard

     if viewControllers[viewControllers.count - 1] is ABCController{
        print("[ABCController] is visible")

     }
}

This code find the last added or the last active controller visible.

This I have used in AppDelegate to find active view Controller