Programs & Examples On #Double checked locking

Double-checked locking is a software design pattern used to reduce the overhead of acquiring a lock by first testing the locking criterion without actually acquiring the lock.

Python main call within class

That entire block is misplaced.

class Example(object):
    def main(self):     
        print "Hello World!"

if __name__ == '__main__':
    Example().main()

But you really shouldn't be using a class just to run your main code.

How to get value by key from JObject?

This should help -

var json = "{'@STARTDATE': '2016-02-17 00:00:00.000',  '@ENDDATE': '2016-02-18 23:59:00.000' }";
var fdate = JObject.Parse(json)["@STARTDATE"];

Visual Studio 2015 is very slow

It is most likely because you uninstalled some SQL Server components Visual Studio is using. Though Visual Studio still works, it's very slow.

Just go to "Programs and Features" in the Control Panel and repair Visual Studio. The needed Visual Studio components will be installed again and Visual Studio will be back as fast as before.

How to detect scroll position of page using jQuery

You can extract the scroll position using jQuery's .scrollTop() method

$(window).scroll(function (event) {
    var scroll = $(window).scrollTop();
    // Do something
});

Create a table without a header in Markdown

Omitting the header above the divider produces a headerless table in at least Perl Text::MultiMarkdown and in FletcherPenney MultiMarkdown

|-------------|--------|
|**Name:**    |John Doe|
|**Position:**|CEO     |

See PHP Markdown feature request


Empty headers in PHP Parsedown produce tables with empty headers that are usually invisible (depending on your CSS) and so look like headerless tables.

|     |     |
|-----|-----|
|Foo  |37   |
|Bar  |101  |

SELECT * FROM multiple tables. MySQL

In order to get rid of duplicates, you can group by drinks.id. But that way you'll get only one photo for each drinks.id (which photo you'll get depends on database internal implementation).

Though it is not documented, in case of MySQL, you'll get the photo with lowest id (in my experience I've never seen other behavior).

SELECT name, price, photo 
FROM drinks, drinks_photos 
WHERE drinks.id = drinks_id
GROUP BY drinks.id

Difference between Pragma and Cache-Control headers?

Pragma is the HTTP/1.0 implementation and cache-control is the HTTP/1.1 implementation of the same concept. They both are meant to prevent the client from caching the response. Older clients may not support HTTP/1.1 which is why that header is still in use.

How to customize <input type="file">?

Here is a quick pure CSS workaround (works on chrome and has a FireFox fallback included), including the file name,a label and an custom upload button, does what it should - no need of JavaScript at all!

Note: ? This works on Chrome and has a FireFox fallback - anyways, I would not use it on a real world website - if browser compatibility is a thing to you (what it should be). So it's more kind of experimental.

_x000D_
_x000D_
.fileUploadInput {_x000D_
  display: grid;_x000D_
  grid-gap: 10px;_x000D_
  position: relative;_x000D_
  z-index: 1; }_x000D_
  _x000D_
  .fileUploadInput label {_x000D_
    display: flex;_x000D_
    align-items: center;_x000D_
    color: setColor(primary, 0.5);_x000D_
    background: setColor(white);_x000D_
    transition: .4s ease;_x000D_
    font-family: arial, sans-serif;_x000D_
    font-size: .75em;_x000D_
    font-weight: regular; }_x000D_
    _x000D_
  .fileUploadInput input {_x000D_
    position: relative;_x000D_
    z-index: 1;_x000D_
    padding: 0 gap(m);_x000D_
    width: 100%;_x000D_
    height: 50px;_x000D_
    border: 1px solid #323262;_x000D_
    border-radius: 3px;_x000D_
    font-family: arial, sans-serif;_x000D_
    font-size: 1rem;_x000D_
    font-weight: regular; }_x000D_
    .fileUploadInput input[type="file"] {_x000D_
      padding: 0 gap(m); }_x000D_
      .fileUploadInput input[type="file"]::-webkit-file-upload-button {_x000D_
        visibility: hidden;_x000D_
        margin-left: 10px;_x000D_
        padding: 0;_x000D_
        height: 50px;_x000D_
        width: 0; }_x000D_
        _x000D_
  .fileUploadInput button {_x000D_
    position: absolute;_x000D_
    right: 0;_x000D_
    bottom: 0;_x000D_
    width: 50px;_x000D_
    height: 50px;_x000D_
    line-height: 0;_x000D_
    user-select: none;_x000D_
    color: white;_x000D_
    background-color: #323262;_x000D_
    border-radius: 0 3px 3px 0;_x000D_
    font-family: arial, sans-serif;_x000D_
    font-size: 1rem;_x000D_
    font-weight: 800; }_x000D_
    .fileUploadInput button svg {_x000D_
      width: auto;_x000D_
      height: 50%; }_x000D_
_x000D_
* {_x000D_
  margin: 0px;_x000D_
  padding: 0px;_x000D_
  box-sizing: border-box;_x000D_
  border: 0px;_x000D_
  outline: 0;_x000D_
  background-repeat: no-repeat;_x000D_
  appearance: none;_x000D_
  border-radius: 0;_x000D_
  vertical-align: middle;_x000D_
  font-weight: inherit;_x000D_
  font-style: inherit;_x000D_
  font-family: inherit;_x000D_
  text-decoration: none;_x000D_
  list-style: none;_x000D_
  user-select: text;_x000D_
  line-height: 1.333em; }_x000D_
_x000D_
body {_x000D_
  display: flex;_x000D_
  align-items: center;_x000D_
  justify-content: center;_x000D_
  width: 100%;_x000D_
  height: 100vh;_x000D_
  background: rgba(66, 50, 98, 0.05); }_x000D_
_x000D_
.container {_x000D_
  padding: 25px;_x000D_
  box-shadow: 0 0 20px rgba(66, 50, 98, 0.35);_x000D_
  border: 1px solid #eaeaea;_x000D_
  border-radius: 3px;_x000D_
  background: white; }_x000D_
_x000D_
@-moz-document url-prefix() {_x000D_
.fileUploadInput button{_x000D_
    display: none_x000D_
}_x000D_
}
_x000D_
<!-- Author: Ali Soueidan-->_x000D_
<!-- Author URI: https//: www.alisoueidan.com-->_x000D_
_x000D_
<div class="container">_x000D_
    <div class="fileUploadInput">_x000D_
    <label>? Upload File</label>_x000D_
    <input type="file" />_x000D_
    <button>+</button></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Conditional HTML Attributes using Razor MVC3

I guess a little more convenient and structured way is to use Html helper. In your view it can be look like:

@{
 var htmlAttr = new Dictionary<string, object>();
 htmlAttr.Add("id", strElementId);
 if (!CSSClass.IsEmpty())
 {
   htmlAttr.Add("class", strCSSClass);
 }
}

@* ... *@

@Html.TextBox("somename", "", htmlAttr)

If this way will be useful for you i recommend to define dictionary htmlAttr in your model so your view doesn't need any @{ } logic blocks (be more clear).

PHP cURL GET request and request's body

For those coming to this with similar problems, this request library allows you to make external http requests seemlessly within your php application. Simplified GET, POST, PATCH, DELETE and PUT requests.

A sample request would be as below

use Libraries\Request;

$data = [
  'samplekey' => 'value',
  'otherkey' => 'othervalue'
];

$headers = [
  'Content-Type' => 'application/json',
  'Content-Length' => sizeof($data)
];

$response = Request::post('https://example.com', $data, $headers);
// the $response variable contains response from the request

Documentation for the same can be found in the project's README.md

C# : assign data to properties via constructor vs. instantiating

Second approach is object initializer in C#

Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to explicitly invoke a constructor.

The first approach

var albumData = new Album("Albumius", "Artistus", 2013);

explicitly calls the constructor, whereas in second approach constructor call is implicit. With object initializer you can leave out some properties as well. Like:

 var albumData = new Album
        {
            Name = "Albumius",
        };

Object initializer would translate into something like:

var albumData; 
var temp = new Album();
temp.Name = "Albumius";
temp.Artist = "Artistus";
temp.Year = 2013;
albumData = temp;

Why it uses a temporary object (in debug mode) is answered here by Jon Skeet.

As far as advantages for both approaches are concerned, IMO, object initializer would be easier to use specially if you don't want to initialize all the fields. As far as performance difference is concerned, I don't think there would any since object initializer calls the parameter less constructor and then assign the properties. Even if there is going to be performance difference it should be negligible.

A fatal error occurred while creating a TLS client credential. The internal error state is 10013

Basically we had to enable TLS 1.2 for .NET 4.x. Making this registry changed worked for me, and stopped the event log filling up with the Schannel error.

More information on the answer can be found here

Linked Info Summary

Enable TLS 1.2 at the system (SCHANNEL) level:

Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2]
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001

(equivalent keys are probably also available for other TLS versions)

Tell .NET Framework to use the system TLS versions:

Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001

This may not be desirable for edge cases where .NET Framework 4.x applications need to have different protocols enabled and disabled than the OS does.

How to do a join in linq to sql with method syntax?

var result = from sc in enumerableOfSomeClass
             join soc in enumerableOfSomeOtherClass
             on sc.Property1 equals soc.Property2
             select new { SomeClass = sc, SomeOtherClass = soc };

Would be equivalent to:

var result = enumerableOfSomeClass
    .Join(enumerableOfSomeOtherClass,
          sc => sc.Property1,
          soc => soc.Property2,
          (sc, soc) => new
                       {
                           SomeClass = sc,
                           SomeOtherClass = soc
                       });

As you can see, when it comes to joins, query syntax is usually much more readable than lambda syntax.

Aligning textviews on the left and right edges in Android layout

enter image description here

This Code will Divide the control into two equal sides.

    <LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/linearLayout">
    <TextView
        android:text = "Left Side"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight = "1"
        android:id = "@+id/txtLeft"/>

    <TextView android:text = "Right Side"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight = "1"
        android:id = "@+id/txtRight"/>
    </LinearLayout>

How can I switch views programmatically in a view controller? (Xcode, iPhone)

If you want to present a new view in the same storyboard,

In CurrentViewController.m,

#import "YourViewController.h"

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
YourViewController *viewController = (YourViewController *)[storyboard instantiateViewControllerWithIdentifier:@"YourViewControllerIdentifier"];
[self presentViewController:viewController animated:YES completion:nil];

To set identifier to a view controller, Open MainStoryBoard.storyboard. Select YourViewController View-> Utilities -> ShowIdentityInspector. There you can specify the identifier.

Debug message "Resource interpreted as other but transferred with MIME type application/javascript"

You need to use a tool to view the HTTP headers sent with the file, something like LiveHTTPHeaders or HTTPFox are what I use. If the files are sent from the webserver without a MIME type, or with a default MIME type like text/plain, that might be what this error is about.

How to dispatch a Redux action with a timeout?

Don’t fall into the trap of thinking a library should prescribe how to do everything. If you want to do something with a timeout in JavaScript, you need to use setTimeout. There is no reason why Redux actions should be any different.

Redux does offer some alternative ways of dealing with asynchronous stuff, but you should only use those when you realize you are repeating too much code. Unless you have this problem, use what the language offers and go for the simplest solution.

Writing Async Code Inline

This is by far the simplest way. And there’s nothing specific to Redux here.

store.dispatch({ type: 'SHOW_NOTIFICATION', text: 'You logged in.' })
setTimeout(() => {
  store.dispatch({ type: 'HIDE_NOTIFICATION' })
}, 5000)

Similarly, from inside a connected component:

this.props.dispatch({ type: 'SHOW_NOTIFICATION', text: 'You logged in.' })
setTimeout(() => {
  this.props.dispatch({ type: 'HIDE_NOTIFICATION' })
}, 5000)

The only difference is that in a connected component you usually don’t have access to the store itself, but get either dispatch() or specific action creators injected as props. However this doesn’t make any difference for us.

If you don’t like making typos when dispatching the same actions from different components, you might want to extract action creators instead of dispatching action objects inline:

// actions.js
export function showNotification(text) {
  return { type: 'SHOW_NOTIFICATION', text }
}
export function hideNotification() {
  return { type: 'HIDE_NOTIFICATION' }
}

// component.js
import { showNotification, hideNotification } from '../actions'

this.props.dispatch(showNotification('You just logged in.'))
setTimeout(() => {
  this.props.dispatch(hideNotification())
}, 5000)

Or, if you have previously bound them with connect():

this.props.showNotification('You just logged in.')
setTimeout(() => {
  this.props.hideNotification()
}, 5000)

So far we have not used any middleware or other advanced concept.

Extracting Async Action Creator

The approach above works fine in simple cases but you might find that it has a few problems:

  • It forces you to duplicate this logic anywhere you want to show a notification.
  • The notifications have no IDs so you’ll have a race condition if you show two notifications fast enough. When the first timeout finishes, it will dispatch HIDE_NOTIFICATION, erroneously hiding the second notification sooner than after the timeout.

To solve these problems, you would need to extract a function that centralizes the timeout logic and dispatches those two actions. It might look like this:

// actions.js
function showNotification(id, text) {
  return { type: 'SHOW_NOTIFICATION', id, text }
}
function hideNotification(id) {
  return { type: 'HIDE_NOTIFICATION', id }
}

let nextNotificationId = 0
export function showNotificationWithTimeout(dispatch, text) {
  // Assigning IDs to notifications lets reducer ignore HIDE_NOTIFICATION
  // for the notification that is not currently visible.
  // Alternatively, we could store the timeout ID and call
  // clearTimeout(), but we’d still want to do it in a single place.
  const id = nextNotificationId++
  dispatch(showNotification(id, text))

  setTimeout(() => {
    dispatch(hideNotification(id))
  }, 5000)
}

Now components can use showNotificationWithTimeout without duplicating this logic or having race conditions with different notifications:

// component.js
showNotificationWithTimeout(this.props.dispatch, 'You just logged in.')

// otherComponent.js
showNotificationWithTimeout(this.props.dispatch, 'You just logged out.')    

Why does showNotificationWithTimeout() accept dispatch as the first argument? Because it needs to dispatch actions to the store. Normally a component has access to dispatch but since we want an external function to take control over dispatching, we need to give it control over dispatching.

If you had a singleton store exported from some module, you could just import it and dispatch directly on it instead:

// store.js
export default createStore(reducer)

// actions.js
import store from './store'

// ...

let nextNotificationId = 0
export function showNotificationWithTimeout(text) {
  const id = nextNotificationId++
  store.dispatch(showNotification(id, text))

  setTimeout(() => {
    store.dispatch(hideNotification(id))
  }, 5000)
}

// component.js
showNotificationWithTimeout('You just logged in.')

// otherComponent.js
showNotificationWithTimeout('You just logged out.')    

This looks simpler but we don’t recommend this approach. The main reason we dislike it is because it forces store to be a singleton. This makes it very hard to implement server rendering. On the server, you will want each request to have its own store, so that different users get different preloaded data.

A singleton store also makes testing harder. You can no longer mock a store when testing action creators because they reference a specific real store exported from a specific module. You can’t even reset its state from outside.

So while you technically can export a singleton store from a module, we discourage it. Don’t do this unless you are sure that your app will never add server rendering.

Getting back to the previous version:

// actions.js

// ...

let nextNotificationId = 0
export function showNotificationWithTimeout(dispatch, text) {
  const id = nextNotificationId++
  dispatch(showNotification(id, text))

  setTimeout(() => {
    dispatch(hideNotification(id))
  }, 5000)
}

// component.js
showNotificationWithTimeout(this.props.dispatch, 'You just logged in.')

// otherComponent.js
showNotificationWithTimeout(this.props.dispatch, 'You just logged out.')    

This solves the problems with duplication of logic and saves us from race conditions.

Thunk Middleware

For simple apps, the approach should suffice. Don’t worry about middleware if you’re happy with it.

In larger apps, however, you might find certain inconveniences around it.

For example, it seems unfortunate that we have to pass dispatch around. This makes it trickier to separate container and presentational components because any component that dispatches Redux actions asynchronously in the manner above has to accept dispatch as a prop so it can pass it further. You can’t just bind action creators with connect() anymore because showNotificationWithTimeout() is not really an action creator. It does not return a Redux action.

In addition, it can be awkward to remember which functions are synchronous action creators like showNotification() and which are asynchronous helpers like showNotificationWithTimeout(). You have to use them differently and be careful not to mistake them with each other.

This was the motivation for finding a way to “legitimize” this pattern of providing dispatch to a helper function, and help Redux “see” such asynchronous action creators as a special case of normal action creators rather than totally different functions.

