Programs & Examples On #Layoutparams

The LayoutParams is a helper class that stores various layout information related to the Android view for which it is used.

Auto-fit TextView for Android

My requirement is to

  • Click on the ScalableTextView
  • Open a listActivity and display various length string items.
  • Select a text from list.
  • Set the text back to the ScalableTextView in another activity.

I referred the link: Auto Scale TextView Text to Fit within Bounds (including comments) and also the DialogTitle.java

I found that the solution provided is nice and simple but it does not dynamically change the size of the text box. It works great when the selected text length from the list view is greater in size than the existing text lenght in the ScalableTextView. When selected the text having length smaller than the existing text in the ScalableTextView, it do not increase the size of the text, showing the text in the smaller size.

I modified the ScalableTextView.java to readjust the text size based on the text length. Here is my ScalableTextView.java

public class ScalableTextView extends TextView
{
float defaultTextSize = 0.0f;

public ScalableTextView(Context context, AttributeSet attrs, int defStyle)
{
    super(context, attrs, defStyle);
    setSingleLine();
    setEllipsize(TruncateAt.END);
    defaultTextSize = getTextSize();
}

public ScalableTextView(Context context, AttributeSet attrs)
{
    super(context, attrs);
    setSingleLine();
    setEllipsize(TruncateAt.END);
    defaultTextSize = getTextSize();
}

public ScalableTextView(Context context)
{
    super(context);
    setSingleLine();
    setEllipsize(TruncateAt.END);
    defaultTextSize = getTextSize();
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
    setTextSize(TypedValue.COMPLEX_UNIT_PX, defaultTextSize);
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    final Layout layout = getLayout();
    if (layout != null)
    {
        final int lineCount = layout.getLineCount();
        if (lineCount > 0)
        {
            int ellipsisCount = layout.getEllipsisCount(lineCount - 1);
            while (ellipsisCount > 0)
            {
                final float textSize = getTextSize();

                // textSize is already expressed in pixels
                setTextSize(TypedValue.COMPLEX_UNIT_PX, (textSize - 1));

                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
                ellipsisCount = layout.getEllipsisCount(lineCount - 1);
            }
        }
    }
}
}

Happy Coding....

Delete specific line from a text file?

You can actually use C# generics for this to make it real easy:

        var file = new List<string>(System.IO.File.ReadAllLines("C:\\path"));
        file.RemoveAt(12);
        File.WriteAllLines("C:\\path", file.ToArray());

Splitting strings in PHP and get last part

You can do it like this:

$str = "abc-123-xyz-789";
$arr = explode('-', $str);
$last = array_pop( $arr );
echo $last; //echoes 789

Laravel blade check empty foreach

It's an array, so ==== '' won't work (the === means it has to be an empty string.)

Use count() to identify the array has any elements (count returns a number, 1 or greater will evaluate to true, 0 = false.)

@if (count($status->replies) > 0)
 // your HTML + foreach loop
@endif

AngularJS : Initialize service with asynchronous data

So I found a solution. I created an angularJS service, we'll call it MyDataRepository and I created a module for it. I then serve up this javascript file from my server-side controller:

HTML:

<script src="path/myData.js"></script>

Server-side:

@RequestMapping(value="path/myData.js", method=RequestMethod.GET)
public ResponseEntity<String> getMyDataRepositoryJS()
{
    // Populate data that I need into a Map
    Map<String, String> myData = new HashMap<String,String>();
    ...
    // Use Jackson to convert it to JSON
    ObjectMapper mapper = new ObjectMapper();
    String myDataStr = mapper.writeValueAsString(myData);

    // Then create a String that is my javascript file
    String myJS = "'use strict';" +
    "(function() {" +
    "var myDataModule = angular.module('myApp.myData', []);" +
    "myDataModule.service('MyDataRepository', function() {" +
        "var myData = "+myDataStr+";" +
        "return {" +
            "getData: function () {" +
                "return myData;" +
            "}" +
        "}" +
    "});" +
    "})();"

    // Now send it to the client:
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.add("Content-Type", "text/javascript");
    return new ResponseEntity<String>(myJS , responseHeaders, HttpStatus.OK);
}

I can then inject MyDataRepository where ever I need it:

someOtherModule.service('MyOtherService', function(MyDataRepository) {
    var myData = MyDataRepository.getData();
    // Do what you have to do...
}

This worked great for me, but I am open to any feedback if anyone has any. }

Set NA to 0 in R

You can just use the output of is.na to replace directly with subsetting:

bothbeams.data[is.na(bothbeams.data)] <- 0

Or with a reproducible example:

dfr <- data.frame(x=c(1:3,NA),y=c(NA,4:6))
dfr[is.na(dfr)] <- 0
dfr
  x y
1 1 0
2 2 4
3 3 5
4 0 6

However, be careful using this method on a data frame containing factors that also have missing values:

> d <- data.frame(x = c(NA,2,3),y = c("a",NA,"c"))
> d[is.na(d)] <- 0
Warning message:
In `[<-.factor`(`*tmp*`, thisvar, value = 0) :
  invalid factor level, NA generated

It "works":

> d
  x    y
1 0    a
2 2 <NA>
3 3    c

...but you likely will want to specifically alter only the numeric columns in this case, rather than the whole data frame. See, eg, the answer below using dplyr::mutate_if.

Fundamental difference between Hashing and Encryption algorithms

My two liners... generally Interviewer wanted the below answer.

Hashing is one way . You can not convert your data/ string from a hash code.

Encryption is 2 way - you can decrypt again the encrypted string if you have the key with you.

How to implement authenticated routes in React Router 4?

(Using Redux for state management)

If user try to access any url, first i am going to check if access token available, if not redirect to login page, Once user logs in using login page, we do store that in localstorage as well as in our redux state. (localstorage or cookies..we keep this topic out of context for now).
since redux state as updated and privateroutes will be rerendered. now we do have access token so we gonna redirect to home page.

Store the decoded authorization payload data as well in redux state and pass it to react context. (We dont have to use context but to access authorization in any of our nested child components it makes easy to access from context instead connecting each and every child component to redux)..

All the routes that don't need special roles can be accessed directly after login.. If it need role like admin (we made a protected route which checks whether he had desired role if not redirects to unauthorized component)

similarly in any of your component if you have to disable button or something based on role.

simply you can do in this way

const authorization = useContext(AuthContext);
const [hasAdminRole] = checkAuth({authorization, roleType:"admin"});
const [hasLeadRole] = checkAuth({authorization, roleType:"lead"});
<Button disable={!hasAdminRole} />Admin can access</Button>
<Button disable={!hasLeadRole || !hasAdminRole} />admin or lead can access</Button>

So what if user try to insert dummy token in localstorage. As we do have access token, we will redirect to home component. My home component will make rest call to grab data, since jwt token was dummy, rest call will return unauthorized user. So i do call logout (which will clear localstorage and redirect to login page again). If home page has static data and not making any api calls(then you should have token-verify api call in the backend so that you can check if token is REAL before loading home page)

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Switch } from 'react-router-dom';
import history from './utils/history';


import Store from './statemanagement/store/configureStore';
import Privateroutes from './Privateroutes';
import Logout from './components/auth/Logout';

ReactDOM.render(
  <Store>
    <Router history={history}>
      <Switch>
        <Route path="/logout" exact component={Logout} />
        <Route path="/" exact component={Privateroutes} />
        <Route path="/:someParam" component={Privateroutes} />
      </Switch>
    </Router>
  </Store>,
  document.querySelector('#root')
);

History.js

import { createBrowserHistory as history } from 'history';

export default history({});

Privateroutes.js

import React, { Fragment, useContext } from 'react';
import { Route, Switch, Redirect } from 'react-router-dom';
import { connect } from 'react-redux';
import { AuthContext, checkAuth } from './checkAuth';
import App from './components/App';
import Home from './components/home';
import Admin from './components/admin';
import Login from './components/auth/Login';
import Unauthorized from './components/Unauthorized ';
import Notfound from './components/404';

const ProtectedRoute = ({ component: Component, roleType, ...rest })=> { 
const authorization = useContext(AuthContext);
const [hasRequiredRole] = checkAuth({authorization, roleType});
return (
<Route
  {...rest}
  render={props => hasRequiredRole ? 
  <Component {...props} /> :
   <Unauthorized {...props} />  } 
/>)}; 

const Privateroutes = props => {
  const { accessToken, authorization } = props.authData;
  if (accessToken) {
    return (
      <Fragment>
       <AuthContext.Provider value={authorization}>
        <App>
          <Switch>
            <Route exact path="/" component={Home} />
            <Route path="/login" render={() => <Redirect to="/" />} />
            <Route exact path="/home" component={Home} />
            <ProtectedRoute
            exact
            path="/admin"
            component={Admin}
            roleType="admin"
          />
            <Route path="/404" component={Notfound} />
            <Route path="*" render={() => <Redirect to="/404" />} />
          </Switch>
        </App>
        </AuthContext.Provider>
      </Fragment>
    );
  } else {
    return (
      <Fragment>
        <Route exact path="/login" component={Login} />
        <Route exact path="*" render={() => <Redirect to="/login" />} />
      </Fragment>
    );
  }
};

// my user reducer sample
// const accessToken = localStorage.getItem('token')
//   ? JSON.parse(localStorage.getItem('token')).accessToken
//   : false;

// const initialState = {
//   accessToken: accessToken ? accessToken : null,
//   authorization: accessToken
//     ? jwtDecode(JSON.parse(localStorage.getItem('token')).accessToken)
//         .authorization
//     : null
// };

// export default function(state = initialState, action) {
// switch (action.type) {
// case actionTypes.FETCH_LOGIN_SUCCESS:
//   let token = {
//                  accessToken: action.payload.token
//               };
//   localStorage.setItem('token', JSON.stringify(token))
//   return {
//     ...state,
//     accessToken: action.payload.token,
//     authorization: jwtDecode(action.payload.token).authorization
//   };
//    default:
//         return state;
//    }
//    }

const mapStateToProps = state => {
  const { authData } = state.user;
  return {
    authData: authData
  };
};

export default connect(mapStateToProps)(Privateroutes);

checkAuth.js

import React from 'react';

export const AuthContext = React.createContext();

export const checkAuth = ({ authorization, roleType }) => {
  let hasRequiredRole = false;

  if (authorization.roles ) {
    let roles = authorization.roles.map(item =>
      item.toLowerCase()
    );

    hasRequiredRole = roles.includes(roleType);
  }

  return [hasRequiredRole];
};

DECODED JWT TOKEN SAMPLE

{
  "authorization": {
    "roles": [
      "admin",
      "operator"
    ]
  },
  "exp": 1591733170,
  "user_id": 1,
  "orig_iat": 1591646770,
  "email": "hemanthvrm@stackoverflow",
  "username": "hemanthvrm"
}

Why is my asynchronous function returning Promise { <pending> } instead of a value?

See the MDN section on Promises. In particular, look at the return type of then().

To log in, the user-agent has to submit a request to the server and wait to receive a response. Since making your application totally stop execution during a request round-trip usually makes for a bad user experience, practically every JS function that logs you in (or performs any other form of server interaction) will use a Promise, or something very much like it, to deliver results asynchronously.

Now, also notice that return statements are always evaluated in the context of the function they appear in. So when you wrote:

let AuthUser = data => {
  return google
    .login(data.username, data.password)
    .then( token => {
      return token;
    });
};

the statement return token; meant that the anonymous function being passed into then() should return the token, not that the AuthUser function should. What AuthUser returns is the result of calling google.login(username, password).then(callback);, which happens to be a Promise.

Ultimately your callback token => { return token; } does nothing; instead, your input to then() needs to be a function that actually handles the token in some way.

What do multiple arrow functions mean in javascript?

Brief and simple

It is a function which returns another function written in short way.

const handleChange = field => e => {
  e.preventDefault()
  // Do something here
}

// is equal to 
function handleChange(field) {
  return function(e) {
    e.preventDefault()
    // Do something here
  }
}

Why people do it ?

Have you faced when you need to write a function which can be customized? Or you have to write a callback function which has fixed parameters (arguments), but you need to pass more variables to the function but avoiding global variables? If your answer "yes" then it is the way how to do it.

For example we have a button with onClick callback. And we need to pass id to the function, but onClick accepts only one parameter event, we can not pass extra parameters within like this:

const handleClick = (event, id) {
  event.preventDefault()
  // Dispatch some delete action by passing record id
}

It will not work!

Therefore we make a function which will return other function with its own scope of variables without any global variables, because global variables are evil .

Below the function handleClick(props.id)} will be called and return a function and it will have id in its scope! No matter how many times it will be pressed the ids will not effect or change each other, they are totally isolated.

const handleClick = id => event {
  event.preventDefault()
  // Dispatch some delete action by passing record id
}

const Confirm = props => (
  <div>
    <h1>Are you sure to delete?</h1>
    <button onClick={handleClick(props.id)}>
      Delete
    </button>
  </div
)

Other benefit

A function which returns another function also called "curried functions" and they are used for function compositions.

You can find example here: https://gist.github.com/sultan99/13ef56b4089789a8d115869ee2c5ec47

Sending Arguments To Background Worker?

Even though this is an already answered question, I'd leave another option that IMO is a lot easier to read:

BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (obj, e) => WorkerDoWork(value, text);
worker.RunWorkerAsync();

And on the handler method:

private void WorkerDoWork(int value, string text) {
    ...
}

jquery change div text

Put the title in its own span.

<span id="dialog_title_span">'+dialog_title+'</span>
$('#dialog_title_span').text("new dialog title");

What's the difference between select_related and prefetch_related in Django ORM?

Both methods achieve the same purpose, to forego unnecessary db queries. But they use different approaches for efficiency.

The only reason to use either of these methods is when a single large query is preferable to many small queries. Django uses the large query to create models in memory preemptively rather than performing on demand queries against the database.

select_related performs a join with each lookup, but extends the select to include the columns of all joined tables. However this approach has a caveat.

Joins have the potential to multiply the number of rows in a query. When you perform a join over a foreign key or one-to-one field, the number of rows won't increase. However, many-to-many joins do not have this guarantee. So, Django restricts select_related to relations that won't unexpectedly result in a massive join.

The "join in python" for prefetch_related is a little more alarming then it should be. It creates a separate query for each table to be joined. It filters each of these table with a WHERE IN clause, like:

SELECT "credential"."id",
       "credential"."uuid",
       "credential"."identity_id"
FROM   "credential"
WHERE  "credential"."identity_id" IN
    (84706, 48746, 871441, 84713, 76492, 84621, 51472);

Rather than performing a single join with potentially too many rows, each table is split into a separate query.

Python Requests and persistent sessions

Save only required cookies and reuse them.

import os
import pickle
from urllib.parse import urljoin, urlparse