If you’re still with us and you also recognize as a problem in your app, you are welcome to use the Redux Thunk middleware.

In a gist, Redux Thunk teaches Redux to recognize special kinds of actions that are in fact functions:

import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'

const store = createStore(
  reducer,
  applyMiddleware(thunk)
)

// It still recognizes plain object actions
store.dispatch({ type: 'INCREMENT' })

// But with thunk middleware, it also recognizes functions
store.dispatch(function (dispatch) {
  // ... which themselves may dispatch many times
  dispatch({ type: 'INCREMENT' })
  dispatch({ type: 'INCREMENT' })
  dispatch({ type: 'INCREMENT' })

  setTimeout(() => {
    // ... even asynchronously!
    dispatch({ type: 'DECREMENT' })
  }, 1000)
})

When this middleware is enabled, if you dispatch a function, Redux Thunk middleware will give it dispatch as an argument. It will also “swallow” such actions so don’t worry about your reducers receiving weird function arguments. Your reducers will only receive plain object actions—either emitted directly, or emitted by the functions as we just described.

This does not look very useful, does it? Not in this particular situation. However it lets us declare showNotificationWithTimeout() as a regular Redux action creator:

// actions.js
function showNotification(id, text) {
  return { type: 'SHOW_NOTIFICATION', id, text }
}
function hideNotification(id) {
  return { type: 'HIDE_NOTIFICATION', id }
}

let nextNotificationId = 0
export function showNotificationWithTimeout(text) {
  return function (dispatch) {
    const id = nextNotificationId++
    dispatch(showNotification(id, text))

    setTimeout(() => {
      dispatch(hideNotification(id))
    }, 5000)
  }
}

Note how the function is almost identical to the one we wrote in the previous section. However it doesn’t accept dispatch as the first argument. Instead it returns a function that accepts dispatch as the first argument.

How would we use it in our component? Definitely, we could write this:

// component.js
showNotificationWithTimeout('You just logged in.')(this.props.dispatch)

We are calling the async action creator to get the inner function that wants just dispatch, and then we pass dispatch.

However this is even more awkward than the original version! Why did we even go that way?

Because of what I told you before. If Redux Thunk middleware is enabled, any time you attempt to dispatch a function instead of an action object, the middleware will call that function with dispatch method itself as the first argument.

So we can do this instead:

// component.js
this.props.dispatch(showNotificationWithTimeout('You just logged in.'))

Finally, dispatching an asynchronous action (really, a series of actions) looks no different than dispatching a single action synchronously to the component. Which is good because components shouldn’t care whether something happens synchronously or asynchronously. We just abstracted that away.

Notice that since we “taught” Redux to recognize such “special” action creators (we call them thunk action creators), we can now use them in any place where we would use regular action creators. For example, we can use them with connect():

// actions.js

function showNotification(id, text) {
  return { type: 'SHOW_NOTIFICATION', id, text }
}
function hideNotification(id) {
  return { type: 'HIDE_NOTIFICATION', id }
}

let nextNotificationId = 0
export function showNotificationWithTimeout(text) {
  return function (dispatch) {
    const id = nextNotificationId++
    dispatch(showNotification(id, text))

    setTimeout(() => {
      dispatch(hideNotification(id))
    }, 5000)
  }
}

// component.js

import { connect } from 'react-redux'

// ...

this.props.showNotificationWithTimeout('You just logged in.')

// ...

export default connect(
  mapStateToProps,
  { showNotificationWithTimeout }
)(MyComponent)

Reading State in Thunks

Usually your reducers contain the business logic for determining the next state. However, reducers only kick in after the actions are dispatched. What if you have a side effect (such as calling an API) in a thunk action creator, and you want to prevent it under some condition?

Without using the thunk middleware, you’d just do this check inside the component:

// component.js
if (this.props.areNotificationsEnabled) {
  showNotificationWithTimeout(this.props.dispatch, 'You just logged in.')
}

However, the point of extracting an action creator was to centralize this repetitive logic across many components. Fortunately, Redux Thunk offers you a way to read the current state of the Redux store. In addition to dispatch, it also passes getState as the second argument to the function you return from your thunk action creator. This lets the thunk read the current state of the store.

let nextNotificationId = 0
export function showNotificationWithTimeout(text) {
  return function (dispatch, getState) {
    // Unlike in a regular action creator, we can exit early in a thunk
    // Redux doesn’t care about its return value (or lack of it)
    if (!getState().areNotificationsEnabled) {
      return
    }

    const id = nextNotificationId++
    dispatch(showNotification(id, text))

    setTimeout(() => {
      dispatch(hideNotification(id))
    }, 5000)
  }
}

Don’t abuse this pattern. It is good for bailing out of API calls when there is cached data available, but it is not a very good foundation to build your business logic upon. If you use getState() only to conditionally dispatch different actions, consider putting the business logic into the reducers instead.

Next Steps

Now that you have a basic intuition about how thunks work, check out Redux async example which uses them.

You may find many examples in which thunks return Promises. This is not required but can be very convenient. Redux doesn’t care what you return from a thunk, but it gives you its return value from dispatch(). This is why you can return a Promise from a thunk and wait for it to complete by calling dispatch(someThunkReturningPromise()).then(...).

You may also split complex thunk action creators into several smaller thunk action creators. The dispatch method provided by thunks can accept thunks itself, so you can apply the pattern recursively. Again, this works best with Promises because you can implement asynchronous control flow on top of that.

For some apps, you may find yourself in a situation where your asynchronous control flow requirements are too complex to be expressed with thunks. For example, retrying failed requests, reauthorization flow with tokens, or a step-by-step onboarding can be too verbose and error-prone when written this way. In this case, you might want to look at more advanced asynchronous control flow solutions such as Redux Saga or Redux Loop. Evaluate them, compare the examples relevant to your needs, and pick the one you like the most.

Finally, don’t use anything (including thunks) if you don’t have the genuine need for them. Remember that, depending on the requirements, your solution might look as simple as

store.dispatch({ type: 'SHOW_NOTIFICATION', text: 'You logged in.' })
setTimeout(() => {
  store.dispatch({ type: 'HIDE_NOTIFICATION' })
}, 5000)

Don’t sweat it unless you know why you’re doing this.

Java NIO: What does IOException: Broken pipe mean?

You should assume the socket was closed on the other end. Wrap your code with a try catch block for IOException.

You can use isConnected() to determine if the SocketChannel is connected or not, but that might change before your write() invocation finishes. Try calling it in your catch block to see if in fact this is why you are getting the IOException.

C: Run a System Command and Get Output?

You want the "popen" function. Here's an example of running the command "ls /etc" and outputing to the console.

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


int main( int argc, char *argv[] )
{

  FILE *fp;
  char path[1035];

  /* Open the command for reading. */
  fp = popen("/bin/ls /etc/", "r");
  if (fp == NULL) {
    printf("Failed to run command\n" );
    exit(1);
  }

  /* Read the output a line at a time - output it. */
  while (fgets(path, sizeof(path), fp) != NULL) {
    printf("%s", path);
  }

  /* close */
  pclose(fp);

  return 0;
}

Read all contacts' phone numbers in android

     package com.example.readcontacts;

        import java.util.ArrayList;

        import android.app.Activity; import android.app.ProgressDialog;
        import android.content.ContentResolver; import
        android.database.Cursor; import android.net.Uri; import
        android.os.Bundle; import android.os.Handler; import
        android.provider.ContactsContract; import android.view.View; import
        android.widget.AdapterView; import
        android.widget.AdapterView.OnItemClickListener; import
        android.widget.ArrayAdapter; import android.widget.ListView; import
        android.widget.Toast;

        public class MainActivity extends Activity {    private ListView
        mListView;  private ProgressDialog pDialog;     private Handler
        updateBarHandler;

            ArrayList<String> contactList;  Cursor cursor;  int counter;    
            @Override   public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);

                pDialog = new ProgressDialog(this);         pDialog.setMessage("Reading
        contacts...");      pDialog.setCancelable(false);       pDialog.show();

                mListView = (ListView) findViewById(R.id.list);         updateBarHandler
        =new Handler();
                        // Since reading contacts takes more time, let's run it on a separate thread.       new Thread(new Runnable() {

                    @Override           public void run() {
                        getContacts();          }       }).start();

                // Set onclicklistener to the list item.
                mListView.setOnItemClickListener(new OnItemClickListener() {

                    @Override           public void onItemClick(AdapterView<?> parent, View
        view,
                            int position, long id) {
                        //TODO Do whatever you want with the list data
                        Toast.makeText(getApplicationContext(), "item clicked : \n"+contactList.get(position), Toast.LENGTH_SHORT).show();          }
                });     }

            public void getContacts() {


                contactList = new ArrayList<String>();

                String phoneNumber = null;      String email = null;

                Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;        String
        _ID = ContactsContract.Contacts._ID;        String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;       String HAS_PHONE_NUMBER =
        ContactsContract.Contacts.HAS_PHONE_NUMBER;

                Uri PhoneCONTENT_URI =
        ContactsContract.CommonDataKinds.Phone.CONTENT_URI;         String
        Phone_CONTACT_ID =
        ContactsContract.CommonDataKinds.Phone.CONTACT_ID;      String NUMBER =
        ContactsContract.CommonDataKinds.Phone.NUMBER;

                Uri EmailCONTENT_URI = 
        ContactsContract.CommonDataKinds.Email.CONTENT_URI;         String
        EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
                String DATA = ContactsContract.CommonDataKinds.Email.DATA;

                StringBuffer output;

                ContentResolver contentResolver = getContentResolver();

                cursor = contentResolver.query(CONTENT_URI, null,null, null,
        null);  

                // Iterate every contact in the phone       if (cursor.getCount() > 0)
        {

                    counter = 0;            while (cursor.moveToNext()) {
                        output = new StringBuffer();

                        // Update the progress message
                        updateBarHandler.post(new Runnable() {
                            public void run() {
                                pDialog.setMessage("Reading contacts : "+ counter++ +"/"+cursor.getCount());
                            }
                        });

                        String contact_id = cursor.getString(cursor.getColumnIndex( _ID ));
                        String name = cursor.getString(cursor.getColumnIndex( DISPLAY_NAME ));

                        int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(
        HAS_PHONE_NUMBER )));

                        if (hasPhoneNumber > 0) {

                            output.append("\n First Name:" + name);

                            //This is to read multiple phone numbers associated with the same contact
                            Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[] { contact_id }, null);

                            while (phoneCursor.moveToNext()) {
                                phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
                                output.append("\n Phone number:" + phoneNumber);

                            }

                            phoneCursor.close();

                            // Read every email id associated with the contact
                            Cursor emailCursor = contentResolver.query(EmailCONTENT_URI,    null, EmailCONTACT_ID+ " =
        ?", new String[] { contact_id }, null);

                            while (emailCursor.moveToNext()) {

                                email = emailCursor.getString(emailCursor.getColumnIndex(DATA));

                                output.append("\n Email:" + email);

                            }

                            emailCursor.close();
                        }

                        // Add the contact to the ArrayList
                        contactList.add(output.toString());             }

                    // ListView has to be updated using a ui thread
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.list_item,
        R.id.text1, contactList);
                            mListView.setAdapter(adapter);          
                        }           });

                    // Dismiss the progressbar after 500 millisecondds
                    updateBarHandler.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            pDialog.cancel();               
                        }           }, 500);        }

            }

        }

List item

CSS word-wrapping in div

Setting just the width and float css properties would get a wrapping panel. The folowing example work just fine:

<div style="float:left; width: 250px">
Pellentesque feugiat tempor elit. Ut mollis lacinia quam. 
Sed pharetra, augue aliquam   ornare vestibulum, metus massa
laoreet tellus, eget iaculis lacus ipsum et diam. 
</div>

Maybe there are other styles in place that modify the appearance?

Keep values selected after form submission

If you are using WordPress (as is the case with the OP), you can use the selected function.

<form method="get" action="">
  <select name="name">
    <option value="a" <?php selected( isset($_POST['name']) ? $_POST['name'] : '', 'a' ); ?>>a</option>
    <option value="b" <?php selected( isset($_POST['name']) ? $_POST['name'] : '', 'b' ); ?>>b</option>
  </select>
  <select name="location">
    <option value="x" <?php selected( isset($_POST['location']) ? $_POST['location'] : '', 'x' ); ?>>x</option>
    <option value="y" <?php selected( isset($_POST['location']) ? $_POST['location'] : '', 'y' ); ?>>y</option>
  </select>
  <input type="submit" value="Submit" class="submit" />
</form>

Div height 100% and expands to fit content

Try this:

body { 
    min-height:100%; 
    background:red; 
} 

#some_div {
    min-height:100%; 
    background:black; 
} 

IE6 and earlier versions do not support the min-height property.

I think the problem is that when you tell the body to have a height of 100%, it's background can only be as tall as the hieght of one browser "viewport" (the viewing area that excludes the browsers toolbars & statusbars & menubars and the window edges). If the content is taller than one viewport, it will overflow the height devoted to the background.

This min-height property on the body should FORCE the background to be at least as tall as one viewport if your content does not fill one whole page down to the bottom, yet it should also let it grow downwards to encompass more interior content.

Example of multipart/form-data

EDIT: I am maintaining a similar, but more in-depth answer at: https://stackoverflow.com/a/28380690/895245

To see exactly what is happening, use nc -l or an ECHO server and an user agent like a browser or cURL.

Save the form to an .html file:

<form action="http://localhost:8000" method="post" enctype="multipart/form-data">
  <p><input type="text" name="text" value="text default">
  <p><input type="file" name="file1">
  <p><input type="file" name="file2">
  <p><button type="submit">Submit</button>
</form>

Create files to upload:

echo 'Content of a.txt.' > a.txt
echo '<!DOCTYPE html><title>Content of a.html.</title>' > a.html

Run:

nc -l localhost 8000

Open the HTML on your browser, select the files and click on submit and check the terminal.

nc prints the request received. Firefox sent:

POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: __atuvc=34%7C7; permanent=0; _gitlab_session=226ad8a0be43681acf38c2fab9497240; __profilin=p%3Dt; request_method=GET
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------9051914041544843365972754266
Content-Length: 554

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="text"

text default
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain

Content of a.txt.

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html

<!DOCTYPE html><title>Content of a.html.</title>

-----------------------------9051914041544843365972754266--

Aternativelly, cURL should send the same POST request as your a browser form:

nc -l localhost 8000
curl -F "text=default" -F "[email protected]" -F "[email protected]" localhost:8000

You can do multiple tests with:

while true; do printf '' | nc -l localhost 8000; done

What is the difference between @Inject and @Autowired in Spring Framework? Which one to use under what condition?

Better use @Inject all the time. Because it is java configuration approach(provided by sun) which makes our application agnostic to the framework. So if you spring also your classes will work.

If you use @Autowired it will works only with spring because @Autowired is spring provided annotation.

Merging 2 branches together in GIT

If you want to merge changes in SubBranch to MainBranch

  1. you should be on MainBranch git checkout MainBranch
  2. then run merge command git merge SubBranch

Getting data from Yahoo Finance

As from the answer from BrianC use the YQL console. But after selecting the "Show Community Tables" go to the bottom of the tables list and expand yahoo where you find plenty of yahoo.finance tables:

Stock Quotes:

  • yahoo.finance.quotes
  • yahoo.finance.historicaldata

Fundamental analysis:

  • yahoo.finance.keystats
  • yahoo.finance.balancesheet
  • yahoo.finance.incomestatement
  • yahoo.finance.analystestimates
  • yahoo.finance.dividendhistory

Technical analysis:

  • yahoo.finance.historicaldata
  • yahoo.finance.quotes
  • yahoo.finance.quant
  • yahoo.finance.option*

General financial information:

  • yahoo.finance.industry
  • yahoo.finance.sectors
  • yahoo.finance.isin
  • yahoo.finance.quoteslist
  • yahoo.finance.xchange

2/Nov/2017: Yahoo finance has apparently killed this API, for more info and alternative resources see https://news.ycombinator.com/item?id=15616880

Executing JavaScript after X seconds

setTimeout will help you to execute any JavaScript code based on the time you set.

Syntax

setTimeout(code, millisec, lang)

Usage,

setTimeout("function1()", 1000);

For more details, see http://www.w3schools.com/jsref/met_win_settimeout.asp

REST URI convention - Singular or plural name of resource while creating it

For me is better to have a schema that you can map directly to code (easy to automate), mainly because code is what is going to be at both ends.

GET  /orders          <---> orders 
POST /orders          <---> orders.push(data)
GET  /orders/1        <---> orders[1]
PUT  /orders/1        <---> orders[1] = data
GET  /orders/1/lines  <---> orders[1].lines
POST /orders/1/lines  <---> orders[1].lines.push(data) 

How do I block or restrict special characters from input fields with jquery?

just the numbers:

$('input.time').keydown(function(e) { if(e.keyCode>=48 && e.keyCode<=57) { return true; } else { return false; } });

or for time including ":"

$('input.time').keydown(function(e) { if(e.keyCode>=48 && e.keyCode<=58) { return true; } else { return false; } });

also including delete and backspace:

$('input.time').keydown(function(e) { if((e.keyCode>=46 && e.keyCode<=58) || e.keyCode==8) { return true; } else { return false; } });

unfortuneatly not getting it to work on a iMAC

Exception 'open failed: EACCES (Permission denied)' on Android

For API 23+ you need to request the read/write permissions even if they are already in your manifest.

// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
};

/**
 * Checks if the app has permission to write to device storage
 *
 * If the app does not has permission then the user will be prompted to grant permissions
 *
 * @param activity
 */
public static void verifyStoragePermissions(Activity activity) {
    // Check if we have write permission
    int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (permission != PackageManager.PERMISSION_GRANTED) {
        // We don't have permission so prompt the user
        ActivityCompat.requestPermissions(
                activity,
                PERMISSIONS_STORAGE,
                REQUEST_EXTERNAL_STORAGE
        );
    }
}

AndroidManifest.xml

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

For official documentation about requesting permissions for API 23+, check https://developer.android.com/training/permissions/requesting.html

Argument Exception "Item with Same Key has already been added"

Clear the dictionary before adding any items to it. I don't know how a dictionary of one object affects another's during assignment but I got the error after creating another object with the same key,value pairs.

NB: If you are going to add items in a loop just make sure you clear the dictionary before entering the loop.

Warning: Attempt to present * on * whose view is not in the window hierarchy - swift

For swift 3.0 and above

public static func getTopViewController() -> UIViewController?{
if var topController = UIApplication.shared.keyWindow?.rootViewController
{
  while (topController.presentedViewController != nil)
  {
    topController = topController.presentedViewController!
  }
  return topController
}
return nil}

How to push changes to github after jenkins build completes?

Found an answer myself, this blog helped: http://thingsyoudidntknowaboutjenkins.tumblr.com/post/23596855946/git-plugin-part-3

Basically need to execute:

git checkout master

before modifying any files

then

git commit -am "Updated version number"

after modified files

and then use post build action of Git Publisher with an option of Merge Results which will push changes to github on successful build.

SSL error : routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

I've experienced the same issue because of certifi library. Installing a different version helped me as well.

How to get Real IP from Visitor?

Proxies may send a HTTP_X_FORWARDED_FOR header but even that is optional.

Also keep in mind that visitors may share IP addresses; University networks, large companies and third-world/low-budget ISPs tend to share IPs over many users.

Favorite Visual Studio keyboard shortcuts

Ctrl + K + C - set current selected code to be comments Ctrl + K + U - set current selected comments to be code

jQuery UI Alert Dialog as a replacement for alert()

I took @EkoJR's answer, and added an additional parameter to pass in with a callback function to occur when the user closes the dialog.

function jqAlert(outputMsg, titleMsg, onCloseCallback) {
    if (!titleMsg)
        titleMsg = 'Alert';

    if (!outputMsg)
        outputMsg = 'No Message to Display.';

    $("<div></div>").html(outputMsg).dialog({
        title: titleMsg,
        resizable: false,
        modal: true,
        buttons: {
            "OK": function () {
                $(this).dialog("close");
            }
        },
        close: onCloseCallback
    });
}

You can then call it and pass it a function, that will occur when the user closes the dialog, as so:

jqAlert('Your payment maintenance has been saved.', 
        'Processing Complete', 
        function(){ window.location = 'search.aspx' })

Copy Data from a table in one Database to another separate database

Hard to say without any idea what you mean by "it didn't work." There are a whole lot of things that can go wrong and any advice we give in troubleshooting one of those paths may lead you further and further from finding a solution, which may be really simple.

Here's a something I would look for though,

Identity Insert must be on on the table you are importing into if that table contains an identity field and you are manually supplying it. Identity Insert can also only be enabled for 1 table at a time in a database, so you must remember to enable it for the table, then disable it immediately after you are done importing.

Also, try listing out all your fields

INSERT INTO db1.user.MyTable (Col1, Col2, Col3)
SELECT Col1, COl2, Col3 FROM db2.user.MyTable

Jquery - Uncaught TypeError: Cannot use 'in' operator to search for '324' in

You can also use $.parseJSON(data) that will explicit convert a string thats come from a PHP script to a real JSON array.

How do we control web page caching, across all browsers?

Also, just for good measure, make sure you reset the ExpiresDefault in your .htaccess file if you're using that to enable caching.

ExpiresDefault "access plus 0 seconds"

Afterwards, you can use ExpiresByType to set specific values for the files you want to cache:

ExpiresByType image/x-icon "access plus 3 month"

This may also come in handy if your dynamic files e.g. php, etc. are being cached by the browser, and you can't figure out why. Check ExpiresDefault.

Difference between /res and /assets directories

I know this is old, but just to make it clear, there is an explanation of each in the official android documentation:

from http://developer.android.com/tools/projects/index.html

assets/

This is empty. You can use it to store raw asset files. Files that you save here are compiled into an .apk file as-is, and the original filename is preserved. You can navigate this directory in the same way as a typical file system using URIs and read files as a stream of bytes using the AssetManager. For example, this is a good location for textures and game data.

res/raw/

For arbitrary raw asset files. Saving asset files here instead of in the assets/ directory only differs in the way that you access them. These files are processed by aapt and must be referenced from the application using a resource identifier in the R class. For example, this is a good place for media, such as MP3 or Ogg files.

jquery/javascript convert date string to date

I used the javascript date funtion toLocaleDateString to get

var Today = new Date();
var r = Today.toLocaleDateString();

The result of r will be

11/29/2016

More info at: http://www.w3schools.com/jsref/jsref_tolocaledatestring.asp

Checking if element exists with Python Selenium

a)

from selenium.common.exceptions import NoSuchElementException        
def check_exists_by_xpath(xpath):
    try:
        webdriver.find_element_by_xpath(xpath)
    except NoSuchElementException:
        return False
    return True

b) use xpath - the most reliable. Moreover you can take the xpath as a standard throughout all your scripts and create functions as above mentions for universal use.

UPDATE: I wrote the initial answer over 4 years ago and at the time I thought xpath would be the best option. Now I recommend to use css selectors. I still recommend not to mix/use "by id", "by name" and etc and use one single approach instead.

Why is this error, 'Sequence contains no elements', happening?

Check again. Use debugger if must. My guess is that for some item in userResponseDetails this query finds no elements:

.Where(y => y.ResponseId.Equals(item.ResponseId))

so you can't call

.First()

on it. Maybe try

.FirstOrDefault()

if it solves the issue.

Do NOT return NULL value! This is purely so that you can see and diagnose where problem is. Handle these cases properly.

How to drop a table if it exists?

I use:

if exists (select * 
           from sys.tables 
           where name = 'tableName' 
           and schema_id = schema_id('dbo'))
begin
    drop table dbo.tableName
end

Android Studio don't generate R.java for my import project

If you are facing this problem in a specific module in your project, you could try opening just that module as a project and then build it. This worked for me. It was failing to generate the R file for the module when I was trying to re-build the entire project.

How to convert <font size="10"> to px?

Using the data points from the accepted answer you can use polynomial interpolation to obtain a formula.

WolframAlpha Input: interpolating polynomial {{1,.63},{2,.82}, {3,1}, {4,1.13}, {5,1.5}, {6, 2}, {7,3}}

Formula: 0.00223611x^6 - 0.0530417x^5 + 0.496319x^4 - 2.30479x^3 + 5.51644x^2 - 6.16717x + 3.14

And use in Groovy code:

import java.math.*
def convert = {x -> (0.00223611*x**6 - 0.053042*x**5 + 0.49632*x**4 - 2.30479*x**3 + 5.5164*x**2 - 6.167*x + 3.14).setScale(2, RoundingMode.HALF_UP) }
(1..7).each { i -> println(convert(i)) }

Is it possible to assign a base class object to a derived class reference with an explicit typecast?

There actually IS a way to do this. Think about how you might use Newtonsoft JSON to deserialize an object from json. It will (or at least can) ignore missing elements and populate all the elements that it does know about.

So here's how I did it. A small code sample will follow my explanation.

  1. Create an instance of your object from the base class and populate it accordingly.

  2. Using the "jsonconvert" class of Newtonsoft json, serialize that object into a json string.

  3. Now create your sub class object by deserializing with the json string created in step 2. This will create an instance of your sub class with all the properties of the base class.

This works like a charm! So.. when is this useful? Some people asked when this would make sense and suggested changing the OP's schema to accommodate the fact that you can't natively do this with class inheritance (in .Net).

In my case, I have a settings class that contains all the "base" settings for a service. Specific services have more options and those come from a different DB table, so those classes inherit the base class. They all have a different set of options. So when retrieving the data for a service, it's much easier to FIRST populate the values using an instance of the base object. One method to do this with a single DB query. Right after that, I create the sub class object using the method outlined above. I then make a second query and populate all the dynamic values on the sub class object.

The final output is a derived class with all the options set. Repeating this for additional new sub classes takes just a few lines of code. It's simple, and it uses a very tried and tested package (Newtonsoft) to make the magic work.

This example code is vb.Net, but you can easily convert to c#.

' First, create the base settings object.
    Dim basePMSettngs As gtmaPayMethodSettings = gtmaPayments.getBasePayMethodSetting(payTypeId, account_id)
    Dim basePMSettingsJson As String = JsonConvert.SerializeObject(basePMSettngs, Formatting.Indented)

    ' Create a pmSettings object of this specific type of payment and inherit from the base class object
    Dim pmSettings As gtmaPayMethodAimACHSettings = JsonConvert.DeserializeObject(Of gtmaPayMethodAimACHSettings)(basePMSettingsJson)

How do I tidy up an HTML file's indentation in VI?

This is my solution that works nicely for opening "ugly" HTML in a nicely spaced way:

vim fileIn.html -c "set sw=2 | %s/>/>\r/ | execute 'normal gg=G' | set nohlsearch | g/^\\s*\$/d"
  • The sw command is because my default is 4, which is too high for HTML.
  • The next part adds a newline (Vim thinks it's a carriage return, sigh) after each element (>).
  • Then re-indent the entire file with =.
  • Then unhighlight > (since I have set hlsearch in my vimrc).
  • Then remove all empty/whitespace-only lines (see "Vim delete blank lines" for more, also this is double-escaped because it's in the shell).

You can even add | wq! fileOut.html to the end if you don't want to enter Vim at all, but just clean up the file.

WordPress path url in js script file

You could avoid hardcoding the full path by setting a JS variable in the header of your template, before wp_head() is called, holding the template URL. Like:

<script type="text/javascript">
var templateUrl = '<?= get_bloginfo("template_url"); ?>';
</script>

And use that variable to set the background (I realize you know how to do this, I only include these details in case they helps others):

Reset.style.background = " url('"+templateUrl+"/images/searchfield_clear.png') ";

Environment Specific application.properties file in Spring Boot application

Yes you can. Since you are using spring, check out @PropertySource anotation.

Anotate your configuration with

@PropertySource("application-${spring.profiles.active}.properties")

You can call it what ever you like, and add inn multiple property files if you like too. Can be nice if you have more sets and/or defaults that belongs to all environments (can be written with @PropertySource{...,...,...} as well).

@PropertySources({
  @PropertySource("application-${spring.profiles.active}.properties"),
  @PropertySource("my-special-${spring.profiles.active}.properties"),
  @PropertySource("overridden.properties")})

Then you can start the application with environment

-Dspring.active.profiles=test

In this example, name will be replaced with application-test-properties and so on.

Is it possible to display my iPhone on my computer monitor?

The latest SDKs (beginning with 2.2, I believe), include TV-Out functionality. With a special cable connected to the iPhone dock connector, a program can send RCA signals representing its current screen contents through the iPhone->RCA cable. If you have a TV Tuner for your computer (i.e. I have an EyeTV Hybrid) with RCA inputs, you can display the screen contents of your iPhone directly in the TV viewer.

R: invalid multibyte string

I had a similarly strange problem with a file from the program e-prime (edat -> SPSS conversion), but then I discovered that there are many additional encodings you can use. this did the trick for me:

tbl <- read.delim("dir/file.txt", fileEncoding="UCS-2LE")

How to copy a file from remote server to local machine?

The scp operation is separate from your ssh login. You will need to issue an ssh command similar to the following one assuming jdoe is account with which you log into the remote system and that the remote system is example.com:

scp [email protected]:/somedir/table /home/me/Desktop/.

The scp command issued from the system where /home/me/Desktop resides is followed by the userid for the account on the remote server. You then add a ":" followed by the directory path and file name on the remote server, e.g., /somedir/table. Then add a space and the location to which you want to copy the file. If you want the file to have the same name on the client system, you can indicate that with a period, i.e. "." at the end of the directory path; if you want a different name you could use /home/me/Desktop/newname, instead. If you were using a nonstandard port for SSH connections, you would need to specify that port with a "-P n" (capital P), where "n" is the port number. The standard port is 22 and if you aren't specifying it for the SSH connection then you won't need that.

How to declare std::unique_ptr and what is the use of it?

Unique pointers are guaranteed to destroy the object they manage when they go out of scope. http://en.cppreference.com/w/cpp/memory/unique_ptr

In this case:

unique_ptr<double> uptr2 (pd);

pd will be destroyed when uptr2 goes out of scope. This facilitates memory management by automatic deletion.

The case of unique_ptr<int> uptr (new int(3)); is not different, except that the raw pointer is not assigned to any variable here.

How do I run a command on an already existing Docker container?

To expand on katrmr's answer, if the container is stopped and can't be started due to an error, you'll need to commit it to an image. Then you can launch bash in the new image:

docker commit [CONTAINER_ID] temporary_image
docker run --entrypoint=bash -it temporary_image

Add querystring parameters to link_to

In case you want to pass in a block, say, for a glyphicon button, as in the following:

<%= link_to my_url, class: "stuff" do %>
  <i class="glyphicon glyphicon-inbox></i> Nice glyph-button
<% end %>

Then passing querystrings params could be accomplished through:

<%= link_to url_for(params.merge(my_params: "value")), class: "stuff" do %>
  <i class="glyphicon glyphicon-inbox></i> Nice glyph-button
<% end %>

Bootstrap 4 multiselect dropdown

Because the bootstrap-select is a bootstrap component and therefore you need to include it in your code as you did for your V3

NOTE: this component only works in since version 1.13.0

_x000D_
_x000D_
$('select').selectpicker();
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<select class="selectpicker" multiple data-live-search="true">_x000D_
  <option>Mustard</option>_x000D_
  <option>Ketchup</option>_x000D_
  <option>Relish</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Refused to load the script because it violates the following Content Security Policy directive

For anyone looking for a complete explanation, I recommend you to take a look at Content Security Policy: https://www.html5rocks.com/en/tutorials/security/content-security-policy/.

"Code from https://mybank.com should only have access to https://mybank.com’s data, and https://evil.example.com should certainly never be allowed access. Each origin is kept isolated from the rest of the web"

XSS attacks are based on the browser's inability to distinguish your app's code from code downloaded from another website. So you must whitelist the content origins that you consider safe to download content from, using the Content-Security-Policy HTTP header.

This policy is described using a series of policy directives, each of which describes the policy for a certain resource type or policy area. Your policy should include a default-src policy directive, which is a fallback for other resource types when they don't have policies of their own.

So, if you modify your tag to:

<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *;**script-src 'self' http://onlineerp.solution.quebec 'unsafe-inline' 'unsafe-eval';** ">

You are saying that you are authorizing the execution of JavaScript code (script-src) from the origins 'self', http://onlineerp.solution.quebec, 'unsafe-inline', 'unsafe-eval'.

I guess that the first two are perfectly valid for your use case, I am a bit unsure about the other ones. 'unsafe-line' and 'unsafe-eval' pose a security problem, so you should not be using them unless you have a very specific need for them:

"If eval and its text-to-JavaScript brethren are completely essential to your application, you can enable them by adding 'unsafe-eval' as an allowed source in a script-src directive. But, again, please don’t. Banning the ability to execute strings makes it much more difficult for an attacker to execute unauthorized code on your site." (Mike West, Google)

Callback function for JSONP with jQuery AJAX

This is what I do on mine

$(document).ready(function() {
  if ($('#userForm').valid()) {
    var formData = $("#userForm").serializeArray();
    $.ajax({
      url: 'http://www.example.com/user/' + $('#Id').val() + '?callback=?',
      type: "GET",
      data: formData,
      dataType: "jsonp",
      jsonpCallback: "localJsonpCallback"
    });
  });

function localJsonpCallback(json) {
  if (!json.Error) {
    $('#resultForm').submit();
  } else {
    $('#loading').hide();
    $('#userForm').show();
    alert(json.Message);
  }
}

Write Base64-encoded image to file

With Java 8's Base64 API

byte[] decodedImg = Base64.getDecoder()
                    .decode(encodedImg.getBytes(StandardCharsets.UTF_8));
Path destinationFile = Paths.get("/path/to/imageDir", "myImage.jpg");
Files.write(destinationFile, decodedImg);

If your encoded image starts with something like data:image/png;base64,iVBORw0..., you'll have to remove the part. See this answer for an easy way to do that.

Android TextView padding between lines

Adding android:lineSpacingMultiplier="0.8" can make the line spacing to 80%.

How to test that no exception is thrown?

The following fails the test for all exceptions, checked or unchecked:

@Test
public void testMyCode() {

    try {
        runMyTestCode();
    } catch (Throwable t) {
        throw new Error("fail!");
    }
}

How to calculate moving average without keeping the count and data-total?

You can simply do:

double approxRollingAverage (double avg, double new_sample) {

    avg -= avg / N;
    avg += new_sample / N;

    return avg;
}

Where N is the number of samples where you want to average over. Note that this approximation is equivalent to an exponential moving average. See: Calculate rolling / moving average in C++

Returning a boolean from a Bash function

Why you should care what I say in spite of there being a 250+ upvote answer

It's not that 0 = true and 1 = false. It is: zero means no failure (success) and non-zero means failure (of type N).

While the selected answer is technically "true" please do not put return 1** in your code for false. It will have several unfortunate side effects.

  1. Experienced developers will spot you as an amateur (for the reason below).
  2. Experienced developers don't do this (for all the reasons below).
  3. It is error prone.
    • Even experienced developers can mistake 0 and 1 as false and true respectively (for the reason above).
  4. It requires (or will encourage) extraneous and ridiculous comments.
  5. It's actually less helpful than implicit return statuses.

Learn some bash

The bash manual says (emphasis mine)

return [n]

Cause a shell function to stop executing and return the value n to its caller. If n is not supplied, the return value is the exit status of the last command executed in the function.

Therefore, we don't have to EVER use 0 and 1 to indicate True and False. The fact that they do so is essentially trivial knowledge useful only for debugging code, interview questions, and blowing the minds of newbies.

The bash manual also says

otherwise the function’s return status is the exit status of the last command executed

The bash manual also says

($?) Expands to the exit status of the most recently executed foreground pipeline.

Whoa, wait. Pipeline? Let's turn to the bash manual one more time.

A pipeline is a sequence of one or more commands separated by one of the control operators ‘|’ or ‘|&’.

Yes. They said 1 command is a pipeline. Therefore, all 3 of those quotes are saying the same thing.

  • $? tells you what happened last.
  • It bubbles up.

My answer

So, while @Kambus demonstrated that with such a simple function, no return is needed at all. I think was unrealistically simple compared to the needs of most people who will read this.

Why return?

If a function is going to return its last command's exit status, why use return at all? Because it causes a function to stop executing.

Stop execution under multiple conditions

01  function i_should(){
02      uname="$(uname -a)"
03
04      [[ "$uname" =~ Darwin ]] && return
05
06      if [[ "$uname" =~ Ubuntu ]]; then
07          release="$(lsb_release -a)"
08          [[ "$release" =~ LTS ]]
09          return
10      fi
11
12      false
13  }
14
15  function do_it(){
16      echo "Hello, old friend."
17  }
18
19  if i_should; then
20    do_it
21  fi

What we have here is...

Line 04 is an explicit[-ish] return true because the RHS of && only gets executed if the LHS was true

Line 09 returns either true or false matching the status of line 08

Line 13 returns false because of line 12

(Yes, this can be golfed down, but the entire example is contrived.)

Another common pattern

# Instead of doing this...
some_command
if [[ $? -eq 1 ]]; then
    echo "some_command failed"
fi

# Do this...
some_command
status=$?
if ! $(exit $status); then
    echo "some_command failed"
fi

Notice how setting a status variable demystifies the meaning of $?. (Of course you know what $? means, but someone less knowledgeable than you will have to Google it some day. Unless your code is doing high frequency trading, show some love, set the variable.) But the real take-away is that "if not exist status" or conversely "if exit status" can be read out loud and explain their meaning. However, that last one may be a bit too ambitious because seeing the word exit might make you think it is exiting the script, when in reality it is exiting the $(...) subshell.


** If you absolutely insist on using return 1 for false, I suggest you at least use return 255 instead. This will cause your future self, or any other developer who must maintain your code to question "why is that 255?" Then they will at least be paying attention and have a better chance of avoiding a mistake.

Parse JSON in C#

Google Map API request and parse DirectionsResponse with C#, change the json in your url to xml and use the following code to turn the result into a usable C# Generic List Object.

Took me a while to make. But here it is

var url = String.Format("http://maps.googleapis.com/maps/api/directions/xml?...");
var result = new System.Net.WebClient().DownloadString(url);
var doc = XDocument.Load(new StringReader(result));

var DirectionsResponse = doc.Elements("DirectionsResponse").Select(l => new
{
    Status = l.Elements("status").Select(q => q.Value).FirstOrDefault(),
    Route = l.Descendants("route").Select(n => new
    {
        Summary = n.Elements("summary").Select(q => q.Value).FirstOrDefault(),
        Leg = n.Elements("leg").ToList().Select(o => new
        {
            Step = o.Elements("step").Select(p => new
            {
                Travel_Mode = p.Elements("travel_mode").Select(q => q.Value).FirstOrDefault(),
                Start_Location = p.Elements("start_location").Select(q => new
                {
                    Lat = q.Elements("lat").Select(r => r.Value).FirstOrDefault(),
                    Lng = q.Elements("lng").Select(r => r.Value).FirstOrDefault()
                }).FirstOrDefault(),
                End_Location = p.Elements("end_location").Select(q => new
                {
                    Lat = q.Elements("lat").Select(r => r.Value).FirstOrDefault(),
                    Lng = q.Elements("lng").Select(r => r.Value).FirstOrDefault()
                }).FirstOrDefault(),
                Polyline = p.Elements("polyline").Select(q => new
                {
                    Points = q.Elements("points").Select(r => r.Value).FirstOrDefault()
                }).FirstOrDefault(),
                Duration = p.Elements("duration").Select(q => new
                {
                    Value = q.Elements("value").Select(r => r.Value).FirstOrDefault(),
                    Text = q.Elements("text").Select(r => r.Value).FirstOrDefault(),
                }).FirstOrDefault(),
                Html_Instructions = p.Elements("html_instructions").Select(q => q.Value).FirstOrDefault(),
                Distance = p.Elements("distance").Select(q => new
                {
                    Value = q.Elements("value").Select(r => r.Value).FirstOrDefault(),
                    Text = q.Elements("text").Select(r => r.Value).FirstOrDefault(),
                }).FirstOrDefault()
            }).ToList(),
            Duration = o.Elements("duration").Select(p => new
            {
                Value = p.Elements("value").Select(q => q.Value).FirstOrDefault(),
                Text = p.Elements("text").Select(q => q.Value).FirstOrDefault()
            }).FirstOrDefault(),
            Distance = o.Elements("distance").Select(p => new
            {
                Value = p.Elements("value").Select(q => q.Value).FirstOrDefault(),
                Text = p.Elements("text").Select(q => q.Value).FirstOrDefault()
            }).FirstOrDefault(),
            Start_Location = o.Elements("start_location").Select(p => new
            {
                Lat = p.Elements("lat").Select(q => q.Value).FirstOrDefault(),
                Lng = p.Elements("lng").Select(q => q.Value).FirstOrDefault()
            }).FirstOrDefault(),
            End_Location = o.Elements("end_location").Select(p => new
            {
                Lat = p.Elements("lat").Select(q => q.Value).FirstOrDefault(),
                Lng = p.Elements("lng").Select(q => q.Value).FirstOrDefault()
            }).FirstOrDefault(),
            Start_Address = o.Elements("start_address").Select(q => q.Value).FirstOrDefault(),
            End_Address = o.Elements("end_address").Select(q => q.Value).FirstOrDefault()
        }).ToList(),
        Copyrights = n.Elements("copyrights").Select(q => q.Value).FirstOrDefault(),
        Overview_polyline = n.Elements("overview_polyline").Select(q => new
        {
            Points = q.Elements("points").Select(r => r.Value).FirstOrDefault()
        }).FirstOrDefault(),
        Waypoint_Index = n.Elements("waypoint_index").Select(o => o.Value).ToList(),
        Bounds = n.Elements("bounds").Select(q => new
        {
            SouthWest = q.Elements("southwest").Select(r => new
            {
                Lat = r.Elements("lat").Select(s => s.Value).FirstOrDefault(),
                Lng = r.Elements("lng").Select(s => s.Value).FirstOrDefault()
            }).FirstOrDefault(),
            NorthEast = q.Elements("northeast").Select(r => new
            {
                Lat = r.Elements("lat").Select(s => s.Value).FirstOrDefault(),
                Lng = r.Elements("lng").Select(s => s.Value).FirstOrDefault()
            }).FirstOrDefault(),
        }).FirstOrDefault()
    }).FirstOrDefault()
}).FirstOrDefault();

I hope this will help someone.

CodeIgniter - Correct way to link to another page in a view

you can also use PHP short tag to make it shorter. here's an example

<a href="<?= site_url('controller/function'); ?>Contacts</a>

or use the built in anchor function of CI.

Finding duplicate rows in SQL Server

You have several way for Select duplicate rows.

for my solutions , first consider this table for example

CREATE TABLE #Employee
(
ID          INT,
FIRST_NAME  NVARCHAR(100),
LAST_NAME   NVARCHAR(300)
)

INSERT INTO #Employee VALUES ( 1, 'Ardalan', 'Shahgholi' );
INSERT INTO #Employee VALUES ( 2, 'name1', 'lname1' );
INSERT INTO #Employee VALUES ( 3, 'name2', 'lname2' );
INSERT INTO #Employee VALUES ( 2, 'name1', 'lname1' );
INSERT INTO #Employee VALUES ( 3, 'name2', 'lname2' );
INSERT INTO #Employee VALUES ( 4, 'name3', 'lname3' );

First solution :

SELECT DISTINCT *
FROM   #Employee;

WITH #DeleteEmployee AS (
                     SELECT ROW_NUMBER()
                            OVER(PARTITION BY ID, First_Name, Last_Name ORDER BY ID) AS
                            RNUM
                     FROM   #Employee
                 )

SELECT *
FROM   #DeleteEmployee
WHERE  RNUM > 1

SELECT DISTINCT *
FROM   #Employee

Secound solution : Use identity field

SELECT DISTINCT *
FROM   #Employee;

ALTER TABLE #Employee ADD UNIQ_ID INT IDENTITY(1, 1)

SELECT *
FROM   #Employee
WHERE  UNIQ_ID < (
    SELECT MAX(UNIQ_ID)
    FROM   #Employee a2
    WHERE  #Employee.ID = a2.ID
           AND #Employee.FIRST_NAME = a2.FIRST_NAME
           AND #Employee.LAST_NAME = a2.LAST_NAME
)

ALTER TABLE #Employee DROP COLUMN UNIQ_ID

SELECT DISTINCT *
FROM   #Employee

and end of all solution use this command

DROP TABLE #Employee

How can I see what I am about to push with git?

Use git gui, there you can see a list of what changed in your actual commit. You can also use gitk wich provides an easy interface for reflogs. Just compare between remotes/... and master to see, what will be pushed. It provides an interface similar to your screenshot.

Both programs are included in git.

Best practices for SQL varchar column length

The best value is the one that is right for the data as defined in the underlying domain.

For some domains, VARCHAR(10) is right for the Name attribute, for other domains VARCHAR(255) might be the best choice.

Wait until page is loaded with Selenium WebDriver for Python

Very good answers here. Quick example of wait for XPATH.

# wait for sizes to load - 2s timeout
try:
    WebDriverWait(driver, 2).until(expected_conditions.presence_of_element_located(
        (By.XPATH, "//div[@id='stockSizes']//a")))
except TimeoutException:
    pass

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

To add on to Andreas' answer, you can install only the dependencies by using:

npm install --production

Encoding URL query parameters in Java

The built in Java URLEncoder is doing what it's supposed to, and you should use it.

A "+" or "%20" are both valid replacements for a space character in a URL. Either one will work.

A ":" should be encoded, as it's a separator character. i.e. http://foo or ftp://bar. The fact that a particular browser can handle it when it's not encoded doesn't make it correct. You should encode them.

As a matter of good practice, be sure to use the method that takes a character encoding parameter. UTF-8 is generally used there, but you should supply it explicitly.

URLEncoder.encode(yourUrl, "UTF-8");

Pyspark: Exception: Java gateway process exited before sending the driver its port number

I use Mac OS. I fixed the problem!

Below is how I fixed it.

JDK8 seems works fine. (https://github.com/jupyter/jupyter/issues/248)

So I checked my JDK /Library/Java/JavaVirtualMachines, I only have jdk-11.jdk in this path.

I downloaded JDK8 (I followed the link). Which is:

brew tap caskroom/versions
brew cask install java8

After this, I added

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_202.jdk/Contents/Home
export JAVA_HOME="$(/usr/libexec/java_home -v 1.8)"

to ~/.bash_profile file. (you sholud check your jdk1.8 file name)

It works now! Hope this help :)

Counting duplicates in Excel

You can achieve your result in two steps. First, create a list of unique entries using Advanced Filter... from the pull down Filter menu. To do so, you have to add a name of the column to be sorted out. It is necessary, otherwise Excel will treat first row as a name rather than an entry. Highlight column that you want to filter (A in the example below), click the filter icon and chose 'Advanced Filter...'. That will bring up a window where you can select an option to "Copy to another location". Choose that one, as you will need your original list to do counts (in my example I will choose C:C). Also, select "Unique record only". That will give you a list of unique entries. Then you can count their frequencies using =COUNTIF() command. See screedshots for details.

Hope this helps!

  +--------+-------+--------+-------------------+
  |   A    |   B   |   C    |         D         |
  +--------+-------+--------+-------------------+
1 | ToSort |       | ToSort |                   |
  +--------+-------+--------+-------------------+
2 |  GL15  |       | GL15   | =COUNTIF(A:A, C2) |
  +--------+-------+--------+-------------------+
3 |  GL15  |       | GL16   | =COUNTIF(A:A, C3) |
  +--------+-------+--------+-------------------+
4 |  GL15  |       | GL17   | =COUNTIF(A:A, C4) |
  +--------+-------+--------+-------------------+
5 |  GL16  |       |        |                   |
  +--------+-------+--------+-------------------+
6 |  GL17  |       |        |                   |
  +--------+-------+--------+-------------------+
7 |  GL17  |       |        |                   |
  +--------+-------+--------+-------------------+

Step 1Step 2Step 3

How does MySQL process ORDER BY and LIMIT in a query?

If there is a suitable index, in this case on the publish_date field, then MySQL need not scan the whole index to get the 20 records requested - the 20 records will be found at the start of the index. But if there is no suitable index, then a full scan of the table will be needed.

There is a MySQL Performance Blog article from 2009 on this.

How to split the name string in mysql?

To get the rest of the string after the second instance of the space delimiter

SELECT
   SUBSTRING_INDEX(SUBSTRING_INDEX('Sachin ramesh tendulkar', ' ', 1), ' ', -1) AS first_name, 
       SUBSTRING_INDEX(SUBSTRING_INDEX('Sachin ramesh tendulkar', ' ', 2), ' ', -1) 
           AS middle_name,
   SUBSTRING('Sachin ramesh tendulkar',LENGTH(SUBSTRING_INDEX('Sachin ramesh tendulkar', ' ', 2))+1) AS last_name

Python script to convert from UTF-8 to ASCII

data="UTF-8 DATA"
udata=data.decode("utf-8")
asciidata=udata.encode("ascii","ignore")

Exception: There is already an open DataReader associated with this Connection which must be closed first

This exception also happens if don't use transactions properly. In my case, I put transaction.Commit() right after command.ExecuteReaderAsync(), and did not wait to commit the transaction until reader.ReadAsync() were called. The proper order:

  1. Create transaction.
  2. Create reader.
  3. Read the data.
  4. Commit the transaction.

How to disable <br> tags inside <div> by css?

You could alter your CSS to render them less obtrusively, e.g.

div p,
div br {
    display: inline;
}

http://jsfiddle.net/zG9Ax/

or - as my commenter points out:

div br {
    display: none;
}

but then to achieve the example of what you want, you'll need to trim the p down, so:

div br {
    display: none;
}
div p {
    padding: 0;
    margin: 0;
}

http://jsfiddle.net/zG9Ax/1

Filename timestamp in Windows CMD batch script getting truncated

The first four lines of this code will give you reliable YY DD MM YYYY HH Min Sec variables in XP Pro and higher, using WMIC.

@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"

set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%"
set "fullstamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause

Output example:

datestamp: "20200828"
timestamp: "085513"
fullstamp: "2020-08-28_08-55-13"
Press any key to continue . . .

pip3: command not found but python3-pip is already installed

There is no need to install virtualenv. Just create a workfolder and open your editor in it. Assuming you are using vscode,

$mkdir Directory && cd Directory
$code .

It is the best way to avoid breaking Ubuntu/linux dependencies by messing around with environments. In case anything goes wrong, you can always delete that folder and begin afresh. Otherwise, messing up with the ubuntu/linux python environments could mess up system apps/OS (including the terminal). Then you can press shift+P and type python:select interpreter. Choose any version above 3. After that you can do

$pip3 -v

It will display the pip version. You can then use it for installations as

$pip3 install Library

What's the difference between a mock & stub?

I came across this interesting article by UncleBob The Little Mocker. It explains all the terminology in a very easy to understand manner, so its useful for beginners. Martin Fowlers article is a hard read especially for beginners like me.

Android JSONObject - How can I loop through a flat JSON object to get each key and value

Use the keys() iterator to iterate over all the properties, and call get() for each.

Iterator<String> iter = json.keys();
while (iter.hasNext()) {
    String key = iter.next();
    try {
        Object value = json.get(key);
    } catch (JSONException e) {
        // Something went wrong!
    }
}

Error:Unknown host services.gradle.org. You may need to adjust the proxy settings in Gradle

Download a recent gradle release from gradle.org/releases Unzip the file and copy the gradle folder e.g. gradle 4.0 into C -- program files -- android -- android studio -- gradle. On your android studio goto file -- settings -- Build, Execution, Deployment --Build Tools -- Gradle and choose Use local gradle distribution, in the gradle home locate your gradle folder and click apply. Then click okay. This solved the problem for me. Your android studio might require a more recent gradle release, make sure you download a gradle that is compatible with your studio or latest releases.

How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas

How I redirect to an area is add it as a parameter

@Html.Action("Action", "Controller", new { area = "AreaName" })

for the href portion of a link I use

@Url.Action("Action", "Controller", new { area = "AreaName" })

How can I tell if an algorithm is efficient?

Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english

What does "zend_mm_heap corrupted" mean

I experienced this issue in local development while using docker & php's built in dev server with Craft CMS.

My solution was to use Redis for Craft's sessions.

PHP 7.4

Updating PartialView mvc 4

So, say you have your View with PartialView, which have to be updated by button click:

<div class="target">
    @{ Html.RenderAction("UpdatePoints");}
</div>

<input class="button" value="update" />

There are some ways to do it. For example you may use jQuery:

<script type="text/javascript">
    $(function(){    
        $('.button').on("click", function(){        
            $.post('@Url.Action("PostActionToUpdatePoints", "Home")').always(function(){
                $('.target').load('/Home/UpdatePoints');        
            })        
        });
    });        
</script>

PostActionToUpdatePoints is your Action with [HttpPost] attribute, which you use to update points

If you use logic in your action UpdatePoints() to update points, maybe you forgot to add [HttpPost] attribute to it:

[HttpPost]
public ActionResult UpdatePoints()
{    
    ViewBag.points =  _Repository.Points;
    return PartialView("UpdatePoints");
}

Access mysql remote database from command line

mysql servers are usually configured to listen only to localhost (127.0.0.1), where they are used by web applications.

If that is your case but you have SSH access to your server, you can create an ssh tunnel and connect through that.

On your local machine, create the tunnel.

ssh -L 3307:127.0.0.1:3306 -N $user@$remote_host

(this example uses local port 3307, in case you also have mysql running on your local machine and using the standard port 3306)

Now you should be ale to connect with

mysql -u $user -p -h 127.0.0.1 -P 3307

How to convert Strings to and from UTF8 byte arrays in Java

I can't comment but don't want to start a new thread. But this isn't working. A simple round trip:

byte[] b = new byte[]{ 0, 0, 0, -127 };  // 0x00000081
String s = new String(b,StandardCharsets.UTF_8); // UTF8 = 0x0000, 0x0000,  0x0000, 0xfffd
b = s.getBytes(StandardCharsets.UTF_8); // [0, 0, 0, -17, -65, -67] 0x000000efbfbd != 0x00000081

I'd need b[] the same array before and after encoding which it isn't (this referrers to the first answer).

TypeError: string indices must be integers, not str // working with dict

time1 is the key of the most outer dictionary, eg, feb2012. So then you're trying to index the string, but you can only do this with integers. I think what you wanted was:

for info in courses[time1][course]:

As you're going through each dictionary, you must add another nest.

How to read a Parquet file into Pandas DataFrame?

Update: since the time I answered this there has been a lot of work on this look at Apache Arrow for a better read and write of parquet. Also: http://wesmckinney.com/blog/python-parquet-multithreading/

There is a python parquet reader that works relatively well: https://github.com/jcrobak/parquet-python

It will create python objects and then you will have to move them to a Pandas DataFrame so the process will be slower than pd.read_csv for example.

How to center buttons in Twitter Bootstrap 3?

<div class="row">
  <div class="col-sm-12">
    <div class="text-center">
      <button class="btn btn-primary" id="singlebutton"> Next Step!</button>
    </div>
  </div>
</div>

How do I use vim registers?

One overlooked register is the '.' dot register which contains the last inserted text no matter how it was inserted eg ct] (change till ]). Then you realise you need to insert it elsewhere but can't use the dot repeat method.

 :reg .
 :%s/fred/<C-R>./