login = '[email protected]'
password = 'secret'
# Assuming two cookies are used for persistent login.
# (Find it by tracing the login process)
persistentCookieNames = ['sessionId', 'profileId']
URL = 'http://example.com'
urlData = urlparse(URL)
cookieFile = urlData.netloc + '.cookie'
signinUrl = urljoin(URL, "/signin")
with requests.Session() as session:
    try:
        with open(cookieFile, 'rb') as f:
            print("Loading cookies...")
            session.cookies.update(pickle.load(f))
    except Exception:
        # If could not load cookies from file, get the new ones by login in
        print("Login in...")
        post = session.post(
            signinUrl,
            data={
                'email': login,
                'password': password,
            }
        )
        try:
            with open(cookieFile, 'wb') as f:
                jar = requests.cookies.RequestsCookieJar()
                for cookie in session.cookies:
                    if cookie.name in persistentCookieNames:
                        jar.set_cookie(cookie)
                pickle.dump(jar, f)
        except Exception as e:
            os.remove(cookieFile)
            raise(e)
    MyPage = urljoin(URL, "/mypage")
    page = session.get(MyPage)

How to Clone Objects

Since the MemberwiseClone() method is not public, I created this simple extension method in order to make it easier to clone objects:

public static T Clone<T>(this T obj)
{
    var inst = obj.GetType().GetMethod("MemberwiseClone", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);

    return (T)inst?.Invoke(obj, null);
}

Usage:

var clone = myObject.Clone();

How to set default values in Go structs

One possible idea is to write separate constructor function

//Something is the structure we work with
type Something struct {
     Text string 
     DefaultText string 
} 
// NewSomething create new instance of Something
func NewSomething(text string) Something {
   something := Something{}
   something.Text = text
   something.DefaultText = "default text"
   return something
}

How can I convert tabs to spaces in every file of a directory?

You can use find with tabs-to-spaces package for this.

First, install tabs-to-spaces

npm install -g tabs-to-spaces

then, run this command from the root directory of your project;

find . -name '*' -exec t2s --spaces 2 {} \;

This will replace every tab character with 2 spaces in every file.

Reactive forms - disabled attribute

this.form.disable()
this.form.enable()

For one formcontrol makes disable

this.form.get('first').disable()
this.form.get('first').enable()

Or initial set method.

first: new FormControl({disabled: true}, Validators.required)

Automatic Preferred Max Layout Width is not available on iOS versions prior to 8.0

Solution it's quite simple

Just enable Builds for iOS 8 and Later

enter image description here

What is HTML5 ARIA?

What is it?

WAI-ARIA stands for “Web Accessibility Initiative – Accessible Rich Internet Applications”. It is a set of attributes to help enhance the semantics of a web site or web application to help assistive technologies, such as screen readers for the blind, make sense of certain things that are not native to HTML. The information exposed can range from something as simple as telling a screen reader that activating a link or button just showed or hid more items, to widgets as complex as whole menu systems or hierarchical tree views.

This is achieved by applying roles and state attributes to HTML 4.01 or later markup that has no bearing on layout or browser functionality, but provides additional information for assistive technologies.

One corner stone of WAI-ARIA is the role attribute. It tells the browser to tell the assistive technology that the HTML element used is not actually what the element name suggests, but something else. While it originally is only a div element, this div element may be the container to a list of auto-complete items, in which case a role of “listbox” would be appropriate to use. Likewise, another div that is a child of that container div, and which contains a single option item, should then get a role of “option”. Two divs, but through the roles, totally different meaning. The roles are modeled after commonly used desktop application counterparts.

An exception to this are document landmark roles, which don’t change the actual meaning of the element in question, but provide information about this particular place in a document.

The second corner stone are WAI-ARIA states and properties. They define the state of certain native or WAI-ARIA elements such as if something is collapsed or expanded, a form element is required, something has a popup menu attached to it or the like. These are often dynamic and change their values throughout the lifecycle of a web application, and are usually manipulated via JavaScript.

What is it not?

WAI-ARIA is not intended to influence browser behavior. Unlike a real button element, for example, a div which you pour the role of “button” onto does not give you keyboard focusability, an automatic click handler when Space or Enter are being pressed on it, and other properties that are indiginous to a button. The browser itself does not know that a div with role of “button” is a button, only its accessibility API portion does.

As a consequence, this means that you absolutely have to implement keyboard navigation, focusability and other behavioural patterns known from desktop applications yourself. You can find some Advanced ARIA techniques Here.

When should I not use it?

Yes, that’s correct, this section comes first! Because the first rule of using WAI-ARIA is: Don’t use it unless you absolutely have to! The less WAI-ARIA you have, and the more you can count on using native HTML widgets, the better! There are some more rules to follow, you can check them out here.

Jenkins / Hudson environment variables

Michael,

Two things:

When Jenkins connects to a computer, it goes to the sh shell, and not the bash shell (at least this is what I have noticed - I may be wrong). So any changes you make to $PATH in your bashrc file are not considered.

Also, any changes you make to $PATH in your local shell (one that you personally ssh into) will not show up in Jenkins.

To change the path that Jenkins uses, you have two options (AFAIK):

1) Edit your /etc/profile file and add the paths that you want there

2) Go to the configuration page of your slave, and add environment variable PATH, with value: $PATH:/followed-by/paths/you/want/to/add

If you use the second option, your System Information will still not show it, but your builds will see the added paths.

HashSet vs LinkedHashSet

LinkedHashSet's constructors invoke the following base class constructor:

HashSet(int initialCapacity, float loadFactor, boolean dummy) {
  map = new LinkedHashMap<E, Object>(initialCapacity, loadFactor);
}

As you can see, the internal map is a LinkedHashMap. If you look inside LinkedHashMap, you'll discover the following field:

private transient Entry<K, V> header;

This is the linked list in question.

What svn command would list all the files modified on a branch?

You can also get a quick list of changed files if thats all you're looking for using the status command with the -u option

svn status -u

This will show you what revision the file is in the current code base versus the latest revision in the repository. I only use diff when I actually want to see differences in the files themselves.

There is a good tutorial on svn command here that explains a lot of these common scenarios: SVN Command Reference

Removing duplicate elements from an array in Swift

Preserve unique values and preserve sorting in an array.

(using Swift 3)

    var top3score: [Int] = []


    outerLoop: for i in 0..<top10score.count {
        dlog(message: String(top10score[i]))

        if top3score.count == 3 {
            break
        }

        for aTop3score in top3score {
            if aTop3score == top10score[i] {
                continue outerLoop
            }
        }

        top3score.append(top10score[i])

    }

    print("top10score is \(top10score)")  //[14, 5, 5, 5, 3, 3, 2, 2, 2, 2]
    print("top3score is \(top3score)")   //[14, 5, 3]

CustomErrors mode="Off"

I have had the same problem, and I went through the Event viewer application log where it clearly mention due to which exception this is happened. In my case exception was as below...

Exception information :

Exception type: HttpException 
Exception message: The target principal name is incorrect.  Cannot generate SSPI context.
at System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app)
at System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers)
at System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context)
at System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context)
at System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext)

The target principal name is incorrect.  Cannot generate SSPI context.

I have just updated my password in application pool and it works for me.

Python Array with String Indices

What you want is called an associative array. In python these are called dictionaries.

Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys.

myDict = {}
myDict["john"] = "johns value"
myDict["jeff"] = "jeffs value"

Alternative way to create the above dict:

myDict = {"john": "johns value", "jeff": "jeffs value"}

Accessing values:

print(myDict["jeff"]) # => "jeffs value"

Getting the keys (in Python v2):

print(myDict.keys()) # => ["john", "jeff"]

In Python 3, you'll get a dict_keys, which is a view and a bit more efficient (see views docs and PEP 3106 for details).

print(myDict.keys()) # => dict_keys(['john', 'jeff']) 

If you want to learn about python dictionary internals, I recommend this ~25 min video presentation: https://www.youtube.com/watch?v=C4Kc8xzcA68. It's called the "The Mighty Dictionary".

Angular 4 HttpClient Query Parameters

You can (in version 5+) use the fromObject and fromString constructor parameters when creating HttpParamaters to make things a bit easier

    const params = new HttpParams({
      fromObject: {
        param1: 'value1',
        param2: 'value2',
      }
    });

    // http://localhost:3000/test?param1=value1&param2=value2

or:

    const params = new HttpParams({
      fromString: `param1=${var1}&param2=${var2}`
    });

    //http://localhost:3000/test?paramvalue1=1&param2=value2

Autocomplete syntax for HTML or PHP in Notepad++. Not auto-close, autocompelete

In Notepad++ v. 6.4.1 is this possibility in:Settings->Preferences->Auto-Completion and there check Enable auto-completion on each input.

For auto-complete in code press Ctrl + Enter.

Passing HTML to template using Flask/Jinja2

From the jinja docs section HTML Escaping:

When automatic escaping is enabled everything is escaped by default except for values explicitly marked as safe. Those can either be marked by the application or in the template by using the |safe filter.

Example:

 <div class="info">
   {{data.email_content|safe}}
 </div>

Calculate distance between two latitude-longitude points? (Haversine formula)

Here is a C# Implementation:

static class DistanceAlgorithm
{
    const double PIx = 3.141592653589793;
    const double RADIUS = 6378.16;

    /// <summary>
    /// Convert degrees to Radians
    /// </summary>
    /// <param name="x">Degrees</param>
    /// <returns>The equivalent in radians</returns>
    public static double Radians(double x)
    {
        return x * PIx / 180;
    }

    /// <summary>
    /// Calculate the distance between two places.
    /// </summary>
    /// <param name="lon1"></param>
    /// <param name="lat1"></param>
    /// <param name="lon2"></param>
    /// <param name="lat2"></param>
    /// <returns></returns>
    public static double DistanceBetweenPlaces(
        double lon1,
        double lat1,
        double lon2,
        double lat2)
    {
        double dlon = Radians(lon2 - lon1);
        double dlat = Radians(lat2 - lat1);

        double a = (Math.Sin(dlat / 2) * Math.Sin(dlat / 2)) + Math.Cos(Radians(lat1)) * Math.Cos(Radians(lat2)) * (Math.Sin(dlon / 2) * Math.Sin(dlon / 2));
        double angle = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
        return angle * RADIUS;
    }

}

iOS 7 status bar overlapping UI

For iPhoneX

For all the answers above :

The height of the status bar in the iPhoneX is 44 and not 20

How to convert text to binary code in JavaScript?

This might be the simplest you can get:

function text2Binary(string) {
    return string.split('').map(function (char) {
        return char.charCodeAt(0).toString(2);
    }).join(' ');
}

git clone: Authentication failed for <URL>

The culprit was russian account password.

Accidentally set up it (wrong keyboard layout). Everything was working, so didnt bother changing it.

Out of despair changed it now and it worked.

If someone looked up this thread and its not a solution for you - check out comments under the question and steps i described in question, they might be useful to you.

How to write MySQL query where A contains ( "a" or "b" )

I've used most of the times the LIKE option and it works just fine. I just like to share one of my latest experiences where I used INSTR function. Regardless of the reasons that made me consider this options, what's important here is that the use is similar: instr(A, 'text 1') > 0 or instr(A, 'text 2') > 0 Another option could be: (instr(A, 'text 1') + instr(A, 'text 2')) > 0

I'd go with the LIKE '%text1%' OR LIKE '%text2%' option... if not hope this other option helps

show/hide a div on hover and hover out

Here are different method of doing this. And i found your code is even working fine.

Your code: http://jsfiddle.net/NKC2j/

Jquery toggle class demo: http://jsfiddle.net/NKC2j/2/

Jquery fade toggle: http://jsfiddle.net/NKC2j/3/

Jquery slide toggle: http://jsfiddle.net/NKC2j/4/

And you can do this with CSS as answered by Sandeep

numpy: most efficient frequency counts for unique values in an array

from collections import Counter
x = array( [1,1,1,2,2,2,5,25,1,1] )
mode = counter.most_common(1)[0][0]

Manipulating an Access database from Java without ODBC

UCanAccess is a pure Java JDBC driver that allows us to read from and write to Access databases without using ODBC. It uses two other packages, Jackcess and HSQLDB, to perform these tasks. The following is a brief overview of how to get it set up.

 

Option 1: Using Maven

If your project uses Maven you can simply include UCanAccess via the following coordinates:

groupId: net.sf.ucanaccess
artifactId: ucanaccess

The following is an excerpt from pom.xml, you may need to update the <version> to get the most recent release:

  <dependencies>
    <dependency>
        <groupId>net.sf.ucanaccess</groupId>
        <artifactId>ucanaccess</artifactId>
        <version>4.0.4</version>
    </dependency>
  </dependencies>

 

Option 2: Manually adding the JARs to your project

As mentioned above, UCanAccess requires Jackcess and HSQLDB. Jackcess in turn has its own dependencies. So to use UCanAccess you will need to include the following components:

UCanAccess (ucanaccess-x.x.x.jar)
HSQLDB (hsqldb.jar, version 2.2.5 or newer)
Jackcess (jackcess-2.x.x.jar)
commons-lang (commons-lang-2.6.jar, or newer 2.x version)
commons-logging (commons-logging-1.1.1.jar, or newer 1.x version)

Fortunately, UCanAccess includes all of the required JAR files in its distribution file. When you unzip it you will see something like

ucanaccess-4.0.1.jar  
  /lib/
    commons-lang-2.6.jar  
    commons-logging-1.1.1.jar  
    hsqldb.jar  
    jackcess-2.1.6.jar

All you need to do is add all five (5) JARs to your project.

NOTE: Do not add loader/ucanload.jar to your build path if you are adding the other five (5) JAR files. The UcanloadDriver class is only used in special circumstances and requires a different setup. See the related answer here for details.

Eclipse: Right-click the project in Package Explorer and choose Build Path > Configure Build Path.... Click the "Add External JARs..." button to add each of the five (5) JARs. When you are finished your Java Build Path should look something like this

BuildPath.png

NetBeans: Expand the tree view for your project, right-click the "Libraries" folder and choose "Add JAR/Folder...", then browse to the JAR file.

nbAddJar.png

After adding all five (5) JAR files the "Libraries" folder should look something like this:

nbLibraries.png

IntelliJ IDEA: Choose File > Project Structure... from the main menu. In the "Libraries" pane click the "Add" (+) button and add the five (5) JAR files. Once that is done the project should look something like this:

IntelliJ.png

 

That's it!

Now "U Can Access" data in .accdb and .mdb files using code like this

// assumes...
//     import java.sql.*;
Connection conn=DriverManager.getConnection(
        "jdbc:ucanaccess://C:/__tmp/test/zzz.accdb");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT [LastName] FROM [Clients]");
while (rs.next()) {
    System.out.println(rs.getString(1));
}

 

Disclosure

At the time of writing this Q&A I had no involvement in or affiliation with the UCanAccess project; I just used it. I have since become a contributor to the project.

How to break out of jQuery each Loop

To break a $.each or $(selector).each loop, you have to return false in the loop callback.