jQuery animate backgroundColor

I used a combination of CSS transitions with JQuery for the desired effect; obviously browsers which don't support CSS transitions will not animate but its a lightweight option which works well for most browsers and for my requirements is acceptable degradation.

Jquery to change the background color:

   $('.mylinkholder a').hover(
        function () {
            $(this).css({ backgroundColor: '#f0f0f0' }); 
        },
        function () {
            $(this).css({ backgroundColor: '#fff' });
        }
    );

CSS using transition to fade background-color change

   .mylinkholder a
   {
   transition: background-color .5s ease-in-out;
   -moz-transition: background-color .5s ease-in-out;
   -webkit-transition: background-color .5s ease-in-out; 
  -o-transition: background-color .5s ease-in-out; 
   }

How to fix Error: laravel.log could not be opened?

If problem persists after setting permissions right for the storage and bootstrap/cache folders, first confirm by turning off selinux with the command

setenforce 0 If this works after the above command, this should allow writing, but you've turned off added security server-wide. That's bad. Turn SELinux back.

setenforce 1 Then finally use SELinux to allow writing of the file by using this command

chcon -R -t httpd_sys_rw_content_t storage And you're good to go!

This link helped a lot!

How to parse JSON using Node.js?

Use JSON.parse(str);. Read more about it here.

Here are some examples:

var jsonStr = '{"result":true, "count":42}';

obj = JSON.parse(jsonStr);

console.log(obj.count);    // expected output: 42
console.log(obj.result);   // expected output: true

CSS div 100% height

try setting the body style to:

body { position:relative;}

it worked for me

How to disable input conditionally in vue.js

Your disabled attribute requires a boolean value:

<input :disabled="validated" />

Notice how i've only checked if validated - This should work as 0 is falsey ...e.g

0 is considered to be false in JS (like undefined or null)

1 is in fact considered to be true

To be extra careful try: <input :disabled="!!validated" />

This double negation turns the falsey or truthy value of 0 or 1 to false or true

don't believe me? go into your console and type !!0 or !!1 :-)

Also, to make sure your number 1 or 0 are definitely coming through as a Number and not the String '1' or '0' pre-pend the value you are checking with a + e.g <input :disabled="!!+validated"/> this turns a string of a number into a Number e.g

+1 = 1 +'1' = 1 Like David Morrow said above you could put your conditional logic into a method - this gives you more readable code - just return out of the method the condition you wish to check.

pandas: to_numeric for multiple columns

df.loc[:,'col':] = df.loc[:,'col':].apply(pd.to_numeric, errors = 'coerce')

How to determine the current shell I'm working on

This one works well on Red Hat Linux (RHEL), macOS, BSD and some AIXes:

ps -T $$ | awk 'NR==2{print $NF}' 

alternatively, the following one should also work if pstree is available,

pstree | egrep $$ | awk 'NR==2{print $NF}'

MYSQL Truncated incorrect DOUBLE value

What it basically is

It's incorrect syntax that causes MySQL to think you're trying to do something with a column or parameter that has the incorrect type "DOUBLE".

Learn from my mistake

In my case I updated the varchar column in a table setting NULL where the value 0 stood. My update query was like this:

UPDATE myTable SET myValue = NULL WHERE myValue = 0;

Now, since the actual type of myValue is VARCHAR(255) this gives the warning:

+---------+------+-----------------------------------------------+
| Level   | Code | Message                                       |
+---------+------+-----------------------------------------------+
| Warning | 1292 | Truncated incorrect DOUBLE value: 'value xyz' |
+---------+------+-----------------------------------------------+

And now myTable is practically empty, because myValue is now NULL for EVERY ROW in the table! How did this happen?
*internal screaming*

Over 30k rows now have missing data.
*internal screaming intensifies*

Thank goodness for backups. I was able to recover all the data.
*internal screaming intensity lowers*

The corrected query is as follows:

UPDATE myTable SET myValue = NULL WHERE myValue = '0';
                                                  ^^^
                                                  Quotation here!

I wish this was more than just a warning so it's less dangerous to forget those quotes.

*End internal screaming*

How to make Python speak

PYTTSX3!

WHAT:

Pyttsx3 is a python module which is a modern clone of pyttsx, modified to work perfectly well in the latest versions of Python 3!

WHY:

It is 100% MULTI-PLATFORM and WORKS OFFLINE and IS ACTIVE/STILL BEING DEVELOPED and WORKS WITH ANY PYTHON VERSION

HOW:

It can be easily installed with pip install pyttsx3 and usage is the same as pyttsx:

import pyttsx3;
engine = pyttsx3.init();
engine.say("I will speak this text");
engine.runAndWait();

This is the best multi platform option!

get DATEDIFF excluding weekends using sql server

/* EXAMPLE: /MONDAY/ SET DATEFIRST 1 SELECT dbo.FUNC_GETDATEDIFFERENCE_WO_WEEKEND('2019-02-01','2019-02-12') */ CREATE FUNCTION FUNC_GETDATEDIFFERENCE_WO_WEEKEND ( @pdtmaLastLoanPayDate DATETIME, @pdtmaDisbursedDate DATETIME ) RETURNS BIGINT BEGIN

DECLARE
@mintDaysDifference     BIGINT

SET @mintDaysDifference = 0

WHILE CONVERT(NCHAR(10),@pdtmaLastLoanPayDate,121) <= CONVERT(NCHAR(10),@pdtmaDisbursedDate,121)
BEGIN
    IF DATEPART(WEEKDAY,@pdtmaLastLoanPayDate) NOT IN (6,7)
    BEGIN
        SET @mintDaysDifference = @mintDaysDifference + 1
    END

    SET @pdtmaLastLoanPayDate = DATEADD(DAY,1,@pdtmaLastLoanPayDate)
END

RETURN ISNULL(@mintDaysDifference,0)

END

How to copy data from one HDFS to another HDFS?

Try dtIngest, it's developed on top of Apache Apex platform. This tool copies data from different sources like HDFS, shared drive, NFS, FTP, Kafka to different destinations. Copying data from remote HDFS cluster to local HDFS cluster is supported by dtIngest. dtIngest runs yarn jobs to copy data in parallel fashion, so it's very fast. It takes care of failure handling, recovery etc. and supports polling directories periodically to do continious copy.

Usage: dtingest [OPTION]... SOURCEURL... DESTINATIONURL example: dtingest hdfs://nn1:8020/source hdfs://nn2:8020/dest

HTML5 Local storage vs. Session storage

performance wise, my (crude) measurements found no difference on 1000 writes and reads

security wise, intuitively it would seem the localStore might be shut down before the sessionStore, but have no concrete evidence - maybe someone else does?

functional wise, concur with digitalFresh above

Update style of a component onScroll in React.js

Function component example using useEffect:

Note: You need to remove the event listener by returning a "clean up" function in useEffect. If you don't, every time the component updates you will have an additional window scroll listener.

import React, { useState, useEffect } from "react"

const ScrollingElement = () => {
  const [scrollY, setScrollY] = useState(0);

  function logit() {
    setScrollY(window.pageYOffset);
  }

  useEffect(() => {
    function watchScroll() {
      window.addEventListener("scroll", logit);
    }
    watchScroll();
    // Remove listener (like componentWillUnmount)
    return () => {
      window.removeEventListener("scroll", logit);
    };
  }, []);

  return (
    <div className="App">
      <div className="fixed-center">Scroll position: {scrollY}px</div>
    </div>
  );
}

Embed youtube videos that play in fullscreen automatically

This was pretty well answered over here: How to make a YouTube embedded video a full page width one?

If you add '?rel=0&autoplay=1' to the end of the url in the embed code (like this)

<iframe id="video" src="//www.youtube.com/embed/5iiPC-VGFLU?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>

of the video it should play on load. Here's a demo over at jsfiddle.

Truncate (not round off) decimal numbers in javascript

const TO_FIXED_MAX = 100;

function truncate(number, decimalsPrecison) {
  // make it a string with precision 1e-100
  number = number.toFixed(TO_FIXED_MAX);

  // chop off uneccessary digits
  const dotIndex = number.indexOf('.');
  number = number.substring(0, dotIndex + decimalsPrecison + 1);

  // back to a number data type (app specific)
  return Number.parseFloat(number);
}

// example
truncate(0.00000001999, 8);
0.00000001

works with:

  • negative numbers
  • very small numbers (Number.EPSILON precision)

Could not load file or assembly "System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

I have same issue and only way how i am able to fix it is add bindingRedirect to app.confing how wrote @tripletdad99.

But if you have solution with more project is really suck update every project by hand (and also sometimes after update some nuget package you need to do it again). And it is reason why i wrote simple powershell script which if all app.configs.

 param(
    [string]$SourceDirectory,
    [string]$Package,
    [string]$OldVersion,
    [string]$NewVersion
)

Write-Host "Start fixing app.config in $sourceDirectory"
Write-Host "$Package set oldVersion to $OldVersion and newVersion $NewVersion"
Write-Host "Search app.config files.."
[array]$files = get-childitem $sourceDirectory -Include app.config App.config -Recurse | select -expand FullName
foreach ($file in $files)
{
    Write-Host $file
    $xml = [xml](Get-Content $file)
    $daNodes = $xml.configuration.runtime.assemblyBinding.dependentAssembly
    foreach($node in $daNodes)
    {
        if($node.assemblyIdentity.name -eq $package)
        {
            $updateNode = $node.bindingRedirect
            $updateNode.oldVersion = $OldVersion
            $updateNode.newVersion =$NewVersion
            Write-Host "Fix"
        }
    }
    $xml.Save($file)
}

Write-Host "Done"

Example how to use:

./scripts/FixAppConfig.ps1 -SourceDirectory "C:\project-folder" -Package "System.Net.Http" -OldVersion "0.0.0.0-4.3.2.0" -NewVersion "4.0.0.0"

Probably it is not perfect and also it will be better if somebody link it to pre-build task.

Convert string to symbol-able in ruby

"Book Author Title".parameterize('_').to_sym
=> :book_author_title

http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-parameterize

parameterize is a rails method, and it lets you choose what you want the separator to be. It is a dash "-" by default.

Submit form without page reloading

You either use AJAX or you

  • create and append an iframe to the document
  • set the iframes name to 'foo'
  • set the forms target to 'foo'
  • submit
  • have the forms action render javascript with 'parent.notify(...)' to give feedback
  • optionally you can remove the iframe

Removing spaces from a variable input using PowerShell 4.0

The Replace operator means Replace something with something else; do not be confused with removal functionality.

Also you should send the result processed by the operator to a variable or to another operator. Neither .Replace(), nor -replace modifies the original variable.

To remove all spaces, use 'Replace any space symbol with empty string'

$string = $string -replace '\s',''

To remove all spaces at the beginning and end of the line, and replace all double-and-more-spaces or tab symbols to spacebar symbol, use

$string = $string -replace '(^\s+|\s+$)','' -replace '\s+',' '

or the more native System.String method

$string = $string.Trim()

Regexp is preferred, because ' ' means only 'spacebar' symbol, and '\s' means 'spacebar, tab and other space symbols'. Note that $string.Replace() does 'Normal' replace, and $string -replace does RegEx replace, which is more heavy but more functional.