Returning true skips to the next iteration, equivalent to a continue in a normal loop.

$.each(array, function(key, value) { 
    if(value === "foo") {
        return false; // breaks
    }
});

// or

$(selector).each(function() {
  if (condition) {
    return false;
  }
});

How to call Stored Procedure in Entity Framework 6 (Code-First)?

if you wanna pass table params into stored procedure, you must necessary set TypeName property for your table params.

SqlParameter codesParam = new SqlParameter(CODES_PARAM, SqlDbType.Structured);
            SqlParameter factoriesParam = new SqlParameter(FACTORIES_PARAM, SqlDbType.Structured);

            codesParam.Value = tbCodes;
            codesParam.TypeName = "[dbo].[MES_CodesType]";
            factoriesParam.Value = tbfactories;
            factoriesParam.TypeName = "[dbo].[MES_FactoriesType]";


            var list = _context.Database.SqlQuery<MESGoodsRemain>($"{SP_NAME} {CODES_PARAM}, {FACTORIES_PARAM}"
                , new SqlParameter[] {
                   codesParam,
                   factoriesParam
                }
                ).ToList();

In Excel, how do I extract last four letters of a ten letter string?

No need to use a macro. Supposing your first string is in A1.

=RIGHT(A1, 4)

Drag this down and you will get your four last characters.

Edit: To be sure, if you ever have sequences like 'ABC DEF' and want the last four LETTERS and not CHARACTERS you might want to use trimspaces()

=RIGHT(TRIMSPACES(A1), 4)

Edit: As per brettdj's suggestion, you may want to check that your string is actually 4-character long or more:

=IF(TRIMSPACES(A1)>=4, RIGHT(TRIMSPACES(A1), 4), TRIMSPACES(A1))

Number of days between past date and current date in Google spreadsheet

I used your idea, and found the difference and then just divided by 365 days. Worked a treat.

=MINUS(F2,TODAY())/365

Then I shifted my cell properties to not display decimals.

Component based game engine design

I am currently researching this exact topic in the many (MANY) threads at GameDev.net and found the following two solutions to be good candidates on what I will develop for my game:

React component initialize state from props

YOU HAVE TO BE CAREFUL when you initialize state from props in constructor. Even if props changed to new one, the state wouldn't be changed because mount never happen again. So getDerivedStateFromProps exists for that.

class FirstComponent extends React.Component {
    state = {
        description: ""
    };
    
    static getDerivedStateFromProps(nextProps, prevState) {
        if (prevState.description !== nextProps.description) {
          return { description: nextProps.description };
        }
    
        return null;
    }

    render() {
        const {state: {description}} = this;    

        return (
            <input type="text" value={description} /> 
        );
    }
}

Or use key props as a trigger to initialize:

class SecondComponent extends React.Component {
  state = {
    // initialize using props
  };
}
<SecondComponent key={something} ... />

In the code above, if something changed, then SecondComponent will re-mount as a new instance and state will be initialized by props.

SQL Server Management Studio missing

Did you include "Management Tools" as a chosen option during setup?

enter image description here

Ensure this option is selected, and SQL Server Management Studio will be installed on the machine.

Download file using libcurl in C/C++

The example you are using is wrong. See the man page for easy_setopt. In the example write_data uses its own FILE, *outfile, and not the fp that was specified in CURLOPT_WRITEDATA. That's why closing fp causes problems - it's not even opened.

This is more or less what it should look like (no libcurl available here to test)

#include <stdio.h>
#include <curl/curl.h>
/* For older cURL versions you will also need 
#include <curl/types.h>
#include <curl/easy.h>
*/
#include <string>

size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
    size_t written = fwrite(ptr, size, nmemb, stream);
    return written;
}

int main(void) {
    CURL *curl;
    FILE *fp;
    CURLcode res;
    char *url = "http://localhost/aaa.txt";
    char outfilename[FILENAME_MAX] = "C:\\bbb.txt";
    curl = curl_easy_init();
    if (curl) {
        fp = fopen(outfilename,"wb");
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        res = curl_easy_perform(curl);
        /* always cleanup */
        curl_easy_cleanup(curl);
        fclose(fp);
    }
    return 0;
}

Updated: as suggested by @rsethc types.h and easy.h aren't present in current cURL versions anymore.

Modify a Column's Type in sqlite3

It is possible by dumping, editing and reimporting the table.

This script will do it for you (Adapt the values at the start of the script to your needs):

#!/bin/bash

DB=/tmp/synapse/homeserver.db
TABLE="public_room_list_stream"
FIELD=visibility
OLD="BOOLEAN NOT NULL"
NEW="INTEGER NOT NULL"
TMP=/tmp/sqlite_$TABLE.sql

echo "### create dump"
echo ".dump '$TABLE'" | sqlite3 "$DB" >$TMP

echo "### editing the create statement"
sed -i "s|$FIELD $OLD|$FIELD $NEW|g" $TMP

read -rsp $'Press any key to continue deleting and recreating the table $TABLE ...\n' -n1 key 

echo "### rename the original to '$TABLE"_backup"'"
sqlite3 "$DB" "PRAGMA busy_timeout=20000; ALTER TABLE '$TABLE' RENAME TO '$TABLE"_backup"'"

echo "### delete the old indexes"
for idx in $(echo "SELECT name FROM sqlite_master WHERE type == 'index' AND tbl_name LIKE '$TABLE""%';" | sqlite3 $DB); do
  echo "DROP INDEX '$idx';" | sqlite3 $DB
done

echo "### reinserting the edited table"
cat $TMP | sqlite3 $DB

Easiest way to toggle 2 classes in jQuery

I've made a jQuery plugin for working DRY:

$.fn.toggle2classes = function(class1, class2){
  if( !class1 || !class2 )
    return this;

  return this.each(function(){
    var $elm = $(this);

    if( $elm.hasClass(class1) || $elm.hasClass(class2) )
      $elm.toggleClass(class1 +' '+ class2);

    else
      $elm.addClass(class1);
  });
};

You can just try it here, copy and run this in the console and then try:

$('body').toggle2classes('a', 'b');

Why should I use a container div in HTML?

THis method allows you to have more flexibility of styling your entire content. Effectivly creating two containers that you can style. THe HTML Body tag which serves as your background, and the div with an id of container which contains your content.

This then allows you to position your content within the page, while styling a background or other effects without issue. THink of it as a "Frame" for the content.

How do I convert a numpy array to (and display) an image?

this could be a possible code solution:

from skimage import io
import numpy as np
data=np.random.randn(5,2)
io.imshow(data)

How to find and restore a deleted file in a Git repository

You could always git revert your commit which deleted the file. (This assumes that the deletion was the only change in the commit.)

> git log
commit 2994bda49cd97ce49099953fc3f76f7d3c35d1d3
Author: Dave <[email protected]>
Date:   Thu May 9 11:11:06 2019 -0700

    deleted readme.md

And if you've continued work, and realized later that you didn't want to commit that deletion commit, you could revert it using:

> git revert 2994bd

Now git log shows:

> git log
Author: Dave <[email protected]>
Date:   Thu May 9 11:17:41 2019 -0700

    Revert "deleted readme"

    This reverts commit 2994bda49cd97ce49099953fc3f76f7d3c35d1d3.

And readme.md has been restored into the repository.

React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function

Step-1: Change the file name src/App.js to src/app.js

Step-2: Click on "Yes" for "Update imports for app.js".

Step-3: Restart the server again.

How to detect the physical connected state of a network cable/connector?

On the low level, these events can be caught using rtnetlink sockets, without any polling. Side note: if you use rtnetlink, you have to work together with udev, or your program may get confused when udev renames a new network interface.

The problem with doing network configurations with shell scripts is that shell scripts are terrible for event handling (such as a network cable being plugged in and out). If you need something more powerful, take a look at my NCD programming language, a programming language designed for network configurations.

For example, a simple NCD script that will print "cable in" and "cable out" to stdout (assuming the interface is already up):

process foo {
    # Wait for device to appear and be configured by udev.
    net.backend.waitdevice("eth0");
    # Wait for cable to be plugged in.
    net.backend.waitlink("eth0");
    # Print "cable in" when we reach this point, and "cable out"
    # when we regress.
    println("cable in");   # or pop_bubble("Network cable in.");
    rprintln("cable out"); # or rpop_bubble("Network cable out!");
                           # just joking, there's no pop_bubble() in NCD yet :)
}

(internally, net.backend.waitlink() uses rtnetlink, and net.backend.waitdevice() uses udev)

The idea of NCD is that you use it exclusively to configure the network, so normally, configuration commands would come in between, such as:

process foo {
    # Wait for device to appear and be configured by udev.
    net.backend.waitdevice("eth0");
    # Set device up.
    net.up("eth0");
    # Wait for cable to be plugged in.
    net.backend.waitlink("eth0");
    # Add IP address to device.
    net.ipv4.addr("eth0", "192.168.1.61", "24");
}

The important part to note is that execution is allowed to regress; in the second example, for instance, if the cable is pulled out, the IP address will automatically be removed.

"string could not resolved" error in Eclipse for C++ (Eclipse can't resolve standard library)

You need to ensure your environment is properly setup in Eclipse so it knows the paths to your includes. Otherwise, it underlines them as not found.

Heatmap in matplotlib with pcolor?

Someone edited this question to remove the code I used, so I was forced to add it as an answer. Thanks to all who participated in answering this question! I think most of the other answers are better than this code, I'm just leaving this here for reference purposes.

With thanks to Paul H, and unutbu (who answered this question), I have some pretty nice-looking output:

import matplotlib.pyplot as plt
import numpy as np
column_labels = list('ABCD')
row_labels = list('WXYZ')
data = np.random.rand(4,4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=plt.cm.Blues)

# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[0])+0.5, minor=False)
ax.set_yticks(np.arange(data.shape[1])+0.5, minor=False)

# want a more natural, table-like display
ax.invert_yaxis()
ax.xaxis.tick_top()

ax.set_xticklabels(row_labels, minor=False)
ax.set_yticklabels(column_labels, minor=False)
plt.show()

And here's the output:

Matplotlib HeatMap

Pass multiple values with onClick in HTML link

Please try this

for static values--onclick="return ReAssign('valuationId','user')"
for dynamic values--onclick="return ReAssign(valuationId,user)"

Why does 2 mod 4 = 2?

2 / 4 = 0 with a remainder of 2

Python dict how to create key or append an element to key?

Here are the various ways to do this so you can compare how it looks and choose what you like. I've ordered them in a way that I think is most "pythonic", and commented the pros and cons that might not be obvious at first glance:

Using collections.defaultdict:

import collections
dict_x = collections.defaultdict(list)

...

dict_x[key].append(value)

Pros: Probably best performance. Cons: Not available in Python 2.4.x.

Using dict().setdefault():

dict_x = {}

...

dict_x.setdefault(key, []).append(value)

Cons: Inefficient creation of unused list()s.

Using try ... except:

dict_x = {}

...

try:
    values = dict_x[key]
except KeyError:
    values = dict_x[key] = []
values.append(value)

Or:

try:
    dict_x[key].append(value)
except KeyError:
    dict_x[key] = [value]

Why should I use an IDE?

I'm not entirely sold on the use of IDEs. However, I think that the most valuable aspect of a good IDE, like Eclipse, is the well-integrated Cscope-style functionality rapid comprehension of a large code base.

For example, in Eclipse, you see a method takes an argument of type FooBar, yet you have no idea what it means. Rather than waste a minute finding the definition the hard way (and risk all sorts of distractions along the way), just select FooBar, hit F3, and it opens the relevant source file to the very line that FooBar is defined.

The downside of IDEs, in my opinion, is that they give you a bigger learning curve, except in the case in which you want to use the absolutely default configuration. (This is true for Emacs as well.)

Redis command to get all available keys?

If you are using Laravel Framework then you can simply use this:

$allKeyList = Redis::KEYS("*");

print_r($allKeyList);

In Core PHP:

$redis = new Redis();

$redis->connect('hostname', 6379);

$allKeyList = $redis->keys('*');

print_r($allKeyList);

Programmatically shut down Spring Boot application

This works, even done is printed.

  SpringApplication.run(MyApplication.class, args).close();
  System.out.println("done");

So adding .close() after run()

Explanation:

public ConfigurableApplicationContext run(String... args)

Run the Spring application, creating and refreshing a new ApplicationContext. Parameters:

args - the application arguments (usually passed from a Java main method)

Returns: a running ApplicationContext

and:

void close() Close this application context, releasing all resources and locks that the implementation might hold. This includes destroying all cached singleton beans. Note: Does not invoke close on a parent context; parent contexts have their own, independent lifecycle.

This method can be called multiple times without side effects: Subsequent close calls on an already closed context will be ignored.

So basically, it will not close the parent context, that's why the VM doesn't quit.

Compare string with all values in list

for word in d:
    if d in paid[j]:
         do_something()

will try all the words in the list d and check if they can be found in the string paid[j].

This is not very efficient since paid[j] has to be scanned again for each word in d. You could also use two sets, one composed of the words in the sentence, one of your list, and then look at the intersection of the sets.

sentence = "words don't come easy"
d = ["come", "together", "easy", "does", "it"]

s1 = set(sentence.split())
s2 = set(d)

print (s1.intersection(s2))

Output:

{'come', 'easy'}

What is this CSS selector? [class*="span"]

It's an attribute wildcard selector. In the sample you've given, it looks for any child element under .show-grid that has a class that CONTAINS span.

So would select the <strong> element in this example:

<div class="show-grid">
    <strong class="span6">Blah blah</strong>
</div>

You can also do searches for 'begins with...'

div[class^="something"] { }

which would work on something like this:-

<div class="something-else-class"></div>

and 'ends with...'

div[class$="something"] { }

which would work on

<div class="you-are-something"></div>

Good references

How to add new contacts in android

This is working fine for me:

ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
            int rawContactInsertIndex = ops.size();

            ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
                    .withValue(RawContacts.ACCOUNT_TYPE, null)
                    .withValue(RawContacts.ACCOUNT_NAME, null).build());
            ops.add(ContentProviderOperation
                    .newInsert(Data.CONTENT_URI)
                    .withValueBackReference(Data.RAW_CONTACT_ID,rawContactInsertIndex)
                    .withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
                    .withValue(StructuredName.DISPLAY_NAME, "Vikas Patidar") // Name of the person
                    .build());
            ops.add(ContentProviderOperation
                    .newInsert(Data.CONTENT_URI)
                    .withValueBackReference(
                            ContactsContract.Data.RAW_CONTACT_ID,   rawContactInsertIndex)
                    .withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
                    .withValue(Phone.NUMBER, "9999999999") // Number of the person
                    .withValue(Phone.TYPE, Phone.TYPE_MOBILE).build()); // Type of mobile number                    
            try
            {
                ContentProviderResult[] res = getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
            }
            catch (RemoteException e)
            { 
                // error
            }
            catch (OperationApplicationException e) 
            {
                // error
            }       