Note that RegEx have some special symbols like dot (.), braces ([]()), slashes (\), hats (^), mathematical signs (+-) or dollar signs ($) that need do be escaped. ( 'my.space.com' -replace '\.','-' => 'my-space-com'. A dollar sign with a number (ex $1) must be used on a right part with care

'2033' -replace '(\d+)',$( 'Data: $1')
Data: 2033

UPDATE: You can also use $str = $str.Trim(), along with TrimEnd() and TrimStart(). Read more at System.String MSDN page.

How to make child process die after parent exits?

Under POSIX, the exit(), _exit() and _Exit() functions are defined to:

  • If the process is a controlling process, the SIGHUP signal shall be sent to each process in the foreground process group of the controlling terminal belonging to the calling process.

So, if you arrange for the parent process to be a controlling process for its process group, the child should get a SIGHUP signal when the parent exits. I'm not absolutely sure that happens when the parent crashes, but I think it does. Certainly, for the non-crash cases, it should work fine.

Note that you may have to read quite a lot of fine print - including the Base Definitions (Definitions) section, as well as the System Services information for exit() and setsid() and setpgrp() - to get the complete picture. (So would I!)

Get most recent file in a directory on Linux

With only Bash builtins, closely following BashFAQ/003:

shopt -s nullglob

for f in * .*; do
    [[ -d $f ]] && continue
    [[ $f -nt $latest ]] && latest=$f
done

printf '%s\n' "$latest"

How do I move an existing Git submodule within a Git repository?

The given solution did not work for me, however a similar version did...

This is with a cloned repository, hence the submodule git repos are contained in the top repositories .git dir. All cations are from the top repository:

  1. Edit .gitmodules and change the "path =" setting for the submodule in question. (No need to change the label, nor to add this file to index.)

  2. Edit .git/modules/name/config and change the "worktree =" setting for the submodule in question

  3. run:

    mv submodule newpath/submodule
    git add -u
    git add newpath/submodule
    

I wonder if it makes a difference if the repositories are atomic, or relative submodules, in my case it was relative (submodule/.git is a ref back to topproject/.git/modules/submodule)

Can I multiply strings in Java to repeat sequences?

There's no shortcut for doing this in Java like the example you gave in Python.

You'd have to do this:

for (;i > 0; i--) {
    somenum = somenum + "0";
}

How to get public directory?

The best way to retrieve your public folder path from your Laravel config is the function:

$myPublicFolder = public_path();
$savePath = $mypublicPath."enter_path_to_save";
$path = $savePath."filename.ext";
return File::put($path , $data);

There is no need to have all the variables, but this is just for a demonstrative purpose.

Hope this helps, GRnGC

PHP Pass variable to next page

Sessions would be the only good way, you could also use GET/POST but that would be potentially insecure.

SelectSingleNode returning null for known good xml node path using XPath

Well... I had the same issue and it was a headache. Since I didn't care much about the namespace or the xml schema, I just deleted this data from my xml and it solved all my issues. May not be the best answer? Probably, but if you don't want to deal with all of this and you ONLY care about the data (and won't be using the xml for some other task) deleting the namespace may solve your problems.

XmlDocument vinDoc = new XmlDocument();
string vinInfo = "your xml string";
vinDoc.LoadXml(vinInfo);

vinDoc.InnerXml = vinDoc.InnerXml.Replace("xmlns=\"http://tempuri.org\/\", "");

WHILE LOOP with IF STATEMENT MYSQL

I have discovered that you cannot have conditionals outside of the stored procedure in mysql. This is why the syntax error. As soon as I put the code that I needed between

   BEGIN
   SELECT MONTH(CURDATE()) INTO @curmonth;
   SELECT MONTHNAME(CURDATE()) INTO @curmonthname;
   SELECT DAY(LAST_DAY(CURDATE())) INTO @totaldays;
   SELECT FIRST_DAY(CURDATE()) INTO @checkweekday;
   SELECT DAY(@checkweekday) INTO @checkday;
   SET @daycount = 0;
   SET @workdays = 0;

     WHILE(@daycount < @totaldays) DO
       IF (WEEKDAY(@checkweekday) < 5) THEN
         SET @workdays = @workdays+1;
       END IF;
       SET @daycount = @daycount+1;
       SELECT ADDDATE(@checkweekday, INTERVAL 1 DAY) INTO @checkweekday;
     END WHILE;
   END

Just for others:

If you are not sure how to create a routine in phpmyadmin you can put this in the SQL query

    delimiter ;;
    drop procedure if exists test2;;
    create procedure test2()
    begin
    select ‘Hello World’;
    end
    ;;

Run the query. This will create a stored procedure or stored routine named test2. Now go to the routines tab and edit the stored procedure to be what you want. I also suggest reading http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/ if you are beginning with stored procedures.

The first_day function you need is: How to get first day of every corresponding month in mysql?

Showing the Procedure is working Simply add the following line below END WHILE and above END

    SELECT @curmonth,@curmonthname,@totaldays,@daycount,@workdays,@checkweekday,@checkday;

Then use the following code in the SQL Query Window.

    call test2 /* or whatever you changed the name of the stored procedure to */

NOTE: If you use this please keep in mind that this code does not take in to account nationally observed holidays (or any holidays for that matter).

AngularJS POST Fails: Response for preflight has invalid HTTP status code 404

For a Node.js app, in the server.js file before registering all of my own routes, I put the code below. It sets the headers for all responses. It also ends the response gracefully if it is a pre-flight "OPTIONS" call and immediately sends the pre-flight response back to the client without "nexting" (is that a word?) down through the actual business logic routes. Here is my server.js file. Relevant sections highlighted for Stackoverflow use.

// server.js

// ==================
// BASE SETUP

// import the packages we need
var express    = require('express');
var app        = express();
var bodyParser = require('body-parser');
var morgan     = require('morgan');
var jwt        = require('jsonwebtoken'); // used to create, sign, and verify tokens

// ====================================================
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// Logger
app.use(morgan('dev'));

// -------------------------------------------------------------
// STACKOVERFLOW -- PAY ATTENTION TO THIS NEXT SECTION !!!!!
// -------------------------------------------------------------

//Set CORS header and intercept "OPTIONS" preflight call from AngularJS
var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    if (req.method === "OPTIONS") 
        res.send(200);
    else 
        next();
}

// -------------------------------------------------------------
// STACKOVERFLOW -- END OF THIS SECTION, ONE MORE SECTION BELOW
// -------------------------------------------------------------


// =================================================
// ROUTES FOR OUR API

var route1 = require("./routes/route1");
var route2 = require("./routes/route2");
var error404 = require("./routes/error404");


// ======================================================
// REGISTER OUR ROUTES with app

// -------------------------------------------------------------
// STACKOVERFLOW -- PAY ATTENTION TO THIS NEXT SECTION !!!!!
// -------------------------------------------------------------

app.use(allowCrossDomain);

// -------------------------------------------------------------
//  STACKOVERFLOW -- OK THAT IS THE LAST THING.
// -------------------------------------------------------------

app.use("/api/v1/route1/", route1);
app.use("/api/v1/route2/", route2);
app.use('/', error404);

// =================
// START THE SERVER

var port = process.env.PORT || 8080;        // set our port
app.listen(port);
console.log('API Active on port ' + port);

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

It allows you to read from the standard input (mainly, the console). This SO question may helps you.

Calculate distance in meters when you know longitude and latitude in java

You can use the Java Geodesy Library for GPS, it uses the Vincenty's formulae which takes account of the earths surface curvature.

Implementation goes like this:

import org.gavaghan.geodesy.*;

...

GeodeticCalculator geoCalc = new GeodeticCalculator();

Ellipsoid reference = Ellipsoid.WGS84;  

GlobalPosition pointA = new GlobalPosition(latitude, longitude, 0.0); // Point A

GlobalPosition userPos = new GlobalPosition(userLat, userLon, 0.0); // Point B

double distance = geoCalc.calculateGeodeticCurve(reference, userPos, pointA).getEllipsoidalDistance(); // Distance between Point A and Point B

The resulting distance is in meters.

Getting and removing the first character of a string

See ?substring.

x <- 'hello stackoverflow'
substring(x, 1, 1)
## [1] "h"
substring(x, 2)
## [1] "ello stackoverflow"

The idea of having a pop method that both returns a value and has a side effect of updating the data stored in x is very much a concept from object-oriented programming. So rather than defining a pop function to operate on character vectors, we can make a reference class with a pop method.

PopStringFactory <- setRefClass(
  "PopString",
  fields = list(
    x = "character"  
  ),
  methods = list(
    initialize = function(x)
    {
      x <<- x
    },
    pop = function(n = 1)
    {
      if(nchar(x) == 0)
      {
        warning("Nothing to pop.")
        return("")
      }
      first <- substring(x, 1, n)
      x <<- substring(x, n + 1)
      first
    }
  )
)

x <- PopStringFactory$new("hello stackoverflow")
x
## Reference class object of class "PopString"
## Field "x":
## [1] "hello stackoverflow"
replicate(nchar(x$x), x$pop())
## [1] "h" "e" "l" "l" "o" " " "s" "t" "a" "c" "k" "o" "v" "e" "r" "f" "l" "o" "w"

How do I make a stored procedure in MS Access?

If you mean the type of procedure you find in SQL Server, prior to 2010, you can't. If you want a query that accepts a parameter, you can use the query design window:

 PARAMETERS SomeParam Text(10);
 SELECT Field FROM Table
 WHERE OtherField=SomeParam

You can also say:

CREATE PROCEDURE ProcedureName
   (Parameter1 datatype, Parameter2 datatype) AS
   SQLStatement

From: http://msdn.microsoft.com/en-us/library/aa139977(office.10).aspx#acadvsql_procs

Note that the procedure contains only one statement.

What is the difference between a JavaBean and a POJO?

Java beans are special type of POJOs.

Specialities listed below with reason

enter image description here

How do I use namespaces with TypeScript external modules?

Try to organize by folder:

baseTypes.ts

export class Animal {
    move() { /* ... */ }
}

export class Plant {
    photosynthesize() { /* ... */ }
}

dog.ts

import b = require('./baseTypes');

export class Dog extends b.Animal {
    woof() { }
}   

tree.ts

import b = require('./baseTypes');

class Tree extends b.Plant {
}

LivingThings.ts

import dog = require('./dog')
import tree = require('./tree')

export = {
    dog: dog,
    tree: tree
}

main.ts

import LivingThings = require('./LivingThings');
console.log(LivingThings.Tree)
console.log(LivingThings.Dog)

The idea is that your module themselves shouldn't care / know they are participating in a namespace, but this exposes your API to the consumer in a compact, sensible way which is agnostic to which type of module system you are using for the project.

End-line characters from lines read from text file, using Python

What's wrong with your code? I find it to be quite elegant and simple. The only problem is that if the file doesn't end in a newline, the last line returned won't have a '\n' as the last character, and therefore doing line = line[:-1] would incorrectly strip off the last character of the line.

The most elegant way to solve this problem would be to define a generator which took the lines of the file and removed the last character from each line only if that character is a newline:

def strip_trailing_newlines(file):
    for line in file:
        if line[-1] == '\n':
            yield line[:-1]
        else:
            yield line

f = open("myFile.txt", "r")
for line in strip_trailing_newlines(f):
    # do something with line

Email Address Validation for ASP.NET

In our code we have a specific validator inherited from the BaseValidator class.

This class does the following:

  1. Validates the e-mail address against a regular expression.
  2. Does a lookup on the MX record for the domain to make sure there is at least a server to deliver to.

This is the closest you can get to validation without actually sending the person an e-mail confirmation link.

How to convert IPython notebooks to PDF and HTML?

Also pass the --execute flag to generate the output cells

jupyter nbconvert --execute --to html notebook.ipynb
jupyter nbconvert --execute --to pdf notebook.ipynb

The best practice is to keep the output out of the notebook for version control, see: Using IPython notebooks under version control

But then, if you don't pass --execute, the output won't be present in the HTML, see also: How to run an .ipynb Jupyter Notebook from terminal?

For an HTML fragment without header: How to export an IPython notebook to HTML for a blog post?

Tested in Jupyter 4.4.0.

C++ terminate called without an active exception

How to reproduce that error:

#include <iostream>
#include <stdlib.h>
#include <string>
#include <thread>
using namespace std;
void task1(std::string msg){
  cout << "task1 says: " << msg;
}
int main() { 
  std::thread t1(task1, "hello"); 
  return 0;
}

Compile and run:

el@defiant ~/foo4/39_threading $ g++ -o s s.cpp -pthread -std=c++11
el@defiant ~/foo4/39_threading $ ./s
terminate called without an active exception
Aborted (core dumped)

You get that error because you didn't join or detach your thread.

One way to fix it, join the thread like this:

#include <iostream>
#include <stdlib.h>
#include <string>
#include <thread>
using namespace std;
void task1(std::string msg){
  cout << "task1 says: " << msg;
}
int main() { 
  std::thread t1(task1, "hello"); 
  t1.join();
  return 0;
}

Then compile and run:

el@defiant ~/foo4/39_threading $ g++ -o s s.cpp -pthread -std=c++11
el@defiant ~/foo4/39_threading $ ./s
task1 says: hello

The other way to fix it, detach it like this:

#include <iostream>
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include <thread>
using namespace std;
void task1(std::string msg){
  cout << "task1 says: " << msg;
}
int main() 
{ 
     {

        std::thread t1(task1, "hello"); 
        t1.detach();

     } //thread handle is destroyed here, as goes out of scope!

     usleep(1000000); //wait so that hello can be printed.
}

Compile and run:

el@defiant ~/foo4/39_threading $ g++ -o s s.cpp -pthread -std=c++11
el@defiant ~/foo4/39_threading $ ./s
task1 says: hello

Read up on detaching C++ threads and joining C++ threads.

How do I export html table data as .csv file?

If it's an infrequent need, try one of several firefox addons which facilitate copying HTML table data to the clipboard (e.g., https://addons.mozilla.org/en-US/firefox/addon/dafizilla-table2clipboard/). For example, for the 'table2clipboard' add-on:

  1. install the add-on in firefox
  2. open the web-page (with the table) in firefox
  3. right-click anywhere in the table and select 'copy whole table'
  4. start up a spreadsheet application such as LibreOffice Calc
  5. paste into the spreadsheet (select appropriate separator character as needed)
  6. save/export the spreadsheet as CSV.

Difference between Running and Starting a Docker container

  • run runs an image
  • start starts a container.

The docker run doc does mention:

The docker run command first creates a writeable container layer over the specified image, and then starts it using the specified command.

That is, docker run is equivalent to the API /containers/create then /containers/(id)/start.

You do not run an existing container, you docker exec to it (since docker 1.3).
You can restart an exited container.

Connect Android Studio with SVN

Android Studio is based on IntelliJ, and it comes with support for SVN (along with git and mercurial) bundled in. Check http://www.jetbrains.com/idea/features/version_control.html for more info.

Can I use GDB to debug a running process?

ps -elf doesn't seem to show the PID. I recommend using instead:

ps -ld | grep foo
gdb -p PID

What is the difference between 'SAME' and 'VALID' padding in tf.nn.max_pool of tensorflow?

Quick Explanation

VALID: Don't apply any padding, i.e., assume that all dimensions are valid so that input image fully gets covered by filter and stride you specified.

SAME: Apply padding to input (if needed) so that input image gets fully covered by filter and stride you specified. For stride 1, this will ensure that output image size is same as input.

Notes

  • This applies to conv layers as well as max pool layers in same way
  • The term "valid" is bit of a misnomer because things don't become "invalid" if you drop part of the image. Sometime you might even want that. This should have probably be called NO_PADDING instead.
  • The term "same" is a misnomer too because it only makes sense for stride of 1 when output dimension is same as input dimension. For stride of 2, output dimensions will be half, for example. This should have probably be called AUTO_PADDING instead.
  • In SAME (i.e. auto-pad mode), Tensorflow will try to spread padding evenly on both left and right.
  • In VALID (i.e. no padding mode), Tensorflow will drop right and/or bottom cells if your filter and stride doesn't full cover input image.

What is the difference among col-lg-*, col-md-* and col-sm-* in Bootstrap?

Device Sizes and class prefix:

  • Extra small devices Phones (<768px) - .col-xs-
  • Small devices Tablets (=768px) - .col-sm-
  • Medium devices Desktops (=992px) - .col-md-
  • Large devices Desktops (=1200px) - .col-lg-

Grid options:

Bootstarp Grid System

Reference: Grid System

How do I work with a git repository within another repository?

I had issues with subtrees and submodules that the other answers suggest... mainly because I am using SourceTree and it seems fairly buggy.

Instead, I ended up using SymLinks and that seems to work well so I am posting it here as a possible alternative.

There is a complete guide here: http://www.howtogeek.com/howto/16226/complete-guide-to-symbolic-links-symlinks-on-windows-or-linux/

But basically you just need to mklink the two paths in an elevated command prompt. Make sure you use the /J hard link prefix. Something along these lines: mklink /J C:\projects\MainProject\plugins C:\projects\SomePlugin

You can also use relative folder paths and put it in a bat to be executed by each person when they first check out your project.

Example: mklink /J .\Assets\TaqtileTools ..\TaqtileHoloTools

Once the folder has been linked you may need to ignore the folder within your main repository that is referencing it. Otherwise you are good to go.

Note I've deleted my duplicate answer from another post as that post was marked as a duplicate question to this one.

error: Error parsing XML: not well-formed (invalid token) ...?

I had same problem. you can't use left < arrow in text property like as android:text="< Go back" in your xml file. Remove any < arrow from you xml code.

Hope It will helps you.

Maximum length of the textual representation of an IPv6 address?

As indicated a standard ipv6 address is at most 45 chars, but an ipv6 address can also include an ending % followed by a "scope" or "zone" string, which has no fixed length but is generally a small positive integer or a network interface name, so in reality it can be bigger than 45 characters. Network interface names are typically "eth0", "eth1", "wlan0", so choosing 50 as the limit is likely good enough.

Test if registry value exists

The Carbon PowerShell module has a Test-RegistryKeyValue function that will do this check for you. (Disclosure: I am the owner/maintainer of Carbon.)

You have to check that that the registry key exists, first. You then have to handle if the registry key has no values. Most of the examples here are actually testing the value itself, instead of the existence of the value. This will return false negatives if a value is empty or null. Instead, you have to test if a property for the value actually exists on the object returned by Get-ItemProperty.

Here's the code, as it stands today, from the Carbon module:

function Test-RegistryKeyValue
{
    <#
    .SYNOPSIS
    Tests if a registry value exists.

    .DESCRIPTION
    The usual ways for checking if a registry value exists don't handle when a value simply has an empty or null value.  This function actually checks if a key has a value with a given name.

    .EXAMPLE
    Test-RegistryKeyValue -Path 'hklm:\Software\Carbon\Test' -Name 'Title'

    Returns `True` if `hklm:\Software\Carbon\Test` contains a value named 'Title'.  `False` otherwise.
    #>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)]
        [string]
        # The path to the registry key where the value should be set.  Will be created if it doesn't exist.
        $Path,

        [Parameter(Mandatory=$true)]
        [string]
        # The name of the value being set.
        $Name
    )

    if( -not (Test-Path -Path $Path -PathType Container) )
    {
        return $false
    }

    $properties = Get-ItemProperty -Path $Path 
    if( -not $properties )
    {
        return $false
    }

    $member = Get-Member -InputObject $properties -Name $Name
    if( $member )
    {
        return $true
    }
    else
    {
        return $false
    }

}

Add column with constant value to pandas dataframe

The reason this puts NaN into a column is because df.index and the Index of your right-hand-side object are different. @zach shows the proper way to assign a new column of zeros. In general, pandas tries to do as much alignment of indices as possible. One downside is that when indices are not aligned you get NaN wherever they aren't aligned. Play around with the reindex and align methods to gain some intuition for alignment works with objects that have partially, totally, and not-aligned-all aligned indices. For example here's how DataFrame.align() works with partially aligned indices:

In [7]: from pandas import DataFrame

In [8]: from numpy.random import randint

In [9]: df = DataFrame({'a': randint(3, size=10)})

In [10]:

In [10]: df
Out[10]:
   a
0  0
1  2
2  0
3  1
4  0
5  0
6  0
7  0
8  0
9  0

In [11]: s = df.a[:5]

In [12]: dfa, sa = df.align(s, axis=0)

In [13]: dfa
Out[13]:
   a
0  0
1  2
2  0
3  1
4  0
5  0
6  0
7  0
8  0
9  0

In [14]: sa
Out[14]:
0     0
1     2
2     0
3     1
4     0
5   NaN
6   NaN
7   NaN
8   NaN
9   NaN
Name: a, dtype: float64

How to use MD5 in javascript to transmit a password

You might want to check out this page: http://pajhome.org.uk/crypt/md5/

However, if protecting the password is important, you should really be using something like SHA256 (MD5 is not cryptographically secure iirc). Even more, you might want to consider using TLS and getting a cert so you can use https.

Unnamed/anonymous namespaces vs. static functions

A compiler specific difference between anonymous namespaces and static functions can be seen compiling the following code.

#include <iostream>

namespace
{
    void unreferenced()
    {
        std::cout << "Unreferenced";
    }

    void referenced()
    {
        std::cout << "Referenced";
    }
}

static void static_unreferenced()
{
    std::cout << "Unreferenced";
}

static void static_referenced()
{
    std::cout << "Referenced";
}

int main()
{
    referenced();
    static_referenced();
    return 0;
}

Compiling this code with VS 2017 (specifying the level 4 warning flag /W4 to enable warning C4505: unreferenced local function has been removed) and gcc 4.9 with the -Wunused-function or -Wall flag shows that VS 2017 will only produce a warning for the unused static function. gcc 4.9 and higher, as well as clang 3.3 and higher, will produce warnings for the unreferenced function in the namespace and also a warning for the unused static function.

Live demo of gcc 4.9 and MSVC 2017

What are all the differences between src and data-src attributes?

If you want the image to load and display a particular image, then use .src to load that image URL.

If you want a piece of meta data (on any tag) that can contain a URL, then use data-src or any data-xxx that you want to select.

MDN documentation on data-xxxx attributes: https://developer.mozilla.org/en-US/docs/DOM/element.dataset

Example of src on an image tag where the image loads the JPEG for you and displays it:

<img id="myImage" src="http://mydomain.com/foo.jpg">

<script>
    var imageUrl = document.getElementById("myImage").src;
</script>

Example of 'data-src' on a non-image tag where the image is not loaded yet - it's just a piece of meta data on the div tag:

<div id="myDiv" data-src="http://mydomain.com/foo.jpg">

<script>
    // in all browsers
    var imageUrl = document.getElementById("myDiv").getAttribute("data-src");

    // or in modern browsers
    var imageUrl = document.getElementById("myDiv").dataset.src;
</script>

Example of data-src on an image tag used as a place to store the URL of an alternate image:

<img id="myImage" src="http://mydomain.com/foo.jpg" data-src="http://mydomain.com/foo.jpg">

<script>
    var item = document.getElementById("myImage");
    // switch the image to the URL specified in data-src
    item.src = item.dataset.src;
</script>

Remove final character from string

What you are trying to do is an extension of string slicing in Python:

Say all strings are of length 10, last char to be removed:

>>> st[:9]
'abcdefghi'

To remove last N characters:

>>> N = 3
>>> st[:-N]
'abcdefg'

How to use OpenFileDialog to select a folder?

There is a hackish solution using OpenFileDialog where ValidateNames and CheckFileExists are both set to false and FileName is given a mock value to indicate that a directory is selected.

I say hack because it is confusing to users about how to select a folder. They need to be in the desired folder and then just press Open while file name says "Folder Selection."

C# Folder selection dialog

This is based on Select file or folder from the same dialog by Denis Stankovski.

OpenFileDialog folderBrowser = new OpenFileDialog();
// Set validate names and check file exists to false otherwise windows will
// not let you select "Folder Selection."
folderBrowser.ValidateNames = false;
folderBrowser.CheckFileExists = false;
folderBrowser.CheckPathExists = true;
// Always default to Folder Selection.
folderBrowser.FileName = "Folder Selection.";
if (folderBrowser.ShowDialog() == DialogResult.OK)
{
    string folderPath = Path.GetDirectoryName(folderBrowser.FileName);
    // ...
}

(grep) Regex to match non-ASCII characters?

You don't really need a regex.

printf "%s\n" *[!\ -~]*

This will show file names with control characters in their names, too, but I consider that a feature.

If you don't have any matching files, the glob will expand to just itself, unless you have nullglob set. (The expression does not match itself, so technically, this output is unambiguous.)

What's a good IDE for Python on Mac OS X?

Visual Studio Code + Official Python Plugin

Here you see an overview of its current Python features:

https://code.visualstudio.com/docs/languages/python

Chocolat

http://chocolatapp.com

It's lightweight and offers Code Completion. Costs money.

EDIT: Apparently Chocolat was an interesting option in 2013 but since then many others came up and development stalled. Nowadays I recommend Visual Studio Code + Python Plugin.

Setting up an MS-Access DB for multi-user access

Access is a great multi-user database. It has lots of built in features to handle the multi-user situation. In fact, it is so very popular because it is such a great multi-user database. There is an upper limit on how many users can all use the database at the same time doing updates and edits - depending on how knowledgeable the developer is about access and how the database has been designed - anywhere from 20 users to approx 50 users. Some access databases can be built to handle up to 50 concurrent users, while many others can handle 20 or 25 concurrent users updating the database. These figures have been observed for databases that have been in use for several or more years and have been discussed many times on the access newsgroups.

How to convert string to boolean in typescript Angular 4

I have been trying different values with JSON.parse(value) and it seems to do the work:

// true
Boolean(JSON.parse("true"));
Boolean(JSON.parse("1"));
Boolean(JSON.parse(1));
Boolean(JSON.parse(true));

// false
Boolean(JSON.parse("0")); 
Boolean(JSON.parse(0));
Boolean(JSON.parse("false"));
Boolean(JSON.parse(false));

How to add items to array in nodejs

Check out Javascript's Array API for details on the exact syntax for Array methods. Modifying your code to use the correct syntax would be:

var array = [];
calendars.forEach(function(item) {
    array.push(item.id);
});

console.log(array);

You can also use the map() method to generate an Array filled with the results of calling the specified function on each element. Something like:

var array = calendars.map(function(item) {
    return item.id;
});

console.log(array);

And, since ECMAScript 2015 has been released, you may start seeing examples using let or const instead of var and the => syntax for creating functions. The following is equivalent to the previous example (except it may not be supported in older node versions):

let array = calendars.map(item => item.id);
console.log(array);

how to open popup window using jsp or jquery?

Try this:

SCRIPT:

function winOpen()
{
    window.open("yourpage.jsp");
}

HTML:

<a href="javascript:;" onclick="winOpen()">Pop Up</a>

Read https://developer.mozilla.org/en/docs/DOM/window.open for window.open

Why is Android Studio reporting "URI is not registered"?

Select appropriate flavour in Build Variants.

If you are viewing a particular file under Flavour1, select that flavor in BuildVariants window.

If your IDE is Android Studio (3.2.1 as of this writing), you should find Build Variants window on the lower left, aligned vertically.

Array initialization in Perl

To produce the output in your comment to your post, this will do it:

use strict;
use warnings;

my @other_array = (0,0,0,1,2,2,3,3,3,4);
my @array;
my %uniqs;

$uniqs{$_}++ for @other_array;

foreach (keys %uniqs) { $array[$_]=$uniqs{$_} }

print "array[$_] = $array[$_]\n" for (0..$#array);

Output:

   array[0] = 3
   array[1] = 1
   array[2] = 2
   array[3] = 3
   array[4] = 1

This is different than your stated algorithm of producing a parallel array with zero values, but it is a more Perly way of doing it...

If you must have a parallel array that is the same size as your first array with the elements initialized to 0, this statement will dynamically do it: @array=(0) x scalar(@other_array); but really, you don't need to do that.

How to install Ruby 2.1.4 on Ubuntu 14.04

There is a PPA with up-to-date versions of Ruby 2.x for Ubuntu 12.04+:

$ sudo apt-add-repository ppa:brightbox/ruby-ng
$ sudo apt-get update
$ sudo apt-get install ruby2.4

$ ruby -v
ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-linux-gnu]

Set 4 Space Indent in Emacs in Text Mode

(defun my-custom-settings-fn ()
  (setq indent-tabs-mode t)
  (setq tab-stop-list (number-sequence 2 200 2))
  (setq tab-width 2)
  (setq indent-line-function 'insert-tab))

(add-hook 'text-mode-hook 'my-custom-settings-fn)

You have not accepted the license agreements of the following SDK components

I have resolve the problem by using the command:

  1. Go to: C:\Users\ [PC NAME] \AppData\Local\Android\sdk\tools\bin\ (If the folder is not available then download the android SDK first, or you can install it from the android studio installation process.)
  2. Shift+Left click and Press W,then Enter to open CMD on the folder path
  3. Type in the cmd: sdkmanager --licenses
  4. Once press enter, you need to accept all the licenses by pressing y

CHECKING THE LICENSES

  1. Go to: C:\Users[PC NAME]\AppData\Local\Android\sdk\
  2. Check the folder named licenses
android-googletv-license
android-sdk-license
android-sdk-preview-license
google-gdk-license
intel-android-extra-license
mips-android-sysimage-license

WAS TESTED ON CORDOVA USING THE COMMAND:

cordova build android

-- UPDATE NEW FOLDER PATH --

Open Android Studio, Tools > Sdk Manager > Android SDK Command-Line Tools (Just Opt-in)

enter image description here

SDKManager will be store in :

  1. Go to C:\Users\ [PC NAME] \AppData\Local\Android\Sdk\cmdline-tools\latest\bin
  2. Type in the cmd: sdkmanager --licenses

Documentation to using the Android SDK: https://developer.android.com/studio/command-line/sdkmanager.html

How do I make a burn down chart in Excel?

But why would you use excel when you could do it all online and have your boss check your dynamic link.

We are using this new tool since last week. http://www.burndown-charts.com/

What I do is I send my boss the link to my chart and he plays around with the links to see if we will be on time...

http://www.burndown-charts.com/teams/dreamteam/sprints/prototype-x

How to disable the ability to select in a DataGridView?

This worked for me like a charm:

row.DataGridView.Enabled = false;

row.DefaultCellStyle.BackColor = Color.LightGray;

row.DefaultCellStyle.ForeColor = Color.DarkGray;

(where row = DataGridView.NewRow(appropriate overloads);)

How to ALTER multiple columns at once in SQL Server

Put ALTER COLUMN statement inside a bracket, it should work.

ALTER TABLE tblcommodityOHLC alter ( column  
CC_CommodityContractID NUMERIC(18,0), 
CM_CommodityID NUMERIC(18,0) )

Notepad++ cached files location

I noticed it myself, and found the files inside the backup folder. You can check where it is using Menu:Settings -> Preferences -> Backup. Note : My NPP installation is portable, and on Windows, so YMMV.

How to create range in Swift?

I created the following extension:

extension String {
    func substring(from from:Int, to:Int) -> String? {
        if from<to && from>=0 && to<self.characters.count {
            let rng = self.startIndex.advancedBy(from)..<self.startIndex.advancedBy(to)
            return self.substringWithRange(rng)
        } else {
            return nil
        }
    }
}

example of use:

print("abcde".substring(from: 1, to: 10)) //nil
print("abcde".substring(from: 2, to: 4))  //Optional("cd")
print("abcde".substring(from: 1, to: 0))  //nil
print("abcde".substring(from: 1, to: 1))  //nil
print("abcde".substring(from: -1, to: 1)) //nil

SSH -L connection successful, but localhost port forwarding not working "channel 3: open failed: connect failed: Connection refused"

ssh -v -L 8783:localhost:8783 [email protected]
...
channel 3: open failed: connect failed: Connection refused

When you connect to port 8783 on your local system, that connection is tunneled through your ssh link to the ssh server on server.com. From there, the ssh server makes TCP connection to localhost port 8783 and relays data between the tunneled connection and the connection to target of the tunnel.

The "connection refused" error is coming from the ssh server on server.com when it tries to make the TCP connection to the target of the tunnel. "Connection refused" means that a connection attempt was rejected. The simplest explanation for the rejection is that, on server.com, there's nothing listening for connections on localhost port 8783. In other words, the server software that you were trying to tunnel to isn't running, or else it is running but it's not listening on that port.

How to convert char to integer in C?

In the old days, when we could assume that most computers used ASCII, we would just do

int i = c[0] - '0';

But in these days of Unicode, it's not a good idea. It was never a good idea if your code had to run on a non-ASCII computer.

Edit: Although it looks hackish, evidently it is guaranteed by the standard to work. Thanks @Earwicker.

What does the servlet <load-on-startup> value signify

--> (Absence of load-on-start-up) tag First of all when ever servlet is deployed in the server, It is the responsibility of the server to creates the servlet object. Eg: Suppose Servlet is deployed in the server ,(Servlet Object is not available in server) client sends the request to the servlet for the first time then server creates the servlet object with help of default constructor and immediately calls init() . From that when ever client sends the request only service method will get executed as object is already available

If load-on-start-up tag is used in deployment descriptor: At the time of deployment itself the server creates the servlet object for the servlets based on the positive value provided in between the tags. The Creation of objects for the servlet classes will follow from 0-128 0 number servlet will be created first and followed by other numbers.

If we provide same value for two servlets in web.xml then creation of objects will be done based on the position of classes in web.xml also varies from server to server.

If we provide negative value in between the load on start up tag then server wont create the servlet object.

Other Scenarios where server creates the object for servlet.

If we dont use load on start up tag in web.xml, then project is deployed when ever client sends the request for the first time server creates the object and server is responsible for calling its life cycle methods. Then if a .class is been modified in the server(tomcat). again client sends the request for modified servlet but in case of tomcat new object will not created and server make use of existing object unless restart of server takes place. But in class of web-logic when ever .class file is modified in the server with out restarting the server if it receives a request then server calls the destroy method on existing servlet and creates a new servlet object and calls init() for its initilization.

xampp MySQL does not start

If you have previously installed MySQL Workbench the problem is that another MySQL instance is running at 3306 port.

So uninstall MySQL and XAMPP and after that, reinstall only XAMPP.

This worked for me.

Conda: Installing / upgrading directly from github

I found a reference to this in condas issues. The following should now work.

name: sample_env
channels:
dependencies:
   - requests
   - bokeh>=0.10.0
   - pip:
     - git+https://github.com/pythonforfacebook/facebook-sdk.git

Using colors with printf

This is a little function that prints colored text using bash scripting. You may add as many styles as you want, and even print tabs and new lines:

#!/bin/bash

# prints colored text
print_style () {

    if [ "$2" == "info" ] ; then
        COLOR="96m";
    elif [ "$2" == "success" ] ; then
        COLOR="92m";
    elif [ "$2" == "warning" ] ; then
        COLOR="93m";
    elif [ "$2" == "danger" ] ; then
        COLOR="91m";
    else #default color
        COLOR="0m";
    fi

    STARTCOLOR="\e[$COLOR";
    ENDCOLOR="\e[0m";

    printf "$STARTCOLOR%b$ENDCOLOR" "$1";
}

print_style "This is a green text " "success";
print_style "This is a yellow text " "warning";
print_style "This is a light blue with a \t tab " "info";
print_style "This is a red text with a \n new line " "danger";
print_style "This has no color";

Android Reading from an Input stream efficiently

If the file is long, you can optimize your code by appending to a StringBuilder instead of using a String concatenation for each line.

How do I copy the contents of a String to the clipboard in C#?

In Windows Forms, if your string is in a textbox, you can easily use this:

textBoxcsharp.SelectAll();
textBoxcsharp.Copy();
textBoxcsharp.DeselectAll();

shorthand c++ if else statement

The basic syntax for using ternary operator is like this:

(condition) ? (if_true) : (if_false)

For you case it is like this:

number < 0 ? bigInt.sign = 0 : bigInt.sign = 1;

An error occurred while executing the command definition. See the inner exception for details

In my case, It was from Stored Producers. I was removed a field from table and forgotten to remove it from my SP.

Hour from DateTime? in 24 hours format

Using ToString("HH:mm") certainly gives you what you want as a string.

If you want the current hour/minute as numbers, string manipulation isn't necessary; you can use the TimeOfDay property:

TimeSpan timeOfDay = fechaHora.TimeOfDay;
int hour = timeOfDay.Hours;
int minute = timeOfDay.Minutes;

CronJob not running

Finally I found the solution. Following is the solution:-

  1. Never use relative path in python scripts to be executed via crontab. I did something like this instead:-

    import os
    import sys
    import time, datetime
    
    CLASS_PATH = '/srv/www/live/mainapp/classes'
    SETTINGS_PATH = '/srv/www/live/foodtrade'
    sys.path.insert(0, CLASS_PATH)
    sys.path.insert(1,SETTINGS_PATH)
    
    import other_py_files
    
  2. Never supress the crontab code instead use mailserver and check the mail for the user. That gives clearer insights of what is going.

android TextView: setting the background color dynamically doesn't work

tv.setTextColor(getResources().getColor(R.color.solid_red));

Should I set max pool size in database connection string? What happens if I don't?

We can define maximum pool size in following way:

                <pool> 
               <min-pool-size>5</min-pool-size>
                <max-pool-size>200</max-pool-size>
                <prefill>true</prefill>
                <use-strict-min>true</use-strict-min>
                <flush-strategy>IdleConnections</flush-strategy>
                </pool>

How do I find a list of Homebrew's installable packages?

brew help will show you the list of commands that are available.

brew list will show you the list of installed packages. You can also append formulae, for example brew list postgres will tell you of files installed by postgres (providing it is indeed installed).

brew search <search term> will list the possible packages that you can install. brew search post will return multiple packages that are available to install that have post in their name.

brew info <package name> will display some basic information about the package in question.

You can also search http://searchbrew.com or https://brewformulas.org (both sites do basically the same thing)

jsonify a SQLAlchemy result set in Flask

Here's my approach: https://github.com/n0nSmoker/SQLAlchemy-serializer

pip install SQLAlchemy-serializer

You can easily add mixin to your model and than just call .to_dict() method on it's instance

You also can write your own mixin on base of SerializerMixin

Issue pushing new code in Github

Assuming that you added the Readme.md file through the interface provided by github, the readme is not yet in your local folder. Hence, when you try to push to the remote repo, you get an error, because your local repo is lacking the readme file - it's "behind the times", so to speak. Hence, as is suggested in the error message, try "git pull" first. This will pull the readme from the remote repository and merge it with your local directory. After that, you should have no problem pushing to the remote repo (the commands you posted look valid to me).

Format price in the current locale and currency

try this:

<?php echo Mage::app()->getLocale()->currency(Mage::app()->getStore()->getCurrentCurrencyCode())->getSymbol(); ?>

JavaScript open in a new window, not tab

I may be wrong, but from what I understand, this is controlled by the user's browser preferences, and I do not believe that this can be overridden.

ArrayList initialization equivalent to array initialization

The selected answer is: ArrayList<Integer>(Arrays.asList(1,2,3,5,8,13,21));

However, its important to understand the selected answer internally copies the elements several times before creating the final array, and that there is a way to reduce some of that redundancy.

Lets start by understanding what is going on:

  1. First, the elements are copied into the Arrays.ArrayList<T> created by the static factory Arrays.asList(T...).

    This does not the produce the same class as java.lang.ArrayListdespite having the same simple class name. It does not implement methods like remove(int) despite having a List interface. If you call those methods it will throw an UnspportedMethodException. But if all you need is a fixed-sized list, you can stop here.

  2. Next the Arrays.ArrayList<T> constructed in #1 gets passed to the constructor ArrayList<>(Collection<T>) where the collection.toArray() method is called to clone it.

    public ArrayList(Collection<? extends E> collection) {
    ......
    Object[] a = collection.toArray();
    }
    
  3. Next the constructor decides whether to adopt the cloned array, or copy it again to remove the subclass type. Since Arrays.asList(T...) internally uses an array of type T, the very same one we passed as the parameter, the constructor always rejects using the clone unless T is a pure Object. (E.g. String, Integer, etc all get copied again, because they extend Object).

    if (a.getClass() != Object[].class) {      
        //Arrays.asList(T...) is always true here 
        //when T subclasses object
        Object[] newArray = new Object[a.length];
        System.arraycopy(a, 0, newArray, 0, a.length);
        a = newArray;
    }
    array = a;
    size = a.length;
    

Thus, our data was copied 3x just to explicitly initialize the ArrayList. We could get it down to 2x if we force Arrays.AsList(T...) to construct an Object[] array, so that ArrayList can later adopt it, which can be done as follows:

(List<Integer>)(List<?>) new ArrayList<>(Arrays.asList((Object) 1, 2 ,3, 4, 5));

Or maybe just adding the elements after creation might still be the most efficient.

Get index of current item in a PowerShell loop

0..($letters.count-1) | foreach { "Value: {0}, Index: {1}" -f $letters[$_],$_}

Form/JavaScript not working on IE 11 with error DOM7011

I have seen exactly the same error, also with IE11. In my case the issue occurred when user clicked <button> element, which was inside <form> tags.

The issue was remedied, by placing the <button> outside of <form> tags.

Node.js - EJS - including a partial

_x000D_
_x000D_
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">_x000D_
_x000D_
 <form method="post" class="mt-3">_x000D_
        <div class="form-group col-md-4">_x000D_
          <input type="text" class="form-control form-control-lg" id="plantName" name="plantName" placeholder="plantName">_x000D_
        </div>_x000D_
        <div class="form-group col-md-4">_x000D_
          <input type="text" class="form-control form-control-lg" id="price" name="price" placeholder="price">_x000D_
        </div>_x000D_
        <div class="form-group col-md-4">_x000D_
            <input type="text" class="form-control form-control-lg" id="harvestTime" name="harvestTime" placeholder="time to harvest">_x000D_
          </div>_x000D_
        <button type="submit" class="btn btn-primary btn-lg col-md-4">Submit</button>_x000D_
      </form>_x000D_
_x000D_
<form method="post">_x000D_
        <table class="table table-striped table-responsive-md">_x000D_
            <thead>_x000D_
            <tr>_x000D_
                <th scope="col">Id</th>_x000D_
                <th scope="col">FarmName</th>_x000D_
                <th scope="col">Player Name</th>_x000D_
                <th scope="col">Birthday Date</th>_x000D_
                <th scope="col">Money</th>_x000D_
                <th scope="col">Day Played</th>_x000D_
                <th scope="col">Actions</th>_x000D_
            </tr>_x000D_
            </thead>_x000D_
            <tbody>_x000D_
            <%for (let i = 0; i < farms.length; i++) {%>_x000D_
                 <tr>_x000D_
                    <td><%= farms[i]['id'] %></td>_x000D_
                    <td><%= farms[i]['farmName'] %></td>_x000D_
                    <td><%= farms[i]['playerName'] %></td>_x000D_
                    <td><%= farms[i]['birthDayDate'] %></td>_x000D_
                    <td><%= farms[i]['money'] %></td>_x000D_
                    <td><%= farms[i]['dayPlayed'] %></td>_x000D_
                    <td><a href="<%=`/farms/${farms[i]['id']}`%>">Look at Farm</a></td>_x000D_
                </tr>_x000D_
            <%}%>_x000D_
        </table>_x000D_
    </form>
_x000D_
_x000D_
_x000D_

Setting Action Bar title and subtitle

Try this one:

android.support.v7.app.ActionBar ab = getSupportActionBar();
ab.setTitle("This is Title");
ab.setSubtitle("This is Subtitle");

Mockito : doAnswer Vs thenReturn

doAnswer and thenReturn do the same thing if:

  1. You are using Mock, not Spy
  2. The method you're stubbing is returning a value, not a void method.

Let's mock this BookService

public interface BookService {
    String getAuthor();
    void queryBookTitle(BookServiceCallback callback);
}

You can stub getAuthor() using doAnswer and thenReturn.

BookService service = mock(BookService.class);
when(service.getAuthor()).thenReturn("Joshua");
// or..
doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        return "Joshua";
    }
}).when(service).getAuthor();

Note that when using doAnswer, you can't pass a method on when.

// Will throw UnfinishedStubbingException
doAnswer(invocation -> "Joshua").when(service.getAuthor());

So, when would you use doAnswer instead of thenReturn? I can think of two use cases:

  1. When you want to "stub" void method.

Using doAnswer you can do some additionals actions upon method invocation. For example, trigger a callback on queryBookTitle.

BookServiceCallback callback = new BookServiceCallback() {
    @Override
    public void onSuccess(String bookTitle) {
        assertEquals("Effective Java", bookTitle);
    }
};
doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        BookServiceCallback callback = (BookServiceCallback) invocation.getArguments()[0];
        callback.onSuccess("Effective Java");
        // return null because queryBookTitle is void
        return null;
    }
}).when(service).queryBookTitle(callback);
service.queryBookTitle(callback);
  1. When you are using Spy instead of Mock

When using when-thenReturn on Spy Mockito will call real method and then stub your answer. This can cause a problem if you don't want to call real method, like in this sample:

List list = new LinkedList();
List spy = spy(list);
// Will throw java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
when(spy.get(0)).thenReturn("java");
assertEquals("java", spy.get(0));

Using doAnswer we can stub it safely.

List list = new LinkedList();
List spy = spy(list);
doAnswer(invocation -> "java").when(spy).get(0);
assertEquals("java", spy.get(0));

Actually, if you don't want to do additional actions upon method invocation, you can just use doReturn.

List list = new LinkedList();
List spy = spy(list);
doReturn("java").when(spy).get(0);
assertEquals("java", spy.get(0));

ModalPopupExtender OK Button click event not firing?

Put into the Button-Control the Attribute "UseSubmitBehavior=false".

Maven:Non-resolvable parent POM and 'parent.relativePath' points at wrong local POM

You can try with the following way,

 <parent>
    <groupId></groupId>
    <artifactId></artifactId>
    <version></version>
  </parent>

So that the parent jar will be fetching from the repository.

Let JSON object accept bytes or let urlopen output strings

As of Python 3.6, you can use json.loads() to deserialize a bytesobject directly (the encoding must be UTF-8, UTF-16 or UTF-32). So, using only modules from the standard library, you can do:

import json
from urllib import request

response = request.urlopen(url).read()
data = json.loads(response)

JavaScript and Threads

In raw Javascript, the best that you can do is using the few asynchronous calls (xmlhttprequest), but that's not really threading and very limited. Google Gears adds a number of APIs to the browser, some of which can be used for threading support.

React Native - Image Require Module using Dynamic Names

Important Part here: We cannot concat the image name inside the require like [require('item'+vairable+'.png')]

Step 1: We create a ImageCollection.js file with the following collection of image properties

ImageCollection.js
================================
export default images={
    "1": require("./item1.png"),
    "2": require("./item2.png"),
    "3": require("./item3.png"),
    "4": require("./item4.png"),
    "5": require("./item5.png")
}

Step 2: Import image in your app and manipulate as necessary

class ListRepoApp extends Component {

    renderItem = ({item }) => (
        <View style={styles.item}>
            <Text>Item number :{item}</Text>
            <Image source={Images[item]}/>
        </View>
    );

    render () {
        const data = ["1","2","3","4","5"]
        return (
            <FlatList data={data} renderItem={this.renderItem}/>
        )
    }
}

export default ListRepoApp;

If you want a detailed explanation you could follow the link below Visit https://www.thelearninguy.com/react-native-require-image-using-dynamic-names

Courtesy : https://www.thelearninguy.com

Unix's 'ls' sort by name

For something simple, you can combine ls with sort. For just a list of file names:
ls -1 | sort

To sort them in reverse order:
ls -1 | sort -r