Awaiting multiple Tasks with different results

After you use WhenAll, you can pull the results out individually with await:

var catTask = FeedCat();
var houseTask = SellHouse();
var carTask = BuyCar();

await Task.WhenAll(catTask, houseTask, carTask);

var cat = await catTask;
var house = await houseTask;
var car = await carTask;

You can also use Task.Result (since you know by this point they have all completed successfully). However, I recommend using await because it's clearly correct, while Result can cause problems in other scenarios.

proper hibernate annotation for byte[]

I'm using the Hibernate 4.2.7.SP1 with Postgres 9.3 and following works for me:

@Entity
public class ConfigAttribute {
  @Lob
  public byte[] getValueBuffer() {
    return m_valueBuffer;
  }
}

as Oracle has no trouble with that, and for Postgres I'm using custom dialect:

public class PostgreSQLDialectCustom extends PostgreSQL82Dialect {

    @Override
    public SqlTypeDescriptor remapSqlTypeDescriptor(SqlTypeDescriptor sqlTypeDescriptor) {
    if (sqlTypeDescriptor.getSqlType() == java.sql.Types.BLOB) {
      return BinaryTypeDescriptor.INSTANCE;
    }
    return super.remapSqlTypeDescriptor(sqlTypeDescriptor);
  }
}

the advantage of this solution I consider, that I can keep hibernate jars untouched.

For more Postgres/Oracle compatibility issues with Hibernate, see my blog post.

How to see the actual Oracle SQL statement that is being executed

I had (have) a similar problem in a Java application. I wrote a JDBC driver wrapper around the Oracle driver so all output is sent to a log file.

Python None comparison: should I use "is" or ==?

PEP 8 defines that it is better to use the is operator when comparing singletons.

converting list to json format - quick and easy way

For me, it worked to use Newtonsoft.Json:

using Newtonsoft.Json;
// ...
var output = JsonConvert.SerializeObject(ListOfMyObject);

How do you make an anchor link non-clickable or disabled?

Write this a single line of jQuery Code

$('.hyperlink').css('pointer-events','none');

if you want to write in css file

.hyperlink{
    pointer-events: none;
}

ReferenceError: $ is not defined

It's one of the common mistake everybody make while working with jQuery, Basically $ is an alias of jQuery() so when you try to call/access it before declaring the function will endup throwing this error.

Reasons might be

1) Path to jQuery library you included is not correct.

2) Added library after the script were you see that error

To solve this

Load the jquery library beginning of all your javascript files/scripts.

<script src="https://code.jquery.com/jquery-3.3.1.js"></script>

node.js http 'get' request with query string parameters

Check out the request module.

It's more full featured than node's built-in http client.

var request = require('request');

var propertiesObject = { field1:'test1', field2:'test2' };

request({url:url, qs:propertiesObject}, function(err, response, body) {
  if(err) { console.log(err); return; }
  console.log("Get response: " + response.statusCode);
});

Laravel 5 – Clear Cache in Shared Hosting Server

Use the code below with the new clear cache commands: php artisan cache clear

//Clear route cache:
 Route::get('/route-cache', function() {
     // EDIT - the linked article uses route:cache, it should be route:clear
     // $exitCode = Artisan::call('route:cache');
     $exitCode = Artisan::call('route:clear');
     return 'Routes cache cleared';
 });

 //Clear config cache:
 Route::get('/config-cache', function() {
     $exitCode = Artisan::call('config:clear');
     return 'Config cache cleared';
 }); 

// Clear application cache:
 Route::get('/clear-cache', function() {
     $exitCode = Artisan::call('cache:clear');
     return 'Application cache cleared';
 });

 // Clear view cache:
 Route::get('/view-clear', function() {
     $exitCode = Artisan::call('view:clear');
     return 'View cache cleared';
 });

Jquery checking success of ajax post

If you need a failure function, you can't use the $.get or $.post functions; you will need to call the $.ajax function directly. You pass an options object that can have "success" and "error" callbacks.

Instead of this:

$.post("/post/url.php", parameters, successFunction);

you would use this:

$.ajax({
    url: "/post/url.php",
    type: "POST",
    data: parameters,
    success: successFunction,
    error: errorFunction
});

There are lots of other options available too. The documentation lists all the options available.

Group by multiple field names in java 8

The groupingBy method has the first parameter is Function<T,K> where:

@param <T> the type of the input elements

@param <K> the type of the keys

If we replace lambda with the anonymous class in your code, we can see some kind of that:

people.stream().collect(Collectors.groupingBy(new Function<Person, int>() {
            @Override
            public int apply(Person person) {
                return person.getAge();
            }
        }));

Just now change output parameter<K>. In this case, for example, I used a pair class from org.apache.commons.lang3.tuple for grouping by name and age, but you may create your own class for filtering groups as you need.

people.stream().collect(Collectors.groupingBy(new Function<Person, Pair<Integer, String>>() {
                @Override
                public YourFilter apply(Person person) {
                    return Pair.of(person.getAge(), person.getName());
                }
            }));

Finally, after replacing with lambda back, code looks like that:

Map<Pair<Integer,String>, List<Person>> peopleByAgeAndName = people.collect(Collectors.groupingBy(p -> Pair.of(person.getAge(), person.getName()), Collectors.mapping((Person p) -> p, toList())));

Python JSON serialize a Decimal object

Based on stdOrgnlDave answer I have defined this wrapper that it can be called with optional kinds so the encoder will work only for certain kinds inside your projects. I believe the work should be done inside your code and not to use this "default" encoder since "it is better explicit than implicit", but I understand using this will save some of your time. :-)

import time
import json
import decimal
from uuid import UUID
from datetime import datetime

def JSONEncoder_newdefault(kind=['uuid', 'datetime', 'time', 'decimal']):
    '''
    JSON Encoder newdfeault is a wrapper capable of encoding several kinds
    Use it anywhere on your code to make the full system to work with this defaults:
        JSONEncoder_newdefault()  # for everything
        JSONEncoder_newdefault(['decimal'])  # only for Decimal
    '''
    JSONEncoder_olddefault = json.JSONEncoder.default

    def JSONEncoder_wrapped(self, o):
        '''
        json.JSONEncoder.default = JSONEncoder_newdefault
        '''
        if ('uuid' in kind) and isinstance(o, uuid.UUID):
            return str(o)
        if ('datetime' in kind) and isinstance(o, datetime):
            return str(o)
        if ('time' in kind) and isinstance(o, time.struct_time):
            return datetime.fromtimestamp(time.mktime(o))
        if ('decimal' in kind) and isinstance(o, decimal.Decimal):
            return str(o)
        return JSONEncoder_olddefault(self, o)
    json.JSONEncoder.default = JSONEncoder_wrapped

# Example
if __name__ == '__main__':
    JSONEncoder_newdefault()

c# open file with default application and parameters

Please add Settings under Properties for the Project and make use of them this way you have clean and easy configurable settings that can be configured as default

How To: Create a New Setting at Design Time

Update: after comments below

  1. Right + Click on project
  2. Add New Item
  3. Under Visual C# Items -> General
  4. Select Settings File

Wait .5 seconds before continuing code VB.net

In web application a timer will be the best approach.

Just fyi, in desktop application I use this instead, inside an async method.

... 
Await Task.Run(Sub()
    System.Threading.Thread.Sleep(5000)
End Sub)
...

It work for me, importantly it doesn't freeze entire screen. But again this is on desktop, i try in web application it does freeze.

Styling HTML5 input type number

Unfortunately in HTML 5 the 'pattern' attribute is linked to only 4-5 attributes. However if you are willing to use a "text" field instead and convert to number later, this might help you;

This limits an input from 1 character (numberic) to 3.

<input name=quantity type=text pattern='[0-9]{1,3}'>

The CSS basically allows for confirmation with an "Thumbs up" or "Down".

Example 1

Example 2

Converting String Array to an Integer Array

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

class MultiArg {

    Scanner sc;
    int n;
    String as;
    List<Integer> numList = new ArrayList<Integer>();

    public void fun() {
        sc = new Scanner(System.in);
        System.out.println("enter value");
        while (sc.hasNextInt())
            as = sc.nextLine();
    }

    public void diplay() {
        System.out.println("x");
        Integer[] num = numList.toArray(new Integer[numList.size()]);
        System.out.println("show value " + as);
        for (Integer m : num) {
            System.out.println("\t" + m);
        }
    }
}

but to terminate the while loop you have to put any charecter at the end of input.

ex. input:

12 34 56 78 45 67 .

output:

12 34 56 78 45 67

How to use executeReader() method to retrieve the value of just one cell

It is not recommended to use DataReader and Command.ExecuteReader to get just one value from the database. Instead, you should use Command.ExecuteScalar as following:

String sql = "SELECT ColumnNumber FROM learer WHERE learer.id = " + index;
SqlCommand cmd = new SqlCommand(sql,conn);
learerLabel.Text = (String) cmd.ExecuteScalar();

Here is more information about Connecting to database and managing data.

Postgresql Windows, is there a default password?

Try this:

Open PgAdmin -> Files -> Open pgpass.conf

You would get the path of pgpass.conf at the bottom of the window. Go to that location and open this file, you can find your password there.

Reference

If the above does not work, you may consider trying this:

 1. edit pg_hba.conf to allow trust authorization temporarily
 2. Reload the config file (pg_ctl reload)
 3. Connect and issue ALTER ROLE / PASSWORD to set the new password
 4. edit pg_hba.conf again and restore the previous settings
 5. Reload the config file again

Cast received object to a List<object> or IEnumerable<object>

This Code worked for me

List<Object> collection = new List<Object>((IEnumerable<Object>)myObject);

ASP.NET MVC: What is the purpose of @section?

It lets you define a @Section of code in your template that you can then include in other files. For example, a sidebar defined in the template, could be referenced in another included view.

//This could be used to render a @Section defined as @Section SideBar { ...
@RenderSection("SideBar", required: false);

Hope this helps.

How can I create a progress bar in Excel VBA?

I'm loving all the solutions posted here, but I solved this using Conditional Formatting as a percentage-based Data Bar.

Conditional Formatting

This is applied to a row of cells as shown below. The cells that include 0% and 100% are normally hidden, because they're just there to give the "ScanProgress" named range (Left) context.

Scan progress

In the code I'm looping through a table doing some stuff.

For intRow = 1 To shData.Range("tblData").Rows.Count

    shData.Range("ScanProgress").Value = intRow / shData.Range("tblData").Rows.Count
    DoEvents

    ' Other processing

Next intRow

Minimal code, looks decent.

What are the rules for calling the superclass constructor?

The only way to pass values to a parent constructor is through an initialization list. The initilization list is implemented with a : and then a list of classes and the values to be passed to that classes constructor.

Class2::Class2(string id) : Class1(id) {
....
}

Also remember that if you have a constructor that takes no parameters on the parent class, it will be called automatically prior to the child constructor executing.

How to get a barplot with several variables side by side grouped by a factor

You can plot the means without resorting to external calculations and additional tables using stat_summary(...). In fact, stat_summary(...) was designed for exactly what you are doing.

library(ggplot2)
library(reshape2)            # for melt(...)
gg <- melt(df,id="gender")   # df is your original table
ggplot(gg, aes(x=variable, y=value, fill=factor(gender))) + 
  stat_summary(fun.y=mean, geom="bar",position=position_dodge(1)) + 
  scale_color_discrete("Gender")
  stat_summary(fun.ymin=min,fun.ymax=max,geom="errorbar",
               color="grey80",position=position_dodge(1), width=.2)

To add "error bars" you cna also use stat_summary(...) (here, I'm using the min and max value rather than sd because you have so little data).

ggplot(gg, aes(x=variable, y=value, fill=factor(gender))) + 
  stat_summary(fun.y=mean, geom="bar",position=position_dodge(1)) + 
  stat_summary(fun.ymin=min,fun.ymax=max,geom="errorbar",
               color="grey40",position=position_dodge(1), width=.2) +
  scale_fill_discrete("Gender")

High CPU Utilization in java application - why?

You did not assign the "linux" to the question but you mentioned "Linux top". And thus this might be helpful:

Use the small Linux tool threadcpu to identify the most cpu using threads. It calls jstack to get the thread name. And with "sort -n" in pipe you get the list of threads ordered by cpu usage.

More details can be found here: http://www.tuxad.com/blog/archives/2018/10/01/threadcpu_-_show_cpu_usage_of_threads/index.html

And if you still need more details then create a thread dump or run strace on the thread.

showing that a date is greater than current date

For those that want a nice conditional:

DECLARE @MyDate DATETIME  = 'some date in future' --example  DateAdd(day,5,GetDate())

IF @MyDate < DATEADD(DAY,1,GETDATE())
    BEGIN
        PRINT 'Date NOT greater than today...'
END
ELSE 
    BEGIN
       PRINT 'Date greater than today...'
END 

How do I get the file extension of a file in Java?

Do you really need a "parser" for this?

String extension = "";

int i = fileName.lastIndexOf('.');
if (i > 0) {
    extension = fileName.substring(i+1);
}

Assuming that you're dealing with simple Windows-like file names, not something like archive.tar.gz.

Btw, for the case that a directory may have a '.', but the filename itself doesn't (like /path/to.a/file), you can do

String extension = "";

int i = fileName.lastIndexOf('.');
int p = Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\'));

if (i > p) {
    extension = fileName.substring(i+1);
}

nginx- duplicate default server error

In my case junk files from editor caused the problem. I had a config as below:

#...
http {
 # ...
 include ../sites/*;
}

In the ../sites directory initially I had a default.config file. However, by mistake I saved duplicate files as default.config.save and default.config.save.1. Removing them resolved the issue.

Insert into C# with SQLCommand

Try confirm the data type (SqlDbType) for each parameter in the database and do it this way;

 using(SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["connSpionshopString"].ConnectionString))
 {
            connection.Open();
            string sql =  "INSERT INTO klant(klant_id,naam,voornaam) VALUES(@param1,@param2,@param3)";
            using(SqlCommand cmd = new SqlCommand(sql,connection)) 
            {
                  cmd.Parameters.Add("@param1", SqlDbType.Int).value = klantId;  
                  cmd.Parameters.Add("@param2", SqlDbType.Varchar, 50).value = klantNaam;
                  cmd.Parameters.Add("@param3", SqlDbType.Varchar, 50).value = klantVoornaam;
                  cmd.CommandType = CommandType.Text;
                  cmd.ExecuteNonQuery(); 
            }
 }

How to fix: "You need to use a Theme.AppCompat theme (or descendant) with this activity"

Your application has an AppCompat theme

<application
    android:theme="@style/AppTheme">

But, you overwrote the Activity (which extends AppCompatActivity) with a theme that isn't descendant of an AppCompat theme

<activity android:name=".MainActivity"
    android:theme="@android:style/Theme.NoTitleBar.Fullscreen" >

You could define your own fullscreen theme like so (notice AppCompat in the parent=)

<style name="AppFullScreenTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowActionBar">false</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowContentOverlay">@null</item>
</style>

Then set that on the Activity.

<activity android:name=".MainActivity"
    android:theme="@style/AppFullScreenTheme" >

Note: There might be an AppCompat theme that's already full screen, but don't know immediately

'node' is not recognized as an internal or an external command, operable program or batch file while using phonegap/cordova

Be aware that the Path is case sensitive. I tried setx PATH and it didn't work. In my case it was setx Path. Make sure your CMD run as Administrator.

setx Path "%PATH%;C:\Program Files\nodejs"

Now just restart your command prompt (or restart the PC) and the node command should be available.

Launch custom android application from android browser

All above answers didn't work for me with CHROME as of 28 Jan 2014

my App launched properly from http://example.com/someresource/ links from apps like hangouts, gmail etc but not from within chrome browser.

to solve this, so that it launches properly from CHROME you have to set intent filter like this

<intent-filter>
    <action android:name="android.intent.action.VIEW" />

    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />

    <data
        android:host="example.com"
        android:pathPrefix="/someresource/"
        android:scheme="http" />
    <data
        android:host="www.example.com"
        android:pathPrefix="/someresource/"
        android:scheme="http" />
</intent-filter>

note the pathPrefix element

your app will now appear inside activity picker whenever user requests http://example.com/someresource/ pattern from chrome browser by clicking a link from google search results or any other website

iOS: Multi-line UILabel in Auto Layout

I find you need the following:

  • A top constraint
  • A leading constraint (eg left side)
  • A trailing constraint (eg right side)
  • Set content hugging priority, horizontal to low, so it'll fill the given space if the text is short.
  • Set content compression resistance, horizontal to low, so it'll wrap instead of try to become wider.
  • Set the number of lines to 0.
  • Set the line break mode to word wrap.

Get visible items in RecyclerView

First / last visible child depends on the LayoutManager. If you are using LinearLayoutManager or GridLayoutManager, you can use

int findFirstVisibleItemPosition();
int findFirstCompletelyVisibleItemPosition();
int findLastVisibleItemPosition();
int findLastCompletelyVisibleItemPosition();

For example:

GridLayoutManager layoutManager = ((GridLayoutManager)mRecyclerView.getLayoutManager());
int firstVisiblePosition = layoutManager.findFirstVisibleItemPosition();

For LinearLayoutManager, first/last depends on the adapter ordering. Don't query children from RecyclerView; LayoutManager may prefer to layout more items than visible for caching.

Add a linebreak in an HTML text area

I believe this will work:

TextArea.Text = "Line 1" & vbCrLf & "Line 2"

System.Environment.NewLine could be used in place of vbCrLf if you wanted to be a little less VB6 about it.

How to run a .jar in mac?

Make Executable your jar and after that double click on it on Mac OS then it works successfully.

sudo chmod +x filename.jar

Try this, I hope this works.

What does -XX:MaxPermSize do?

In Java 8 that parameter is commonly used to print a warning message like this one:

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=512m; support was removed in 8.0

The reason why you get this message in Java 8 is because Permgen has been replaced by Metaspace to address some of PermGen's drawbacks (as you were able to see for yourself, one of those drawbacks is that it had a fixed size).

FYI: an article on Metaspace: http://java-latte.blogspot.in/2014/03/metaspace-in-java-8.html

'Found the synthetic property @panelState. Please include either "BrowserAnimationsModule" or "NoopAnimationsModule" in your application.'

My problem was that my @angular/platform-browser was on version 2.3.1

npm install @angular/platform-browser@latest --save

Upgrading to 4.4.6 did the trick and added /animations folder under node_modules/@angular/platform-browser

C++ delete vector, objects, free memory

vector::clear() does not free memory allocated by the vector to store objects; it calls destructors for the objects it holds.

For example, if the vector uses an array as a backing store and currently contains 10 elements, then calling clear() will call the destructor of each object in the array, but the backing array will not be deallocated, so there is still sizeof(T) * 10 bytes allocated to the vector (at least). size() will be 0, but size() returns the number of elements in the vector, not necessarily the size of the backing store.

As for your second question, anything you allocate with new you must deallocate with delete. You typically do not maintain a pointer to a vector for this reason. There is rarely (if ever) a good reason to do this and you prevent the vector from being cleaned up when it leaves scope. However, calling clear() will still act the same way regardless of how it was allocated.

Exclude property from type

If you prefer to use a library, use ts-essentials.

import { Omit } from "ts-essentials";

type ComplexObject = {
  simple: number;
  nested: {
    a: string;
    array: [{ bar: number }];
  };
};

type SimplifiedComplexObject = Omit<ComplexObject, "nested">;

// Result:
// {
//  simple: number
// }

// if you want to Omit multiple properties just use union type:
type SimplifiedComplexObject = Omit<ComplexObject, "nested" | "simple">;

// Result:
// { } (empty type)

PS: You will find lots of other useful stuff there ;)

Chrome DevTools Devices does not detect device when plugged in

Just adding this here for reference, I was trying to connect an LG G5 Android phone and Chrome dev tools did not recognize it until I downloaded the LG usb driver here.

Good luck, all!

Merge two array of objects based on a key

You could use an arbitrary count of arrays and map on the same index new objects.

_x000D_
_x000D_
var array1 = [{ id: "abdc4051", date: "2017-01-24" }, { id: "abdc4052", date: "2017-01-22" }],_x000D_
    array2 = [{ id: "abdc4051", name: "ab" }, { id: "abdc4052", name: "abc" }],_x000D_
    result = [array1, array2].reduce((a, b) => a.map((c, i) => Object.assign({}, c, b[i])));_x000D_
    _x000D_
console.log(result);
_x000D_
.as-console-wrapper { max-height: 100% !important; top: 0; }
_x000D_
_x000D_
_x000D_

Docker is in volume in use, but there aren't any Docker containers

Perhaps the volume was created via docker-compose? If so, it should get removed by:

docker-compose down --volumes

Credit to Niels Bech Nielsen!

How to scale Docker containers in production

While we're big fans of Deis (deis.io) and are actively deploying to it, there are other Heroku like PaaS style deployment solutions out there, including:

Longshoreman from the Wayfinder folks:

https://github.com/longshoreman/longshoreman

Decker from the CloudCredo folks, using CloudFoundry:

http://www.cloudcredo.com/decker-docker-cloud-foundry/

As for straight up orchestration, NewRelic's opensource Centurion project seems quite promising:

https://github.com/newrelic/centurion

Android Studio Emulator and "Process finished with exit code 0"

I solved this issue by offing all of advantage features of my graphics card in its settings(Nvidaa type). It started to throw such hanging error less a lot. But finally I found a simplier way: In avd manager you need to put less resolution for the avd. Say, 400x800. Then I reenabled graphics card features again and now it runs all ok. (I suspect my graphics card or cpu are weaker than needed. )

jQuery Set Select Index

Shortly:

$("#selectBox").attr("selectedIndex",index)

where index is the selected index as integer.

JDBC ResultSet: I need a getDateTime, but there is only getDate and getTimeStamp

this worked:

    Date date = null;
    String dateStr = rs.getString("doc_date");
    if (dateStr != null) {
        date = dateFormat.parse(dateStr);
    }

using SimpleDateFormat.

TypeError: document.getElementbyId is not a function

JavaScript is case-sensitive. The b in getElementbyId should be capitalized.

var content = document.getElementById("edit").innerHTML;

Clear History and Reload Page on Login/Logout Using Ionic Framework

None of the solutions mentioned above worked for a hostname that is different from localhost!

I had to add notify: false to the list of options that I pass to $state.go, to avoid calling Angular change listeners, before $window.location.reload call gets called. Final code looks like:

$state.go('home', {}, {reload: true, notify: false});

>>> EDIT - $timeout might be necessary depending on your browser >>>

$timeout(function () { $window.location.reload(true); }, 100);

<<< END OF EDIT <<<

More about this on ui-router reference.

Python MYSQL update statement

You've got the syntax all wrong:

cursor.execute ("""
   UPDATE tblTableName
   SET Year=%s, Month=%s, Day=%s, Hour=%s, Minute=%s
   WHERE Server=%s
""", (Year, Month, Day, Hour, Minute, ServerID))

For more, read the documentation.

How to get response using cURL in PHP

Just use the below piece of code to get the response from restful web service url, I use social mention url.

$response = get_web_page("http://socialmention.com/search?q=iphone+apps&f=json&t=microblogs&lang=fr");
$resArr = array();
$resArr = json_decode($response);
echo "<pre>"; print_r($resArr); echo "</pre>";

function get_web_page($url) {
    $options = array(
        CURLOPT_RETURNTRANSFER => true,   // return web page
        CURLOPT_HEADER         => false,  // don't return headers
        CURLOPT_FOLLOWLOCATION => true,   // follow redirects
        CURLOPT_MAXREDIRS      => 10,     // stop after 10 redirects
        CURLOPT_ENCODING       => "",     // handle compressed
        CURLOPT_USERAGENT      => "test", // name of client
        CURLOPT_AUTOREFERER    => true,   // set referrer on redirect
        CURLOPT_CONNECTTIMEOUT => 120,    // time-out on connect
        CURLOPT_TIMEOUT        => 120,    // time-out on response
    ); 

    $ch = curl_init($url);
    curl_setopt_array($ch, $options);

    $content  = curl_exec($ch);

    curl_close($ch);

    return $content;
}

Tomcat Server Error - Port 8080 already in use

I would suggest to end java.exe or javaw.exe process from task manager and try again. This will not end the entire eclipse application but will free the port.

Using the "With Clause" SQL Server 2008

Try the sp_foreachdb procedure.

C# : changing listbox row color?

Once you've added your listbox item to your form, change DrawMode with OwnerDrawFixed option from the Properties panel. If you forget to do this, none of the codes below will work. Then click DrawItem event from the Events area.

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
   // 1. Get the item
   string selectedItem = listBox1.Items[e.Index].ToString();
                    
   // 2. Choose font 
   Font font = new Font("Arial", 12);
        
   // 3. Choose colour
   SolidBrush solidBrush = new SolidBrush(Color.Red);
        
   // 4. Get bounds
   int left = e.Bounds.Left;
   int top = e.Bounds.Top;
                    
   // 5. Use Draw the background within the bounds
   e.DrawBackground();
        
   // 6. Colorize listbox items
   e.Graphics.DrawString(selectedItem, font, solidBrush, left, top);
}

Get commit list between tags in git

If your team uses descriptive commit messages (eg. "Ticket #12345 - Update dependencies") on this project, then generating changelog since the latest tag can de done like this:

git log --no-merges --pretty=format:"%s" 'old-tag^'...new-tag > /path/to/changelog.md
  • --no-merges omits the merge commits from the list
  • old-tag^ refers to the previous commit earlier than the tagged one. Useful if you want to see the tagged commit at the bottom of the list by any reason. (Single quotes needed only for iTerm on mac OS).

Determine if $.ajax error is a timeout

If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.

Per the jQuery documentation:

Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".

You can handle your error accordingly then.

I created this fiddle that demonstrates this.

$.ajax({
    url: "/ajax_json_echo/",
    type: "GET",
    dataType: "json",
    timeout: 1000,
    success: function(response) { alert(response); },
    error: function(xmlhttprequest, textstatus, message) {
        if(textstatus==="timeout") {
            alert("got timeout");
        } else {
            alert(textstatus);
        }
    }
});?

With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.

Hope this helps!

C free(): invalid pointer

From where did you get the idea that you need to free(token) and free(tk)? You don't. strsep() doesn't allocate memory, it only returns pointers inside the original string. Of course, those are not pointers allocated by malloc() (or similar), so free()ing them is undefined behavior. You only need to free(s) when you are done with the entire string.

Also note that you don't need dynamic memory allocation at all in your example. You can avoid strdup() and free() altogether by simply writing char *s = p;.

How to get the primary IP address of the local machine on Linux and OS X?

on Linux

hostname -I

on macOS

ipconfig getifaddr en0

hostname -I can return multiple addresses in an unreliable order (see the hostname manpage), but for me it just returns 192.168.1.X, which is what you wanted.

Invoking a PHP script from a MySQL trigger

The trigger is executed on the MySQL server, not on the PHP one (even if those are both on the same machine).

So, I would say this is not quite possible -- at least not simply.


Still, considering this entry from the MySQL FAQ on Triggers :

23.5.11: Can triggers call an external application through a UDF?

Yes. For example, a trigger could invoke the sys_exec() UDF available here: https://github.com/mysqludf/lib_mysqludf_sys#readme

So, there might be a way via an UDF function that would launch the php executable/script. Not that easy, but seems possible. ;-)

Android Studio update -Error:Could not run build action using Gradle distribution

You can download the gradle you want from Gradle Service by reading the gradle-wrapper.properties.Download it ,unpack it where you like and then change your grandle configuration use local not the recommended.

How to check if a Unix .tar.gz file is a valid file without uncompressing?

> use the -O option. [...] If the tar file is corrupt, the process will abort with an error.

Sometimes yes, but sometimes not. Let's see an example of a corrupted file:

echo Pete > my_name
tar -cf my_data.tar my_name 

# // Simulate a corruption
sed < my_data.tar 's/Pete/Fool/' > my_data_now.tar
# // "my_data_now.tar" is the corrupted file

tar -xvf my_data_now.tar -O

It shows:

my_name
Fool  

Even if you execute

echo $?

tar said that there was no error:

0

but the file was corrupted, it has now "Fool" instead of "Pete".

Difference between variable declaration syntaxes in Javascript (including global variables)?

Bassed on the excellent answer of T.J. Crowder: (Off-topic: Avoid cluttering window)

This is an example of his idea:

Html

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="init.js"></script>
    <script type="text/javascript">
      MYLIBRARY.init(["firstValue", 2, "thirdValue"]);
    </script>
    <script src="script.js"></script>
  </head>

  <body>
    <h1>Hello !</h1>
  </body>    
</html>

init.js (Based on this answer)

var MYLIBRARY = MYLIBRARY || (function(){
    var _args = {}; // private

    return {
        init : function(Args) {
            _args = Args;
            // some other initialising
        },
        helloWorld : function(i) {
            return _args[i];
        }
    };
}());

script.js

// Here you can use the values defined in the html as if it were a global variable
var a = "Hello World " + MYLIBRARY.helloWorld(2);

alert(a);

Here's the plnkr. Hope it help !

How to check a radio button with jQuery?

Try This:

$(document).ready(function(){
  $("#Id").prop("checked", true).checkboxradio('refresh');
});

How to use UIVisualEffectView to Blur Image?

Here is how to use UIVibrancyEffect and UIBlurEffect with UIVisualEffectView

Objective-C:

// Blur effect
UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
UIVisualEffectView *blurEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
[blurEffectView setFrame:self.view.bounds];
[self.view addSubview:blurEffectView];

// Vibrancy effect
UIVibrancyEffect *vibrancyEffect = [UIVibrancyEffect effectForBlurEffect:blurEffect];
UIVisualEffectView *vibrancyEffectView = [[UIVisualEffectView alloc] initWithEffect:vibrancyEffect];
[vibrancyEffectView setFrame:self.view.bounds];

// Label for vibrant text
UILabel *vibrantLabel = [[UILabel alloc] init];
[vibrantLabel setText:@"Vibrant"];
[vibrantLabel setFont:[UIFont systemFontOfSize:72.0f]];
[vibrantLabel sizeToFit];
[vibrantLabel setCenter: self.view.center];

// Add label to the vibrancy view
[[vibrancyEffectView contentView] addSubview:vibrantLabel];

// Add the vibrancy view to the blur view
[[blurEffectView contentView] addSubview:vibrancyEffectView];

Swift 4:

    // Blur Effect
    let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark)
    let blurEffectView = UIVisualEffectView(effect: blurEffect)
    blurEffectView.frame = view.bounds
    view.addSubview(blurEffectView)

    // Vibrancy Effect
    let vibrancyEffect = UIVibrancyEffect(blurEffect: blurEffect)
    let vibrancyEffectView = UIVisualEffectView(effect: vibrancyEffect)
    vibrancyEffectView.frame = view.bounds

    // Label for vibrant text
    let vibrantLabel = UILabel()
    vibrantLabel.text = "Vibrant"
    vibrantLabel.font = UIFont.systemFont(ofSize: 72.0)
    vibrantLabel.sizeToFit()
    vibrantLabel.center = view.center

    // Add label to the vibrancy view
    vibrancyEffectView.contentView.addSubview(vibrantLabel)

    // Add the vibrancy view to the blur view
    blurEffectView.contentView.addSubview(vibrancyEffectView)

is there something like isset of php in javascript/jQuery?

Here :)

function isSet(iVal){
 return (iVal!=="" && iVal!=null && iVal!==undefined && typeof(iVal) != "undefined") ? 1 : 0;
} // Returns 1 if set, 0 false

How change List<T> data to IQueryable<T> data

var list = new List<string>();
var queryable = list.AsQueryable();

Add a reference to: System.Linq

How do you properly determine the current script directory?

Here is a partial solution, still better than all published ones so far.

import sys, os, os.path, inspect

#os.chdir("..")

if '__file__' not in locals():
    __file__ = inspect.getframeinfo(inspect.currentframe())[0]

print os.path.dirname(os.path.abspath(__file__))

Now this works will all calls but if someone use chdir() to change the current directory, this will also fail.

Notes:

  • sys.argv[0] is not going to work, will return -c if you execute the script with python -c "execfile('path-tester.py')"
  • I published a complete test at https://gist.github.com/1385555 and you are welcome to improve it.

Proper way to initialize a C# dictionary with values?

Object initializers were introduced in C# 3.0, check which framework version you are targeting.

Overview of C# 3.0

Gradle: Could not determine java version from '11.0.2'

Getting this error when doing a cordova build android --release

I was able to resolve this, after trying so so many different things, by simply doing :

npm install cordova -g   # to upgrade to version 10.0.0

cordova platform rm android
cordova platform add android    # to upgrade to android version 9.0.0

How to find the php.ini file used by the command line?

The easiest way nowadays is to use PHP configure:

# php-config --ini-dir
/usr/local/etc/php/7.4/conf.d

There's more you can find there. Example output of the --help sub command (macOS local install):

# php-config --help
Usage: /usr/local/bin/php-config [OPTION]
Options:
  --prefixUsage: /usr/local/bin/php-config [OPTION]
Options:
  --prefix            [/usr/local/Cellar/php/7.4.11]
  --includes          [-I/usr/local/Cellar/php/7.4.11/include/php - …ETC…]
  --ldflags           [ -L/usr/local/Cellar/krb5/1.18.2/lib -…ETC…]
  --libs              [ -ltidy -largon2 …ETC… ]
  --extension-dir     [/usr/local/Cellar/php/7.4.11/pecl/20190902]
  --include-dir       [/usr/local/Cellar/php/7.4.11/include/php]
  --man-dir           [/usr/local/Cellar/php/7.4.11/share/man]
  --php-binary        [/usr/local/Cellar/php/7.4.11/bin/php]
  --php-sapis         [ apache2handler cli fpm phpdbg cgi]
  --ini-path          [/usr/local/etc/php/7.4]
  --ini-dir           [/usr/local/etc/php/7.4/conf.d]
  --configure-options [--prefix=/usr/local/Cellar/php/7.4.11 --…ETC…]
  --version           [7.4.11]
  --vernum            [70411]

How do I force Postgres to use a particular index?

Assuming you're asking about the common "index hinting" feature found in many databases, PostgreSQL doesn't provide such a feature. This was a conscious decision made by the PostgreSQL team. A good overview of why and what you can do instead can be found here. The reasons are basically that it's a performance hack that tends to cause more problems later down the line as your data changes, whereas PostgreSQL's optimizer can re-evaluate the plan based on the statistics. In other words, what might be a good query plan today probably won't be a good query plan for all time, and index hints force a particular query plan for all time.

As a very blunt hammer, useful for testing, you can use the enable_seqscan and enable_indexscan parameters. See:

These are not suitable for ongoing production use. If you have issues with query plan choice, you should see the documentation for tracking down query performance issues. Don't just set enable_ params and walk away.

Unless you have a very good reason for using the index, Postgres may be making the correct choice. Why?

  • For small tables, it's faster to do sequential scans.
  • Postgres doesn't use indexes when datatypes don't match properly, you may need to include appropriate casts.
  • Your planner settings might be causing problems.

See also this old newsgroup post.

Bootstrap 3 dropdown select

;(function ($) {
    $.fn.bootselect = function (options) {
        this.each(function () {
            var os = jQuery(this).find('option');
            var parent = this.parentElement;
            var css = jQuery(this).attr('class').split('input').join('btn').split('form-control').join('');
            var vHtml = jQuery(this).find('option[value="' + jQuery(this).val() + '"]').html();
            var html = '<div class="btn-group" role="group">' + '<button type="button" data-toggle="dropdown" value="1" class="btn btn-default ' + css + ' dropdown-toggle">' +
                vHtml + '<span class="caret"></span>' + '</button>' + '<ul class="dropdown-menu">';
            var i = 0;
            while (i < os.length) {
                html += '<li><a href="#" data-value="' + jQuery(os[i]).val() + '" html-attr="' + jQuery(os[i]).html() + '">' + jQuery(os[i]).html() + '</a></li>';
                i++;
            }
            html += '</ul>' + '</div>';
            var that = this;
            jQuery(parent).append(html);
            jQuery(parent).find('ul.dropdown-menu > li > a').on('click', function () {
                jQuery(parent).find('button.btn').html(jQuery(this).html() + '<span class="caret"></span>');
                jQuery(that).find('option[value="' + jQuery(this).attr('data-value') + '"]')[0].selected = true;
                jQuery(that).trigger('change');
            });
            jQuery(this).hide();
        });
    };
}(jQuery));


jQuery('.bootstrap-select').bootselect();

Selenium WebDriver: I want to overwrite value in field instead of appending to it with sendKeys using Java

Okay, it is a few days ago... In my current case, the answer from ZloiAdun does not work for me, but brings me very close to my solution...

Instead of:

element.sendKeys(Keys.chord(Keys.CONTROL, "a"), "55");

the following code makes me happy:

element.sendKeys(Keys.HOME, Keys.chord(Keys.SHIFT, Keys.END), "55");

So I hope that helps somebody!

RHEL 6 - how to install 'GLIBC_2.14' or 'GLIBC_2.15'?

Naive question: Is it possible to somehow download GLIBC 2.15, put it in any folder (e.g. /tmp/myglibc) and then point to this path ONLY when executing something that needs this specific version of glibc?

Yes, it's possible.

showDialog deprecated. What's the alternative?

To display dialog box, you can use the following code. This is to display a simple AlertDialog box with multiple check boxes:

AlertDialog.Builder alertDialog= new AlertDialog.Builder(MainActivity.this); .
            alertDialog.setTitle("this is a dialog box ");
            alertDialog.setPositiveButton("ok", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    Toast.makeText(getBaseContext(),"ok ive wrote this 'ok' here" ,Toast.LENGTH_SHORT).show();

                }
            });
            alertDialog.setNegativeButton("cancel", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                        Toast.makeText(getBaseContext(), "cancel ' comment same as ok'", Toast.LENGTH_SHORT).show();


                }
            });
            alertDialog.setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                    // TODO Auto-generated method stub
                    Toast.makeText(getBaseContext(), items[which] +(isChecked?"clicked'again i've wrrten this click'":"unchecked"),Toast.LENGTH_SHORT).show();

                }
            });
            alertDialog.show();

Heading

Whereas if you are using the showDialog function to display different dialog box or anything as per the arguments passed, you can create a self function and can call it under the onClickListener() function. Something like:

 public CharSequence[] items={"google","Apple","Kaye"};
public boolean[] checkedItems=new boolean[items.length];
Button bt;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    bt=(Button) findViewById(R.id.bt);
    bt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            display(0);             
        }       
    });
}

and add the code of dialog box given above in the function definition.

How do you detect the clearing of a "search" HTML5 input?

I know this is an old question, but I was looking for the similar thing. Determine when the 'X' was clicked to clear the search box. None of the answers here helped me at all. One was close but also affected when the user hit the 'enter' button, it would fire the same result as clicking the 'X'.

I found this answer on another post and it works perfect for me and only fires when the user clears the search box.

$("input").bind("mouseup", function(e){
   var $input = $(this),
   oldValue = $input.val();

   if (oldValue == "") return;

   // When this event is fired after clicking on the clear button
   // the value is not cleared yet. We have to wait for it.
   setTimeout(function(){
     var newValue = $input.val();

      if (newValue == ""){
         // capture the clear
         $input.trigger("cleared");
      }
    }, 1);
});

java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty on Linux, or why is the default truststore empty

Had the same issue on Ubuntu 14.10 with java-8-oracle installed.

Solved installing ca-certificates-java package:

sudo apt-get install ca-certificates-java

How to parse a month name (string) to an integer for comparison in C#?

What I did was to use SimpleDateFormat to create a format string, and parse the text to a date, and then retrieve the month from that. The code is below:

int year = 2012 \\or any other year
String monthName = "January" \\or any other month
SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy");
int monthNumber = format.parse("01-" + monthName + "-" + year).getMonth();

How to center the elements in ConstraintLayout

The solution with guideline works only for this particular case with single line EditText. To make it work for multiline EditText you should use "packed" chain.

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="16dp"
    android:paddingRight="16dp">

    <android.support.design.widget.TextInputLayout
        android:id="@+id/client_id_input_layout"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toTopOf="@+id/authenticate"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_chainStyle="packed">

        <android.support.design.widget.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/login_client_id"
            android:inputType="textEmailAddress" />

    </android.support.design.widget.TextInputLayout>

    <android.support.v7.widget.AppCompatButton
        android:id="@+id/authenticate"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="@string/login_auth"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="@id/client_id_input_layout"
        app:layout_constraintRight_toRightOf="@id/client_id_input_layout"
        app:layout_constraintTop_toBottomOf="@id/client_id_input_layout" />

</android.support.constraint.ConstraintLayout>

Here's how it looks:

View on Nexus 5

You can read more about using chains in following posts:

Round double value to 2 decimal places

For Swift there is a simple solution if you can't either import Foundation, use round() and/or does not want a String (usually the case when you're in Playground):

var number = 31.726354765
var intNumber = Int(number * 1000.0)
var roundedNumber = Double(intNumber) / 1000.0

result: 31.726

How to find the date of a day of the week from a date using PHP?

Just:

2012-10-11 as $date and 5 as $day

<?php
$day=5;
$w      = date("w", strtotime("2011-01-11")) + 1; // you must add 1 to for Sunday

echo $w;

$sunday = date("Y-m-d", strtotime("2011-01-11")-strtotime("+$w day"));

$result = date("Y-m-d", strtotime($sunday)+strtotime("+$day day"));

echo $result;

?>

The $result = '2012-10-12' is what you want.

Twitter - How to embed native video from someone else's tweet into a New Tweet or a DM

I found a faster way of embedding:

  • Just copy the link.
  • Paste the link and remove the "?s=19" part and add "/video/1"
  • That's it.

Setting Remote Webdriver to run tests in a remote computer using Java

This is how I got rid of the error:

WebDriverException: Error forwarding the new session cannot find : {platform=WINDOWS, ensureCleanSession=true, browserName=internet explorer, version=11}

In your nodeconfig.json, the version must be a String, not an integer.

So instead of using "version": 11 use "version": "11" (note the double quotes).

A full example of a working nodecondig.json file for a RemoteWebDriver:

{
  "capabilities":
  [
    {
      "platform": "WIN8_1",
      "browserName": "internet explorer",
      "maxInstances": 1,
      "seleniumProtocol": "WebDriver"
      "version": "11"
    }
    ,{
      "platform": "WIN7",
      "browserName": "chrome",
      "maxInstances": 4,
      "seleniumProtocol": "WebDriver"
      "version": "40"
    }
    ,{
      "platform": "LINUX",
      "browserName": "firefox",
      "maxInstances": 4,
      "seleniumProtocol": "WebDriver"
      "version": "33"
    }
  ],
  "configuration":
  {
    "proxy": "org.openqa.grid.selenium.proxy.DefaultRemoteProxy",
    "maxSession": 3,
    "port": 5555,
    "host": ip,
    "register": true,
    "registerCycle": 5000,
    "hubPort": 4444,
    "hubHost": {your-ip-address}
  }
}

How do I pass an object from one activity to another on Android?

You can create a subclass of Application and store your shared object there. The Application object should exist for the lifetime of your app as long as there is some active component.

From your activities, you can access the application object via getApplication().

Flutter - Wrap text on overflow, like insert ellipsis or fade

One way to fix an overflow of a Text Widget within a row if for example a chat message can be one really long line. You can create a Container and a BoxConstraint with a maxWidth in it.

            Container(
              constraints: BoxConstraints(maxWidth: 200),
                child: Text(
                  (chatName == null) ? " ": chatName,
                  style: TextStyle(
                      fontWeight: FontWeight.w400,
                      color: Colors.black87,
                      fontSize: 17.0),
                )
            ),

Squash my last X commits together using Git

Use git rebase -i <after-this-commit> and replace "pick" on the second and subsequent commits with "squash" or "fixup", as described in the manual.

In this example, <after-this-commit> is either the SHA1 hash or the relative location from the HEAD of the current branch from which commits are analyzed for the rebase command. For example, if the user wishes to view 5 commits from the current HEAD in the past the command is git rebase -i HEAD~5.

matplotlib savefig in jpeg format

Matplotlib can handle directly and transparently jpg if you have installed PIL. You don't need to call it, it will do it by itself. If Python cannot find PIL, it will raise an error.

is python capable of running on multiple cores?

I converted the script to Python3 and ran it on my Raspberry Pi 3B+:

import time
import threading

def t():
        with open('/dev/urandom', 'rb') as f:
                for x in range(100):
                        f.read(4 * 65535)

if __name__ == '__main__':
    start_time = time.time()
    t()
    t()
    t()
    t()
    print("Sequential run time: %.2f seconds" % (time.time() - start_time))

    start_time = time.time()
    t1 = threading.Thread(target=t)
    t2 = threading.Thread(target=t)
    t3 = threading.Thread(target=t)
    t4 = threading.Thread(target=t)
    t1.start()
    t2.start()
    t3.start()
    t4.start()
    t1.join()
    t2.join()
    t3.join()
    t4.join()
    print("Parallel run time: %.2f seconds" % (time.time() - start_time))

python3 t.py

Sequential run time: 2.10 seconds
Parallel run time: 1.41 seconds

For me, running parallel was quicker.

How to disable Django's CSRF validation?

To disable CSRF for class based views the following worked for me.
Using django 1.10 and python 3.5.2

from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator

@method_decorator(csrf_exempt, name='dispatch')
class TestView(View):
    def post(self, request, *args, **kwargs):
        return HttpResponse('Hello world')

How to return multiple values?

You can return an object of a Class in Java.

If you are returning more than 1 value that are related, then it makes sense to encapsulate them into a class and then return an object of that class.

If you want to return unrelated values, then you can use Java's built-in container classes like Map, List, Set etc. Check the java.util package's JavaDoc for more details.

How do I create an Excel chart that pulls data from multiple sheets?

Here's some code from Excel 2010 that may work. It has a couple specifics (like filtering bad-encode characters from titles) but it was designed to create multiple multi-series graphs from 4-dimensional data having both absolute and percentage-based data. Modify it how you like:

Sub createAllGraphs()

Const chartWidth As Integer = 260
Const chartHeight As Integer = 200




If Sheets.Count = 1 Then
    Sheets.Add , Sheets(1)
    Sheets(2).Name = "AllCharts"
ElseIf Sheets("AllCharts").ChartObjects.Count > 0 Then
    Sheets("AllCharts").ChartObjects.Delete
End If
Dim c As Variant
Dim c2 As Variant
Dim cs As Object
Set cs = Sheets("AllCharts")
Dim s As Object
Set s = Sheets(1)

Dim i As Integer


Dim chartX As Integer
Dim chartY As Integer

Dim r As Integer
r = 2

Dim curA As String
curA = s.Range("A" & r)
Dim curB As String
Dim curC As String
Dim startR As Integer
startR = 2

Dim lastTime As Boolean
lastTime = False

Do While s.Range("A" & r) <> ""

    If curC <> s.Range("C" & r) Then

        If r <> 2 Then
seriesAdd:
            c.SeriesCollection.Add s.Range("D" & startR & ":E" & (r - 1)), , False, True
            c.SeriesCollection(c.SeriesCollection.Count).Name = Replace(s.Range("C" & startR), "Â", "")
            c.SeriesCollection(c.SeriesCollection.Count).XValues = "='" & s.Name & "'!$D$" & startR & ":$D$" & (r - 1)
            c.SeriesCollection(c.SeriesCollection.Count).Values = "='" & s.Name & "'!$E$" & startR & ":$E$" & (r - 1)
            c.SeriesCollection(c.SeriesCollection.Count).HasErrorBars = True
            c.SeriesCollection(c.SeriesCollection.Count).ErrorBars.Select
            c.SeriesCollection(c.SeriesCollection.Count).ErrorBar Direction:=xlY, Include:=xlBoth, Type:=xlCustom, Amount:="='" & s.Name & "'!$F$" & startR & ":$F$" & (r - 1), minusvalues:="='" & s.Name & "'!$F$" & startR & ":$F$" & (r - 1)
            c.SeriesCollection(c.SeriesCollection.Count).ErrorBar Direction:=xlX, Include:=xlBoth, Type:=xlFixedValue, Amount:=0

            c2.SeriesCollection.Add s.Range("D" & startR & ":D" & (r - 1) & ",G" & startR & ":G" & (r - 1)), , False, True
            c2.SeriesCollection(c2.SeriesCollection.Count).Name = Replace(s.Range("C" & startR), "Â", "")
            c2.SeriesCollection(c2.SeriesCollection.Count).XValues = "='" & s.Name & "'!$D$" & startR & ":$D$" & (r - 1)
            c2.SeriesCollection(c2.SeriesCollection.Count).Values = "='" & s.Name & "'!$G$" & startR & ":$G$" & (r - 1)
            c2.SeriesCollection(c2.SeriesCollection.Count).HasErrorBars = True
            c2.SeriesCollection(c2.SeriesCollection.Count).ErrorBars.Select
            c2.SeriesCollection(c2.SeriesCollection.Count).ErrorBar Direction:=xlY, Include:=xlBoth, Type:=xlCustom, Amount:="='" & s.Name & "'!$H$" & startR & ":$H$" & (r - 1), minusvalues:="='" & s.Name & "'!$H$" & startR & ":$H$" & (r - 1)
            c2.SeriesCollection(c2.SeriesCollection.Count).ErrorBar Direction:=xlX, Include:=xlBoth, Type:=xlFixedValue, Amount:=0
            If lastTime = True Then GoTo postLoop
        End If

        If curB <> s.Range("B" & r).Value Then

            If curA <> s.Range("A" & r).Value Then
                chartX = chartX + chartWidth * 2
                chartY = 0
                curA = s.Range("A" & r)
            End If

            Set c = cs.ChartObjects.Add(chartX, chartY, chartWidth, chartHeight)
            Set c = c.Chart
            c.ChartWizard , xlXYScatterSmooth, , , , , True, Replace(s.Range("B" & r), "Â", "") & " " & s.Range("A" & r), s.Range("D1"), s.Range("E1")

            Set c2 = cs.ChartObjects.Add(chartX + chartWidth, chartY, chartWidth, chartHeight)
            Set c2 = c2.Chart
            c2.ChartWizard , xlXYScatterSmooth, , , , , True, Replace(s.Range("B" & r), "Â", "") & " " & s.Range("A" & r) & " (%)", s.Range("D1"), s.Range("G1")

            chartY = chartY + chartHeight
            curB = s.Range("B" & r)
            curC = s.Range("C" & r)
        End If

        curC = s.Range("C" & r)
        startR = r
    End If

    If s.Range("A" & r) <> "" Then oneMoreTime = False ' end the loop for real this time
    r = r + 1
Loop

lastTime = True
GoTo seriesAdd
postLoop:
cs.Activate

End Sub

Is < faster than <=?

TL;DR answer

For most combinations of architecture, compiler and language, < will not be faster than <=.

Full answer

Other answers have concentrated on x86 architecture, and I don't know the ARM architecture (which your example assembler seems to be) well enough to comment specifically on the code generated, but this is an example of a micro-optimisation which is very architecture specific, and is as likely to be an anti-optimisation as it is to be an optimisation.

As such, I would suggest that this sort of micro-optimisation is an example of cargo cult programming rather than best software engineering practice.

Counterexample

There are probably some architectures where this is an optimisation, but I know of at least one architecture where the opposite may be true. The venerable Transputer architecture only had machine code instructions for equal to and greater than or equal to, so all comparisons had to be built from these primitives.

Even then, in almost all cases, the compiler could order the evaluation instructions in such a way that in practice, no comparison had any advantage over any other. Worst case though, it might need to add a reverse instruction (REV) to swap the top two items on the operand stack. This was a single byte instruction which took a single cycle to run, so had the smallest overhead possible.

Summary

Whether or not a micro-optimisation like this is an optimisation or an anti-optimisation depends on the specific architecture you are using, so it is usually a bad idea to get into the habit of using architecture specific micro-optimisations, otherwise you might instinctively use one when it is inappropriate to do so, and it looks like this is exactly what the book you are reading is advocating.

How to negate a method reference predicate

I'm planning to static import the following to allow for the method reference to be used inline:

public static <T> Predicate<T> not(Predicate<T> t) {
    return t.negate();
}

e.g.

Stream<String> s = ...;
long nonEmptyStrings = s.filter(not(String::isEmpty)).count();

Update: Starting from Java-11, the JDK offers a similar solution built-in as well.

Copy array by value

I would personally prefer this way:

JSON.parse(JSON.stringify( originalObject ));

MySQL - Cannot add or update a child row: a foreign key constraint fails

Since you haven't given table definitions, it's hard to guess. But it looks like you are attempting to modify the foreign key in the child table. AFAIK, this is illegal, you can modify it from the parent, but not the child table.

Consider this example:

CREATE TABLE parent (
  parent_id INT NOT NULL,
  parent_data int,

  PRIMARY KEY (parent_id)
) ENGINE=INNODB;

CREATE TABLE child1 (
  child1_id INT,
  child1_data INT,
  fk_parent_id INT,

  INDEX par_ind1 (fk_parent_id),

  FOREIGN KEY (fk_parent_id)
    REFERENCES parent(parent_id)
    ON DELETE CASCADE
    ON UPDATE CASCADE
) ENGINE=INNODB;

CREATE TABLE child2 (
  child2_id INT,
  child2_data INT,
  fk_parent_id INT,

  INDEX par_ind2 (fk_parent_id),

  FOREIGN KEY (fk_parent_id)
    REFERENCES parent(parent_id)
    ON DELETE CASCADE
    ON UPDATE CASCADE
) ENGINE=INNODB;

INSERT INTO parent
  (parent_id, parent_data)
  VALUES
  (1, 11),
  (2, 12);

INSERT INTO child1
  (child1_id, child1_data, fk_parent_id)
  VALUES
  (101, 1001, 1),
  (102, 1002, 1),
  (103, 1003, 1),
  (104, 1004, 2),
  (105, 1005, 2);

INSERT INTO child2
  (child2_id, child2_data, fk_parent_id)
  VALUES
  (106, 1006, 1),
  (107, 1007, 1),
  (108, 1008, 1),
  (109, 1009, 2),
  (110, 1010, 2);

Then this is allowed:

UPDATE parent
  SET parent_id = 3 WHERE parent_id = 2;

SELECT * FROM parent;
SELECT * FROM child1;
SELECT * FROM child2;

But this is not, because it modifies the parent fk from the child table:

UPDATE child1
  SET fk_parent_id = 4 WHERE fk_parent_id = 1;

It gets an error very similar to your error:

Cannot add or update a child row: a foreign key constraint fails (`db_2_b43a7`.`child1`, CONSTRAINT `child1_ibfk_1` FOREIGN KEY (`fk_parent_id`) REFERENCES `parent` (`parent_id`) ON DELETE CASCADE ON UPDATE CASCADE):

How to use Git?

Using Git for version control

Visual studio code have Integrated Git Support.

  • Steps to use git.

Install Git : https://git-scm.com/downloads

1) Initialize your repository

Navigate to directory where you want to initialize Git

Use git init command This will create a empty .git repository

2) Stage the changes

Staging is process of making Git to track our newly added files. For example add a file and type git status. You will find the status that untracked file. So to stage the changes use git add filename. If now type git status, you will find that new file added for tracking.

You can also unstage files. Use git reset

3) Commit Changes

Commiting is the process of recording your changes to repository. To commit the statges changes, you need to add a comment that explains the changes you made since your previous commit.

Use git commit -m message string

We can also commit the multiple files of same type using command git add '*.txt'. This command will commit all files with txt extension.

4) Follow changes

The aim of using version control is to keep all versions of each and every file in our project, Compare the the current version with last commit and keep the log of all changes.

Use git log to see the log of all changes.

Visual studio code’s integrated git support help us to compare the code by double clicking on the file OR Use git diff HEAD

You can also undo file changes at the last commit. Use git checkout -- file_name

5) Create remote repositories

Till now we have created a local repository. But in order to push it to remote server. We need to add a remote repository in server.

Use git remote add origin server_git_url

Then push it to server repository

Use git push -u origin master

Let assume some time has passed. We have invited other people to our project who have pulled our changes, made their own commits, and pushed them.

So to get the changes from our team members, we need to pull the repository.

Use git pull origin master

6) Create Branches

Lets think that you are working on a feature or a bug. Better you can create a copy of your code(Branch) and make separate commits to. When you have done, merge this branch back to their master branch.

Use git branch branch_name

Now you have two local branches i.e master and XXX(new branch). You can switch branches using git checkout master OR git checkout new_branch_name

Commiting branch changes using git commit -m message

Switch back to master using git checkout master

Now we need to merge changes from new branch into our master Use git merge branch_name

Good! You just accomplished your bugfix Or feature development and merge. Now you don’t need the new branch anymore. So delete it using git branch -d branch_name

Now we are in the last step to push everything to remote repository using git push

Hope this will help you

How to convert jsonString to JSONObject in Java

you must import org.json

JSONObject jsonObj = null;
        try {
            jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
        } catch (JSONException e) {
            e.printStackTrace();
        }

Node.js setting up environment specific configs to be used with everyauth

How about doing this in a much more elegant way with nodejs-config module.

This module is able to set configuration environment based on your computer's name. After that when you request a configuration you will get environment specific value.

For example lets assume your have two development machines named pc1 and pc2 and a production machine named pc3. When ever you request configuration values in your code in pc1 or pc2 you must get "development" environment configuration and in pc3 you must get "production" environment configuration. This can be achieved like this:

  1. Create a base configuration file in the config directory, lets say "app.json" and add required configurations to it.
  2. Now simply create folders within the config directory that matches your environment name, in this case "development" and "production".
  3. Next, create the configuration files you wish to override and specify the options for each environment at the environment directories(Notice that you do not have to specify every option that is in the base configuration file, but only the options you wish to override. The environment configuration files will "cascade" over the base files.).

Now create new config instance with following syntax.

var config = require('nodejs-config')(
   __dirname,  // an absolute path to your applications 'config' directory
   {
      development: ["pc1", "pc2"],
      production: ["pc3"],

   }
);

Now you can get any configuration value without worrying about the environment like this:

config.get('app').configurationKey;

how to use php DateTime() function in Laravel 5

DateTime is not a function, but the class.

When you just reference a class like new DateTime() PHP searches for the class in your current namespace. However the DateTime class obviously doesn't exists in your controllers namespace but rather in root namespace.

You can either reference it in the root namespace by prepending a backslash:

$now = new \DateTime();

Or add an import statement at the top:

use DateTime;

$now = new DateTime();

How to remove files that are listed in the .gitignore but still on the repository?

An easier way that works regardless of the OS is to do

git rm -r --cached .
git add .
git commit -m "Drop files from .gitignore"

You basically remove and re-add all files, but git add will ignore the ones in .gitignore.

Using the --cached option will keep files in your filesystem, so you won't be removing files from your disk.

Note: Some pointed out in the comments that you will lose the history of all your files. I tested this with git 2.27.0 on MacOS and it is not the case. If you want to check what is happening, check your git diff HEAD~1 before you push your commit.

How to get N rows starting from row M from sorted table in T-SQL

Probably good for small results, works in all versions of TSQL:

SELECT 
        * 
FROM
     (SELECT TOP (N) * 
      FROM 
            (SELECT TOP (M + N - 1) 
             FROM 
                   Table
             ORDER BY 
                      MyColumn) qasc
      ORDER BY 
               MyColumn DESC) qdesc
 ORDER BY 
         MyColumn

How to copy a char array in C?

Well, techincally you can…

typedef struct { char xx[18]; } arr_wrap;

char array1[18] = "abcdefg";
char array2[18];

*((arr_wrap *) array2) = *((arr_wrap *) array1);

printf("%s\n", array2);     /* "abcdefg" */

but it will not look very beautiful.

…Unless you use the C preprocessor…

#define CC_MEMCPY(DESTARR, SRCARR, ARRSIZE) \
    { struct _tmparrwrap_ { char xx[ARRSIZE]; }; *((struct _tmparrwrap_ *) DESTARR) = *((struct _tmparrwrap_ *) SRCARR); }

You can then do:

char array1[18] = "abcdefg";
char array2[18];

CC_MEMCPY(array2, array1, sizeof(array1));

printf("%s\n", array2);     /* "abcdefg" */

And it will work with any data type, not just char:

int numbers1[3] = { 1, 2, 3 };
int numbers2[3];

CC_MEMCPY(numbers2, numbers1, sizeof(numbers1));

printf("%d - %d - %d\n", numbers2[0], numbers2[1], numbers2[2]);     /* "abcdefg" */

(Yes, the code above is granted to work always and it's portable)

Opening a .ipynb.txt File

If you have a unix/linux system I'd just rename the file via command line

mv file_name.pynb.txt file_name.ipynb

worked like a charm for me!

Warning: Use the 'defaultValue' or 'value' props on <select> instead of setting 'selected' on <option>

With Hooks and useState

Use defaultValue to select the default value.

    const statusOptions = [
        { value: 1, label: 'Publish' },
        { value: 0, label: 'Unpublish' }
    ];
    const [statusValue, setStatusValue] = useState('');
    const handleStatusChange = e => {
        setStatusValue(e.value);
    }

return(
<>
<Select options={statusOptions} 
    defaultValue={[{ value: published, label: published == 1 ? 'Publish' : 'Unpublish' }]} 
    onChange={handleStatusChange} 
    value={statusOptions.find(obj => obj.value === statusValue)} required />
</>
)

Text vertical alignment in WPF TextBlock

Just for giggles, give this XAML a whirl. It isn't perfect as it is not an 'alignment' but it allows you to adjust text alignment within a paragraph.

<TextBlock>
    <TextBlock BaselineOffset="30">One</TextBlock>
    <TextBlock BaselineOffset="20">Two</TextBlock>  
    <Run>Three</Run>            
    <Run BaselineAlignment="Subscript">Four</Run>   
</TextBlock>

How can I read the contents of an URL with Python?

For python3 users, to save time, use the following code,

from urllib.request import urlopen

link = "https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html"

f = urlopen(link)
myfile = f.read()
print(myfile)

I know there are different threads for error: Name Error: urlopen is not defined, but thought this might save time.

jQuery issue in Internet Explorer 8

Maybe you insert two scripts,it should be work.

<script src="http://ie7-js.googlecode.com/svn/version/2.1(beta4)/IE8.js"></script>  
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js">/script> 

Copy all the lines to clipboard

Another easy way to copy the entire file if you're having problems using VI, is just by typing "cat filename". It will echo the file to screen and then you can just scroll up and down and copy/paste.

AttributeError: 'numpy.ndarray' object has no attribute 'append'

Use numpy.concatenate(list1 , list2) or numpy.append() Look into the thread at Append a NumPy array to a NumPy array.

How to update /etc/hosts file in Docker image during "docker build"

You can not modify the host file in the image using echo in RUN step because docker daemon will maintain the file(/etc/hosts) and its content(hosts entry) when you start a container from the image.

However following can be used to achieve the same:

ENTRYPOINT ["/bin/sh", "-c" , "echo 192.168.254.10   database-server >> /etc/hosts && echo 192.168.239.62   redis-ms-server >> /etc/hosts && exec java -jar ./botblocker.jar " ]

Key to notice here is the use of exec command as docker documentation suggests. Use of exec will make the java command as PID 1 for the container. Docker interrupts will only respond to that.

See https://docs.docker.com/engine/reference/builder/#entrypoint

A JOIN With Additional Conditions Using Query Builder or Eloquent

You can replicate those brackets in the left join:

LEFT JOIN bookings  
               ON rooms.id = bookings.room_type_id
              AND (  bookings.arrival between ? and ?
                  OR bookings.departure between ? and ? )

is

->leftJoin('bookings', function($join){
    $join->on('rooms.id', '=', 'bookings.room_type_id');
    $join->on(DB::raw('(  bookings.arrival between ? and ? OR bookings.departure between ? and ? )'), DB::raw(''), DB::raw(''));
})

You'll then have to set the bindings later using "setBindings" as described in this SO post: How to bind parameters to a raw DB query in Laravel that's used on a model?

It's not pretty but it works.

Easiest way to split a string on newlines in .NET?

Very easy, actually.

VB.NET:

Private Function SplitOnNewLine(input as String) As String
    Return input.Split(Environment.NewLine)
End Function

C#:

string splitOnNewLine(string input)
{
    return input.split(environment.newline);
}

Class has been compiled by a more recent version of the Java Environment

Refreshing gradle dependencies works for me: Right click over the project -> Gradle -> Refresh Gradle Project.

Best way to store passwords in MYSQL database

best to use crypt for password storing in DB

example code :

$crypted_pass = crypt($password);

//$pass_from_login is the user entered password
//$crypted_pass is the encryption
if(crypt($pass_from_login,$crypted_pass)) == $crypted_pass)
{
   echo("hello user!")
}

documentation :

http://www.php.net/manual/en/function.crypt.php

Android SQLite SELECT Query

Try trimming the string to make sure there is no extra white space:

Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE TRIM(name) = '"+name.trim()+"'", null);

Also use c.moveToFirst() like @thinksteep mentioned.


This is a complete code for select statements.

SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT column1,column2,column3 FROM table ", null);
if (c.moveToFirst()){
    do {
        // Passing values 
        String column1 = c.getString(0);
        String column2 = c.getString(1);
        String column3 = c.getString(2); 
        // Do something Here with values
    } while(c.moveToNext());
}
c.close();
db.close();

Date in mmm yyyy format in postgresql

SELECT TO_CHAR(NOW(), 'Mon YYYY');

How do I enable/disable log levels in Android?

Another way is to use a logging platform that has the capabilities of opening and closing logs. This can give much of flexibility sometimes even on a production app which logs should be open and which closed depending on which issues you have for example:

Convert UTC dates to local time in PHP

date() and localtime() both use the local timezone for the server unless overridden; you can override the timezone used with date_default_timezone_set().

http://www.php.net/manual/en/function.date-default-timezone-set.php

http://us3.php.net/manual/en/function.date.php

http://php.net/manual/en/function.localtime.php

Sending mass email using PHP

You can use swiftmailer for it. By using batch process.

<?php
    $message = Swift_Message::newInstance()
      ->setSubject('Let\'s get together today.')
      ->setFrom(array('[email protected]' => 'From Me'))
      ->setBody('Here is the message itself')
      ->addPart('<b>Test message being sent!!</b>', 'text/html');

    $data = mysql_query('SELECT first, last, email FROM users WHERE is_active=1') or die(mysql_error());
    while($row = mysql_fetch_assoc($data))
    {
       $message->addTo($row['email'], $row['first'] . ' ' . $row['last']);
    }

    $message->batchSend();
?>

Best solution to protect PHP code without encryption

They distribute their software under a proprietary license. The law protects their rights and prevents their customers from redistributing the source, though there is no actual difficulty doing so.

But as you might be well aware, copyright infringement (piracy) of software products is a pretty common phenomenon.

Overloading and overriding

Simple definitions for overloading and overriding

Overloading (Compile Time Polymorphism):: Functions with same name and different parameters

public class A
{
    public void print(int x, int y)
    {
        Console.WriteLine("Parent Method");
    }
}

public class B : A
{
    public void child()
    {
        Console.WriteLine("Child Method");
    }

    public void print(float x, float y)
    {
        Console.WriteLine("Overload child method");
    }
}

Overriding (Run Time Polymorphism):: Functions in the extended class with same name and same parameters as in the base class, but with different behaviors.

public class A
{
    public virtual void print()
    {
        Console.WriteLine("Parent Method");
    }
}

public class B : A
{
    public void child()
    {
        Console.WriteLine("Child Method");
    }

    public override void print()
    {
        Console.WriteLine("Overriding child method");
    }
}

How can I use tabs for indentation in IntelliJ IDEA?

File > Settings > Editor > Code Style > Java > Tabs and Indents > Use tab character

Substitute weapon of choice for Java as required.

TypeError: 'list' object is not callable in python

I was getting this error for another reason:

I accidentally had a blank list created in my __init__ which had the same name as a method I was trying to call (I had just finished refactoring a bit and the variable was no longer needed, but I missed it when cleaning up). So when I was instantiating the class and trying to call the method, it thought I was referencing the list object, not the method:

class DumbMistake:
    def __init__(self, k, v):
        self.k = k
        self.v = v
        self.update = []

    def update(self):
        // do updates to k, v, etc

if __name__ == '__main__':
    DumbMistake().update('one,two,three', '1,2,3')

So it was trying to assign the two strings to self.update[] instead of calling the update() method. Removed the variable and it all worked as intended. Hope this helps someone.

How do I update Ruby Gems from behind a Proxy (ISA-NTLM)

for anyone tunnelling with SSH; you can create a version of the gem command that uses SOCKS proxy:

  1. Install socksify with gem install socksify (you'll need to be able to do this step without proxy, at least)
  2. Copy your existing gem exe

    cp $(command which gem) /usr/local/bin/proxy_gem
    
  3. Open it in your favourite editor and add this at the top (after the shebang)

    require 'socksify'
    
    if ENV['SOCKS_PROXY']
      require 'socksify'
      host, port = ENV['SOCKS_PROXY'].split(':')
      TCPSocket.socks_server = host || 'localhost'
      TCPSocket.socks_port = port.to_i || 1080
    end
    
  4. Set up your tunnel

    ssh -D 8123 -f -C -q -N user@proxy
    
  5. Run your gem command with proxy_gem

    SOCKS_PROXY=localhost:8123 proxy_gem push mygem
    

Laravel - Eloquent or Fluent random row

For Laravel 5.2 >=

use the Eloquent method:

inRandomOrder()

The inRandomOrder method may be used to sort the query results randomly. For example, you may use this method to fetch a random user:

$randomUser = DB::table('users')
            ->inRandomOrder()
            ->first();

from docs: https://laravel.com/docs/5.2/queries#ordering-grouping-limit-and-offset

Getting title and meta tags from external website

My solution (adapted from parts of cronoklee's & shamittomar's posts) so I can call it from anywhere and get a JSON return. Can be easily parsed into any content.

<?php
header('Content-type: application/json; charset=UTF-8');

if (!empty($_GET['url']))
{
    file_get_contents_curl($_GET['url']);
}
else
{
    echo "No Valid URL Provided.";
}


function file_get_contents_curl($url)
{
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

    $data = curl_exec($ch);
    curl_close($ch);

    echo json_encode(getSiteOG($data), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}

function getSiteOG( $OGdata){
    $doc = new DOMDocument();
    @$doc->loadHTML($OGdata);
    $res['title'] = $doc->getElementsByTagName('title')->item(0)->nodeValue;

    foreach ($doc->getElementsByTagName('meta') as $m){
        $tag = $m->getAttribute('name') ?: $m->getAttribute('property');
        if(in_array($tag,['description','keywords']) || strpos($tag,'og:')===0) $res[str_replace('og:','',$tag)] = utf8_decode($m->getAttribute('content'));

    }

    return $res;
}
?>

Why do we usually use || over |? What is the difference?

| does not do short-circuit evaluation in boolean expressions. || will stop evaluating if the first operand is true, but | won't.

In addition, | can be used to perform the bitwise-OR operation on byte/short/int/long values. || cannot.

How to perform a fade animation on Activity transition?

you can also add animation in your activity, in onCreate method like below becasue overridePendingTransition is not working with some mobile, or it depends on device settings...

View view = findViewById(android.R.id.content);
Animation mLoadAnimation = AnimationUtils.loadAnimation(getApplicationContext(), android.R.anim.fade_in);
mLoadAnimation.setDuration(2000);
view.startAnimation(mLoadAnimation);

Return Bit Value as 1/0 and NOT True/False in SQL Server

just you pass this things in your select query. using CASE

CASE WHEN  gender=0 then 'Female' WHEN  gender=1 then 'Male' END as Genderdisp

How many times a substring occurs

I'm not sure if this is something looked at already, but I thought of this as a solution for a word that is 'disposable':

for i in xrange(len(word)):
if word[:len(term)] == term:
    count += 1
word = word[1:]

print count

Where word is the word you are searching in and term is the term you are looking for

Angular 2: Get Values of Multiple Checked Checkboxes

@ccwasden solution above works for me with a small change, each checkbox must have a unique name otherwise binding wont works

<div class="form-group">
    <label for="options">Options:</label>
    <div *ngFor="let option of options; let i = index">
        <label>
            <input type="checkbox"
                   name="options_{{i}}"
                   value="{{option.value}}"
                   [(ngModel)]="option.checked"/>
            {{option.name}}
        </label>
    </div>
</div>

// my.component.ts

@Component({ moduleId:module.id, templateUrl:'my.component.html'})

export class MyComponent {
  options = [
    {name:'OptionA', value:'1', checked:true},
    {name:'OptionB', value:'2', checked:false},
    {name:'OptionC', value:'3', checked:true}
  ]

  get selectedOptions() { // right now: ['1','3']
    return this.options
              .filter(opt => opt.checked)
              .map(opt => opt.value)
  }
}

and also make sur to import FormsModule in your main module

import { FormsModule } from '@angular/forms';


imports: [
    FormsModule
  ],

How do I measure time elapsed in Java?

i found this code to be useful when timing things:

public class Et {
    public Et() {
    reset();
    }
    public void reset() {
    t0=System.nanoTime();
    }
    public long t0() {
        return t0;
    }
    public long dt() {
        return System.nanoTime()-t0();
    }
    public double etms() {
    return etms(dt());
    }
    @Override public String toString() {
        return etms()+" ms.";
    }
    public static double etms(long dt) {
        return dt/1000000.; // 1_000_000. breaks cobertura
    }
    private Long t0;
}