Programs & Examples On #Dmo

DirectX Media Objects (DMOs) are COM-based data-streaming components. In some respects, DMOs are similar to Microsoft DirectShow filters; DMOs are easier to create, test, and use.

AngularJs directive not updating another directive's scope

Just wondering why you are using 2 directives?

It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.

Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).

It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.

Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.

500 Error on AppHarbor but downloaded build works on my machine

Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.

So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.

Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.

Server Discovery And Monitoring engine is deprecated

i had the same errors popping up each time and this worked for me

mongoose.connect("mongodb://localhost:27017/${yourDB}", {
    useNewUrlParser: true,
    useUnifiedTopology: true

}, function (err) {
    if (err) {
        console.log(err)
    } else {
        console.log("Database connection successful")
    }
});

How to fix missing dependency warning when using useEffect React Hook?

just disable eslint for the next line;

useEffect(() => {
   fetchBusinesses();
// eslint-disable-next-line
}, []);

in this way you are using it just like a component did mount (called once)

updated

or

const fetchBusinesses = useCallback(() => {
 // your logic in here
 }, [someDeps])

useEffect(() => {
   fetchBusinesses();
// no need to skip eslint warning
}, [fetchBusinesses]); 

fetchBusinesses will be called everytime someDeps will change

react hooks useEffect() cleanup for only componentWillUnmount?

useEffect are isolated within its own scope and gets rendered accordingly. Image from https://reactjs.org/docs/hooks-custom.html

enter image description here

Can't perform a React state update on an unmounted component

There is a hook that's fairly common called useIsMounted that solves this problem (for functional components)...

import { useRef, useEffect } from 'react';

export function useIsMounted() {
  const isMounted = useRef(false);

  useEffect(() => {
    isMounted.current = true;
    return () => isMounted.current = false;
  }, []);

  return isMounted;
}

then in your functional component

function Book() {
  const isMounted = useIsMounted();
  ...

  useEffect(() => {
    asyncOperation().then(data => {
      if (isMounted.current) { setState(data); }
    })
  });
  ...
}

Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util

Issue has been resolved after updating Android studio version to 3.3-rc2 or latest released version.

cr: @shadowsheep

have to change version under /gradle/wrapper/gradle-wrapper.properties. refer below url https://stackoverflow.com/a/56412795/7532946

How to use componentWillMount() in React Hooks?

As it has been stated in react document:

You might be thinking that we’d need a separate effect to perform the cleanup. But code for adding and removing a subscription is so tightly related that useEffect is designed to keep it together. If your effect returns a function, React will run it when it is time to clean up:

useEffect(() => {
    function handleStatusChange(status) {
      setIsOnline(status.isOnline);
    }
    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
    // Specify how to clean up after this effect:
    return function cleanup() {
      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
    };
  });

  if (isOnline === null) {
    return 'Loading...';
  }
  return isOnline ? 'Online' : 'Offline';
}

so the only thing that we need to have the componentWillUnmount in hooks is to return a function inside a useEffect, as explained above.

How to call loading function with React useEffect only once

TL;DR

useEffect(yourCallback, []) - will trigger the callback only after the first render.

Detailed explanation

useEffect runs by default after every render of the component (thus causing an effect).

When placing useEffect in your component you tell React you want to run the callback as an effect. React will run the effect after rendering and after performing the DOM updates.

If you pass only a callback - the callback will run after each render.

If passing a second argument (array), React will run the callback after the first render and every time one of the elements in the array is changed. for example when placing useEffect(() => console.log('hello'), [someVar, someOtherVar]) - the callback will run after the first render and after any render that one of someVar or someOtherVar are changed.

By passing the second argument an empty array, React will compare after each render the array and will see nothing was changed, thus calling the callback only after the first render.

Objects are not valid as a React child. If you meant to render a collection of children, use an array instead

Had the same error but with a different scenario. I had my state as

        this.state = {
        date: new Date()
    }

so when I was asking it in my Class Component I had

p>Date = {this.state.date}</p>

Instead of

p>Date = {this.state.date.toLocaleDateString()}</p>

Flutter - The method was called on null

As stated in the above answers, it's always a good practice to initialize the variables, but if you have something which you don't know what value should it takes, and you want to leave it uninitialized so you have to make sure that you are updating it before using it.

For example: Assume we have double _bmi; and you don't know what value should it takes, so you can leave it as it is, but before using it, you have to update its value first like calling a function that calculating BMI like follows:

String calculateBMI (){
_bmi = weight / pow( height/100, 2);
return _bmi.toStringAsFixed(1);}

or whatever, what I mean is, you can leave the variable as it is, but before using it make sure you have initialized it using whatever the method you are using.

'mat-form-field' is not a known element - Angular 5 & Material2

I had this problem too. It turned out I forgot to include one of the components in app.module.ts

How to read file with async/await properly?

You can use fs.promises available natively since Node v11.0.0

import fs from 'fs';

const readFile = async filePath => {
  try {
    const data = await fs.promises.readFile(filePath, 'utf8')
    return data
  }
  catch(err) {
    console.log(err)
  }
}

Please add a @Pipe/@Directive/@Component annotation. Error

You have a typo in the import in your LoginComponent's file

import { Component } from '@angular/Core';

It's lowercase c, not uppercase

import { Component } from '@angular/core';

How do you set the document title in React?

I haven't tested this too thoroughly, but this seems to work. Written in TypeScript.

interface Props {
    children: string|number|Array<string|number>,
}

export default class DocumentTitle extends React.Component<Props> {

    private oldTitle: string = document.title;

    componentWillUnmount(): void {
        document.title = this.oldTitle;
    }

    render() {
        document.title = Array.isArray(this.props.children) ? this.props.children.join('') : this.props.children;
        return null;
    }
}

Usage:

export default class App extends React.Component<Props, State> {

    render() {
        return <>
            <DocumentTitle>{this.state.files.length} Gallery</DocumentTitle>
            <Container>
                Lorem ipsum
            </Container>
        </>
    }
}

Not sure why others are keen on putting their entire app inside their <Title> component, that seems weird to me.

By updating the document.title inside render() it'll refresh/stay up to date if you want a dynamic title. It should revert the title when unmounted too. Portals are cute, but seem unnecessary; we don't really need to manipulate any DOM nodes here.

ReactJS lifecycle method inside a function Component

According to the documentation:

import React, { useState, useEffect } from 'react'
// Similar to componentDidMount and componentDidUpdate:

useEffect(() => {


});

see React documentation

Error: the entity type requires a primary key

This exception message doesn't mean it requires a primary key to be defined in your database, it means it requires a primary key to be defined in your class.

Although you've attempted to do so:

private Guid _id;
[Key]
public Guid ID
{
    get { return _id; }
}

This has no effect, as Entity Framework ignores read-only properties. It has to: when it retrieves a Fruits record from the database, it constructs a Fruit object, and then calls the property setters for each mapped property. That's never going to work for read-only properties.

You need Entity Framework to be able to set the value of ID. This means the property needs to have a setter.

How to implement authenticated routes in React Router 4?

I know it's been a while but I've been working on an npm package for private and public routes.

Here's how to make a private route:

<PrivateRoute exact path="/private" authed={true} redirectTo="/login" component={Title} text="This is a private route"/>

And you can also make Public routes that only unauthed user can access

<PublicRoute exact path="/public" authed={false} redirectTo="/admin" component={Title} text="This route is for unauthed users"/>

I hope it helps!

'Access-Control-Allow-Origin' issue when API call made from React (Isomorphic app)

Use the google Chrome Extension called Allow-Control-Allow-Origin: *. It modifies the CORS headers on the fly in your application.

React - Display loading screen while DOM is rendering?

I had to deal with that problem recently and came up with a solution, which works just fine for me. However, I've tried @Ori Drori solution above and unfortunately it didn't work just right (had some delays + I don't like the usage of setTimeout function there).

This is what I came up with:

index.html file

Inside head tag - styles for the indicator:

<style media="screen" type="text/css">

.loading {
  -webkit-animation: sk-scaleout 1.0s infinite ease-in-out;
  animation: sk-scaleout 1.0s infinite ease-in-out;
  background-color: black;
  border-radius: 100%;
  height: 6em;
  width: 6em;
}

.container {
  align-items: center;
  background-color: white;
  display: flex;
  height: 100vh;
  justify-content: center;
  width: 100vw;
}

@keyframes sk-scaleout {
  0% {
    -webkit-transform: scale(0);
    transform: scale(0);
  }
  100% {
    -webkit-transform: scale(1.0);
    opacity: 0;
    transform: scale(1.0);
  }
}

</style>

Now the body tag:

<div id="spinner" class="container">
  <div class="loading"></div>
</div>

<div id="app"></div>

And then comes a very simple logic, inside app.js file (in the render function):

const spinner = document.getElementById('spinner');

if (spinner && !spinner.hasAttribute('hidden')) {
  spinner.setAttribute('hidden', 'true');
}

How does it work?

When the first component (in my app it's app.js aswell in most cases) mounts correctly, the spinner is being hidden with applying hidden attribute to it.

What's more important to add - !spinner.hasAttribute('hidden') condition prevents to add hidden attribute to the spinner with every component mount, so actually it will be added only one time, when whole app loads.

Maximum call stack size exceeded on npm install

For those having this issue when building a Docker image with Jenkins (or any CI), make sure the package-lock.json is also copied to the container.

COPY ./src/package*.json /home/node/
RUN npm install

For us, the install actually went fine, the error only occurred when running npm prune production for the production image.

React component initialize state from props

Update for React 16.3 alpha introduced static getDerivedStateFromProps(nextProps, prevState) (docs) as a replacement for componentWillReceiveProps.

getDerivedStateFromProps is invoked after a component is instantiated as well as when it receives new props. It should return an object to update state, or null to indicate that the new props do not require any state updates.

Note that if a parent component causes your component to re-render, this method will be called even if props have not changed. You may want to compare new and previous values if you only want to handle changes.

https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops

It is static, therefore it does not have direct access to this (however it does have access to prevState, which could store things normally attached to this e.g. refs)

edited to reflect @nerfologist's correction in comments

Plugin with id 'com.google.gms.google-services' not found

simply add "classpath 'com.google.gms:google-services:3.0.0'" to android/build.gradle to look like this

buildscript {
    repositories {
        maven {
            url "https://maven.google.com"
        }
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
        classpath 'com.google.gms:google-services:3.0.0'

       // NOTE: Do not place your application dependencies here; they belong
       // in the individual module build.gradle files

    }
}

and also add "apply plugin: 'com.google.gms.google-services'" to the end of file in android/app/build.gradle to look like this

apply plugin: 'com.google.gms.google-services'

Use component from another module

Whatever you want to use from another module, just put it in the export array. Like this-

 @NgModule({
  declarations: [TaskCardComponent],
  exports: [TaskCardComponent],
  imports: [MdCardModule]
})

Update React component every second

Owing to changes in React V16 where componentWillReceiveProps() has been deprecated, this is the methodology that I use for updating a component. Notice that the below example is in Typescript and uses the static getDerivedStateFromProps method to get the initial state and updated state whenever the Props are updated.

    class SomeClass extends React.Component<Props, State> {
  static getDerivedStateFromProps(nextProps: Readonly<Props>): Partial<State> | null {
    return {
      time: nextProps.time
    };
  }

  timerInterval: any;

  componentDidMount() {
    this.timerInterval = setInterval(this.tick.bind(this), 1000);
  }

  tick() {
    this.setState({ time: this.props.time });
  }

  componentWillUnmount() {
    clearInterval(this.timerInterval);
  }

  render() {
    return <div>{this.state.time}</div>;
  }
}

Error: Unexpected value 'undefined' imported by the module

I met this problem at the situation: - app-module --- app-routing // app router ----- imports: [RouterModule.forRoot(routes)] --- demo-module // sub-module ----- demo-routing ------- imports: [RouterModule.forRoot(routes)] // --> should be RouterModule.forChild!

because there is only a root.

Angular2 RC5: Can't bind to 'Property X' since it isn't a known property of 'Child Component'

I fixed it with adding the prefix (attr.) :

<create-report-card-form [attr.currentReportCardCount]="expression" ...

Unfortunately this haven't documented properly yet.

more detail here

React eslint error missing in props validation

I ran into this issue over the past couple days. Like Omri Aharon said in their answer above, it is important to add definitions for your prop types similar to:

SomeClass.propTypes = {
    someProp: PropTypes.number,
    onTap: PropTypes.func,
};

Don't forget to add the prop definitions outside of your class. I would place it right below/above my class. If you are not sure what your variable type or suffix is for your PropType (ex: PropTypes.number), refer to this npm reference. To Use PropTypes, you must import the package:

import PropTypes from 'prop-types';

If you get the linting error:someProp is not required, but has no corresponding defaultProps declaration all you have to do is either add .isRequired to the end of your prop definition like so:

SomeClass.propTypes = {
    someProp: PropTypes.number.isRequired,
    onTap: PropTypes.func.isRequired,
};

OR add default prop values like so:

SomeClass.defaultProps = {
    someProp: 1
};

If you are anything like me, unexperienced or unfamiliar with reactjs, you may also get this error: Must use destructuring props assignment. To fix this error, define your props before they are used. For example:

const { someProp } = this.props;

Getting "Cannot call a class as a function" in my React Project

In my case, I accidentally put component name (Home) as the first argument to connect function while it was supposed to be at the end. duh.

This one -surely- gave me the error:

export default connect(Home)(mapStateToProps, mapDispatchToProps)

But this one worked -surely- fine:

export default connect(mapStateToProps, mapDispatchToProps)(Home)

Import JavaScript file and call functions using webpack, ES6, ReactJS

Named exports:

Let's say you create a file called utils.js, with utility functions that you want to make available for other modules (e.g. a React component). Then you would make each function a named export:

export function add(x, y) {
  return x + y
}

export function mutiply(x, y) {
  return x * y
}

Assuming that utils.js is located in the same directory as your React component, you can use its exports like this:

import { add, multiply } from './utils.js';
...
add(2, 3) // Can be called wherever in your component, and would return 5.

Or if you prefer, place the entire module's contents under a common namespace:

import * as utils from './utils.js'; 
...
utils.multiply(2,3)

Default exports:

If you on the other hand have a module that only does one thing (could be a React class, a normal function, a constant, or anything else) and want to make that thing available to others, you can use a default export. Let's say we have a file log.js, with only one function that logs out whatever argument it's called with:

export default function log(message) {
  console.log(message);
}

This can now be used like this:

import log from './log.js';
...
log('test') // Would print 'test' in the console.

You don't have to call it log when you import it, you could actually call it whatever you want:

import logToConsole from './log.js';
...
logToConsole('test') // Would also print 'test' in the console.

Combined:

A module can have both a default export (max 1), and named exports (imported either one by one, or using * with an alias). React actually has this, consider:

import React, { Component, PropTypes } from 'react';

'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync

Override constructor of DbContext Try this :-

public DataContext(DbContextOptions<DataContext> option):base(option) {}

"SyntaxError: Unexpected token < in JSON at position 0"

You're receiving HTML (or XML) back from the server, but the dataType: json is telling jQuery to parse as JSON. Check the "Network" tab in Chrome dev tools to see contents of the server's response.

Re-render React component when prop changes

ComponentWillReceiveProps() is going to be deprecated in the future due to bugs and inconsistencies. An alternative solution for re-rendering a component on props change is to use ComponentDidUpdate() and ShouldComponentUpdate().

ComponentDidUpdate() is called whenever the component updates AND if ShouldComponentUpdate() returns true (If ShouldComponentUpdate() is not defined it returns true by default).

shouldComponentUpdate(nextProps){
    return nextProps.changedProp !== this.state.changedProp;
}

componentDidUpdate(props){
    // Desired operations: ex setting state
}

This same behavior can be accomplished using only the ComponentDidUpdate() method by including the conditional statement inside of it.

componentDidUpdate(prevProps){
    if(prevProps.changedProp !== this.props.changedProp){
        this.setState({          
            changedProp: this.props.changedProp
        });
    }
}

If one attempts to set the state without a conditional or without defining ShouldComponentUpdate() the component will infinitely re-render

Angular 2 beta.17: Property 'map' does not exist on type 'Observable<Response>'

You need to import the map operator:

import 'rxjs/add/operator/map'

Toggle Class in React

refs is not a DOM element. In order to find a DOM element, you need to use findDOMNode menthod first.

Do, this

var node = ReactDOM.findDOMNode(this.refs.btn);
node.classList.toggle('btn-menu-open');

alternatively, you can use like this (almost actual code)

this.state.styleCondition = false;


<a ref="btn" href="#" className={styleCondition ? "btn-menu show-on-small" : ""}><i></i></a>

you can then change styleCondition based on your state change conditions.

setInterval in a React app

If anyone is looking for a React Hook approach to implementing setInterval. Dan Abramov talked about it on his blog. Check it out if you want a good read about the subject including a Class approach. Basically the code is a custom Hook that turns setInterval as declarative.

function useInterval(callback, delay) {
  const savedCallback = useRef();

  // Remember the latest callback.
  useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);

  // Set up the interval.
  useEffect(() => {
    function tick() {
      savedCallback.current();
    }
    if (delay !== null) {
      let id = setInterval(tick, delay);
      return () => clearInterval(id);
    }
  }, [delay]);
}

Also posting the CodeSandbox link for convenience: https://codesandbox.io/s/105x531vkq

ReactJS: setTimeout() not working?

setTimeout(() => {
  this.setState({ position: 1 });
}, 3000);

The above would also work because the ES6 arrow function does not change the context of this.

How to fix Error: this class is not key value coding-compliant for the key tableView.'

You have your storyboard set up to expect an outlet called tableView but the actual outlet name is myTableView.

If you delete the connection in the storyboard and reconnect to the right variable name, it should fix the problem.

Invariant Violation: Could not find "store" in either the context or props of "Connect(SportsDatabase)"

in the end of your Index.js need to add this Code:

_x000D_
_x000D_
import React from 'react';_x000D_
import ReactDOM from 'react-dom';_x000D_
import { BrowserRouter  } from 'react-router-dom';_x000D_
_x000D_
import './index.css';_x000D_
import App from './App';_x000D_
_x000D_
import { Provider } from 'react-redux';_x000D_
import { createStore, applyMiddleware, compose, combineReducers } from 'redux';_x000D_
import thunk from 'redux-thunk';_x000D_
_x000D_
///its your redux ex_x000D_
import productReducer from './redux/reducer/admin/product/produt.reducer.js'_x000D_
_x000D_
const rootReducer = combineReducers({_x000D_
    adminProduct: productReducer_x000D_
   _x000D_
})_x000D_
const composeEnhancers = window._REDUX_DEVTOOLS_EXTENSION_COMPOSE_ || compose;_x000D_
const store = createStore(rootReducer, composeEnhancers(applyMiddleware(thunk)));_x000D_
_x000D_
_x000D_
const app = (_x000D_
    <Provider store={store}>_x000D_
        <BrowserRouter   basename='/'>_x000D_
            <App />_x000D_
        </BrowserRouter >_x000D_
    </Provider>_x000D_
);_x000D_
ReactDOM.render(app, document.getElementById('root'));
_x000D_
_x000D_
_x000D_

ReactJS - Add custom event listener to component

You could use componentDidMount and componentWillUnmount methods:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class MovieItem extends Component
{
    _handleNVEvent = event => {
        ...
    };

    componentDidMount() {
        ReactDOM.findDOMNode(this).addEventListener('nv-event', this._handleNVEvent);
    }

    componentWillUnmount() {
        ReactDOM.findDOMNode(this).removeEventListener('nv-event', this._handleNVEvent);
    }

    [...]

}

export default MovieItem;

Setting state on componentDidMount()

It is not an anti-pattern to call setState in componentDidMount. In fact, ReactJS provides an example of this in their documentation:

You should populate data with AJAX calls in the componentDidMount lifecycle method. This is so you can use setState to update your component when the data is retrieved.

Example From Doc

componentDidMount() {
    fetch("https://api.example.com/items")
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            isLoaded: true,
            items: result.items
          });
        },
        // Note: it's important to handle errors here
        // instead of a catch() block so that we don't swallow
        // exceptions from actual bugs in components.
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      )
  }

How to enable production mode?

You don't need any environment.ts or such file to be provided by your seed project. Just have a configuration.ts and add all such entries which require runtime decision (example:- logging configuration and urls). This will fit in any design structure and also help in future

configuration.ts

export class Configuration {

   isInProductionMode : bool = true;

   // other configuration
   serviceUrl : string = "http://myserver/myservice.svc";
   logFileName : string = "...";
}

// Now use in your startup code (main.ts or equivalent as per the seed project design

import { Configuration } from './configuration';
import { enableProdMode } from '@angular/core';
....
if (Configuration.isInProductionMode)
    enableProdMode();

How to get current route in react-router 2.0.0-rc5

Works for me in the same way:

...
<MyComponent {...this.props}>
  <Route path="path1" name="pname1" component="FirstPath">
  ...
</MyComponent>
...

And then, I can access "this.props.location.pathname" in the MyComponent function.

I forgot that it was I am...))) Following link describes more for make navigation bar etc.: react router this.props.location

Creating custom function in React component

You can create functions in react components. It is actually regular ES6 class which inherits from React.Component. Just be careful and bind it to the correct context in onClick event:

export default class Archive extends React.Component { 

    saySomething(something) {
        console.log(something);
    }

    handleClick(e) {
        this.saySomething("element clicked");
    }

    componentDidMount() {
        this.saySomething("component did mount");
    }

    render() {
        return <button onClick={this.handleClick.bind(this)} value="Click me" />;
    }
}

Can I execute a function after setState is finished updating?

With hooks in React 16.8 onward, it's easy to do this with useEffect

I've created a CodeSandbox to demonstrate this.

useEffect(() => {
  // code to be run when state variables in
  // dependency array changes
}, [stateVariables, thatShould, triggerChange])

Basically, useEffect synchronises with state changes and this can be used to render the canvas

import React, { useState, useEffect, useRef } from "react";
import { Stage, Shape } from "@createjs/easeljs";
import "./styles.css";

export default function App() {
  const [rows, setRows] = useState(10);
  const [columns, setColumns] = useState(10);
  let stage = useRef()

  useEffect(() => {
    stage.current = new Stage("canvas");
    var rectangles = [];
    var rectangle;
    //Rows
    for (var x = 0; x < rows; x++) {
      // Columns
      for (var y = 0; y < columns; y++) {
        var color = "Green";
        rectangle = new Shape();
        rectangle.graphics.beginFill(color);
        rectangle.graphics.drawRect(0, 0, 32, 44);
        rectangle.x = y * 33;
        rectangle.y = x * 45;

        stage.current.addChild(rectangle);

        var id = rectangle.x + "_" + rectangle.y;
        rectangles[id] = rectangle;
      }
    }
    stage.current.update();
  }, [rows, columns]);

  return (
    <div>
      <div className="canvas-wrapper">
        <canvas id="canvas" width="400" height="300"></canvas>
        <p>Rows: {rows}</p>
        <p>Columns: {columns}</p>
      </div>
      <div className="array-form">
        <form>
          <label>Number of Rows</label>
          <select
            id="numRows"
            value={rows}
            onChange={(e) => setRows(e.target.value)}
          >
            {getOptions()}
          </select>
          <label>Number of Columns</label>
          <select
            id="numCols"
            value={columns}
            onChange={(e) => setColumns(e.target.value)}
          >
            {getOptions()}
          </select>
        </form>
      </div>
    </div>
  );
}

const getOptions = () => {
  const options = [1, 2, 5, 10, 12, 15, 20];
  return (
    <>
      {options.map((option) => (
        <option key={option} value={option}>
          {option}
        </option>
      ))}
    </>
  );
};

setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op

removeEventListener has the same signature as addEventListener. All of the arguments must be exactly the same for it to remove the listener.

var onEnded = () => {};
audioNode.addEventListener('ended', onEnded, false);

this.cleanup = () => {
  audioNode.removeEventListener('ended', onEnded, false);
}

And in componentWillUnmount call this.cleanup().

IIS Config Error - This configuration section cannot be used at this path

Follow the below steps to unlock the handlers at the parent level:

1) In the connections tree(in IIS), go to your server node and then to your website.

2) For the website, in the right window you will see configuration editor under Management.

3) Double click on the configuration editor.

4) In the window that opens, on top you will find a drop down for sections. Choose "system.webServer/handlers" from the drop down.

5) On the right side, there is another drop down. Choose "ApplicationHost.Config "

6) On the right most pane, you will find "Unlock Section" under "Section" heading. Click on that.

7) Once the handlers at the applicationHost is unlocked, your website should run fine.

Shrink to fit content in flexbox, or flex-basis: content workaround?

It turns out that it was shrinking and growing correctly, providing the desired behaviour all along; except that in all current browsers flexbox wasn't accounting for the vertical scrollbar! Which is why the content appears to be getting cut off.

You can see here, which is the original code I was using before I added the fixed widths, that it looks like the column isn't growing to accomodate the text:

http://jsfiddle.net/2w157dyL/1/

However if you make the content in that column wider, you'll see that it always cuts it off by the same amount, which is the width of the scrollbar.

So the fix is very, very simple - add enough right padding to account for the scrollbar:

http://jsfiddle.net/2w157dyL/2/

_x000D_
_x000D_
  main > section {_x000D_
    overflow-y: auto;_x000D_
    padding-right: 2em;_x000D_
  }
_x000D_
_x000D_
_x000D_

It was when I was trying some things suggested by Michael_B (specifically adding a padding buffer) that I discovered this, thanks so much!

Edit: I see that he also posted a fiddle which does the same thing - again, thanks so much for all your help

Jquery in React is not defined

Just a note: if you use arrow functions you don't need the const that = this part. It might look like this:

fetch('http://jsonplaceholder.typicode.com/posts') 
  .then((response) => { return response.json(); }) 
  .then((myJson) => { 
     this.setState({data: myJson}); // for example
});

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'

In terminal execute in root project folder:

./gradlew clean

It helped me.

Get div's offsetTop positions in React

  import ReactDOM from 'react-dom';
  //...
  componentDidMount() {
    var n = ReactDOM.findDOMNode(this);
    console.log(n.offsetTop);
  }

You can just grab the offsetTop from the Node.

RecyclerView and java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder in Samsung devices

I ran into the same problem when I have both removed and updated items in the list... After days of investigating I think I finally found a solution.

What you need to do is first do all the notifyItemChanged of your list and only then do all the notifyItemRemoved in a descending order

I hope this will help people that are running into the same issue...

How do I conditionally add attributes to React components?

For example using property styles for custom container

const DriverSelector = props => {
  const Container = props.container;
  const otherProps = {
    ...( props.containerStyles && { style: props.containerStyles } )
  };

  return (
    <Container {...otherProps} >

React this.setState is not a function

You can avoid the need for .bind(this) with an ES6 arrow function.

VK.api('users.get',{fields: 'photo_50'},(data) => {
        if(data.response){
            this.setState({ //the error happens here
                FirstName: data.response[0].first_name
            });
            console.info(this.state.FirstName);
        }

    });

No tests found for given includes Error, when running Parameterized Unit test in Android Studio

In my case I was getting this message due to a runtime error with Junit which wasn't at all visible from the output of the gradle test task execution. I've run into this for a couple reasons:

  1. Including the org.junit.platform:junit-platform-launcher dependency with a version that didn't match the junit version I was using
  2. Having an entry in META-INF/services for a Junit test listener which I had commented out

You can try re-running with --debug and search for FAILED or org.gradle.api.internal.tasks.testing.TestSuiteExecutionException. In my second case, the exception was:

2020-10-20T11:34:26.517-0700 [DEBUG] [TestEventLogger]
2020-10-20T11:34:26.517-0700 [DEBUG] [TestEventLogger] Gradle Test Executor 1 STARTED
2020-10-20T11:34:26.661-0700 [DEBUG] [TestEventLogger]
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger] Gradle Test Executor 1 FAILED
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger]     org.gradle.api.internal.tasks.testing.TestSuiteExecutionException: Could not complete execution for Gradle Test Executor 1.
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger]         at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:63)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger]         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger]         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger]         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger]         at java.lang.reflect.Method.invoke(Method.java:498)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger]         at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger]         at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger]         at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger]         at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger]         at com.sun.proxy.$Proxy2.stop(Unknown Source)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger]         at org.gradle.api.internal.tasks.testing.worker.TestWorker.stop(TestWorker.java:132)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at java.lang.reflect.Method.invoke(Method.java:498)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:413)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at java.lang.Thread.run(Thread.java:748)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]         Caused by:
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]         java.util.ServiceConfigurationError: org.junit.platform.launcher.TestExecutionListener: Provider com.example.myproject.MyCommentedOutClass not found
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             at java.util.ServiceLoader.fail(ServiceLoader.java:239)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             at java.util.ServiceLoader.access$300(ServiceLoader.java:185)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             at java.util.ServiceLoader$LazyIterator.nextService(ServiceLoader.java:372)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:404)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             at java.util.ServiceLoader$1.next(ServiceLoader.java:480)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             at java.lang.Iterable.forEach(Iterable.java:74)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             at org.junit.platform.launcher.core.LauncherFactory.create(LauncherFactory.java:94)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             at org.junit.platform.launcher.core.LauncherFactory.create(LauncherFactory.java:67)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:97)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:79)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:75)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             ... 25 more

Notice that these are DEBUG logs. I didn't see anything helpful with just --info

How to change the style of a DatePicker in android?

Try this. It's the easiest & most efficient way

<style name="datepicker" parent="Theme.AppCompat.Light.Dialog">
        <item name="colorPrimary">@color/primary</item>
        <item name="colorPrimaryDark">@color/primary_dark</item>
        <item name="colorAccent">@color/primary</item>
</style>

React JS - Uncaught TypeError: this.props.data.map is not a function

try componentDidMount() lifecycle when fetching data

Asp.Net WebApi2 Enable CORS not working with AspNet.WebApi.Cors 5.2.3

In case of CORS request all modern browsers respond with an OPTION verb, and then the actual request follows through. This is supposed to be used to prompt the user for confirmation in case of a CORS request. But in case of an API if you would want to skip this verification process add the following snippet to Global.asax

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, PUT, DELETE");

                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }

Here we are just by passing the check by checking for OPTIONS verb.

React.js create loop through Array

You can simply do conditional check before doing map like

{Array.isArray(this.props.data.participants) && this.props.data.participants.map(function(player) {
   return <li key={player.championId}>{player.summonerName}</li>
   })
}

Now a days .map can be done in two different ways but still the conditional check is required like

.map with return

{Array.isArray(this.props.data.participants) && this.props.data.participants.map(player => {
   return <li key={player.championId}>{player.summonerName}</li>
 })
}

.map without return

{Array.isArray(this.props.data.participants) && this.props.data.participants.map(player => (
   return <li key={player.championId}>{player.summonerName}</li>
 ))
}

both the above functionalities does the same

Bootstrap modal in React.js

You can use the model from the react-bootstrap from link and it's basically a function based

function Example() {
  const [show, setShow] = useState(false);
  const handleClose = () => setShow(false);
  const handleShow = () => setShow(true);
  return (
    <>
      <Button variant="primary" onClick={handleShow}>
        Launch demo modal
      </Button>

      <Modal show={show} onHide={handleClose} animation={false}>
        <Modal.Header closeButton>
          <Modal.Title>Modal heading</Modal.Title>
        </Modal.Header>
        <Modal.Body>Woohoo, you're reading this text in a modal!</Modal.Body>
        <Modal.Footer>
          <Button variant="secondary" onClick={handleClose}>
            Close
          </Button>
          <Button variant="primary" onClick={handleClose}>
            Save Changes
          </Button>
        </Modal.Footer>
      </Modal>
    </>
  );
}

and You can convert it into the class component

import React, { Component } from "react";
import { Button, Modal } from "react-bootstrap";


export default class exampleextends Component {
  constructor(props) {
    super(props);
    this.state = {
      show: false,
      close: false,
    };
  } 
  render() {
    return (
      <div>
        <Button
          variant="none"
          onClick={() => this.setState({ show: true })}
        >
          Choose Profile
        </Button>
        <Modal
          show={this.state.show}
          animation={true}
          size="md" className="" shadow-lg border">
          <Modal.Header className="bg-danger text-white text-center py-1">
            <Modal.Title className="text-center">
              <h5>Delete</h5>
            </Modal.Title>
          </Modal.Header>
          <Modal.Body className="py-0 border">
            body   
          </Modal.Body>
<Modal.Footer className="py-1 d-flex justify-content-center">
              <div>
                <Button
                  variant="outline-dark" onClick={() => this.setState({ show: false })}>Cancel</Button>
              </div>
              <div>
                <Button variant="outline-danger" className="mx-2 px-3">Delete</Button>
              </div>
            </Modal.Footer>
        </Modal>
      </div>
    );
  }
}

How to listen state changes in react.js?

If you use hooks like const [ name , setName ] = useState (' '), you can try the following:

 useEffect(() => {
      console.log('Listening: ', name);
    }, [name]);

There is already an object named in the database

I had the same issue described in the answer that Elnaz gave. I had a requirement to change the namespace of the datalayer during a refactoring of our project. This caused the migrations to not see the existing migrations in the database. I found an excellent answer to this issue that James Chambers blogged.

http://jameschambers.com/2014/02/changing-the-namespace-with-entity-framework-6-0-code-first-databases/

I simply changed the following in the Migration configuration file.

public Configuration()
{
    AutomaticMigrationsEnabled = false;
    this.ContextKey = “Old_Namespace.Migrations.Configuration”;
}

Hope this helps someone else in a bind.

ValueError: max() arg is an empty sequence

I realized that I was iterating over a list of lists where some of them were empty. I fixed this by adding this preprocessing step:

tfidfLsNew = [x for x in tfidfLs if x != []]

the len() of the original was 3105, and the len() of the latter was 3101, implying that four of my lists were completely empty. After this preprocess my max() min() etc. were functioning again.

Callback when DOM is loaded in react.js

You can watch your container element using the useRef hook. Note that you need to watch the ref's current value specifically, otherwise it won't work.

Example:

  const containerRef = useRef();
  const { current } = containerRef;

  useEffect(setLinksData, [current]);

return (
    <div ref={containerRef}>
      // your child elements...
    </div>
)

React component not re-rendering on state change

I was going through same issue in React-Native where API response & reject weren't updating states

apiCall().then(function(resp) { this.setState({data: resp}) // wasn't updating }

I solved the problem by changing function with the arrow function

apiCall().then((resp) => {
    this.setState({data: resp}) // rendering the view as expected
}

For me, it was a binding issue. Using arrow functions solved it because arrow function doesn't create its's own this, its always bounded to its outer context where it comes from

Problems with local variable scope. How to solve it?

not Error:

JSONObject json1 = getJsonX();

Error:

JSONObject json2 = null;
if(x == y)
   json2 = getJSONX();

Error: Local variable statement defined in an enclosing scope must be final or effectively final.

But you can write:

JSONObject json2 = (x == y) ? json2 = getJSONX() : null;

Httpd returning 503 Service Unavailable with mod_proxy for Tomcat 8

Resolve issue Immediate, It's related to internal security

We, SnippetBucket.com working for enterprise linux RedHat, found httpd server don't allow proxy to run, neither localhost or 127.0.0.1, nor any other external domain.

As investigate in server log found

[error] (13)Permission denied: proxy: AJP: attempt to connect to
   10.x.x.x:8069 (virtualhost.virtualdomain.com) failed

Audit log found similar port issue

type=AVC msg=audit(1265039669.305:14): avc:  denied  { name_connect } for  pid=4343 comm="httpd" dest=8069 
scontext=system_u:system_r:httpd_t:s0 tcontext=system_u:object_r:port_t:s0 tclass=tcp_socket

Due to internal default security of linux, this cause, now to fix (temporary)

 /usr/sbin/setsebool httpd_can_network_connect 1

Resolve Permanent Issue

/usr/sbin/setsebool -P httpd_can_network_connect 1

Error "library not found for" after putting application in AdMob

Easy solution. Here's how I'd fix the issue:

  1. Go to the directory platforms/ios
  2. Then, execute the command pod install

That's it. This should install the missing library.

Apache Proxy: No protocol handler was valid

This was happening for me in my Apache/2.4.18 (Ubuntu) setup. In my case, the error I was seeing was:

... AH01144: No protocol handler was valid for the URL /~socket.io/. If you are using a DSO version of mod_proxy, make sure the proxy submodules are included in the configuration using LoadModule.

The configuration related to this was:

  ProxyPass /~socket.io/ ws://127.0.0.1:8090/~socket.io/
  ProxyPassReverse /~socket.io/ ws://127.0.0.1:8090/~socket.io/

"No protocol handler was valid for the URL /~socket.io/" meant that Apache could not handle the request being sent to "ws://127.0.0.1:8090/~socket.io/"

I had proxy_http loaded, but also needed proxy_wstunnel. Once that was enabled all was good.

Does this app use the Advertising Identifier (IDFA)? - AdMob 6.8.0

In app store connect now if we are using ads in our app then we will answer as yes to Does this app use the Advertising Identifier (IDFA)?

further 3 questions will be asked as

enter image description here

if your using just admob then check the first one and leave other two unchecked. Other two options (2nd , 3rd ) will be checked if your using app flyer to show ads. all options are explained with detail here

java.lang.ClassNotFoundException: Didn't find class on path: dexpathlist

after i tried the given answers, i found out another reason for the same Exception, that i had to add the library i'm using manually to my main library through

Right click on my main library > 
Properties > 
Android > 
Go to the very bottom of the screen and click (Add) > 
Select my other library that caused the crash >
Apply

before this solution, i used the "Fix Project setup" from within the .java file in eclipse, but this did not work, so i had to add it manually here and it worked

Forbidden You don't have permission to access / on this server

Found my solution on Apache/2.2.15 (Unix).

And Thanks for answer from @QuantumHive:

First: I finded all

Order allow,deny
Deny from all

instead of

Order allow,deny

Allow from all

and then:

I setted

#
# Control access to UserDir directories.  The following is an example
# for a site where these directories are restricted to read-only.
#
#<Directory /var/www/html>
#    AllowOverride FileInfo AuthConfig Limit
#    Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
#    <Limit GET POST OPTIONS>
#        Order allow,deny
#        Allow from all
#    </Limit>
#    <LimitExcept GET POST OPTIONS>
#        Order deny,allow
#        Deny from all
#    </LimitExcept>
#</Directory>

Remove the previous "#" annotation to

#
# Control access to UserDir directories.  The following is an example
# for a site where these directories are restricted to read-only.
#
<Directory /var/www/html>
    AllowOverride FileInfo AuthConfig Limit
    Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
    <Limit GET POST OPTIONS>
        Order allow,deny
        Allow from all
    </Limit>
    <LimitExcept GET POST OPTIONS>
        Order deny,allow
        Deny from all
    </LimitExcept>
</Directory>

ps. my WebDir is: /var/www/html

MVC 5 Access Claims Identity User Data

You can also do this:

//Get the current claims principal
var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;
var claims = identity.Claims;

Update

To provide further explanation as per comments.

If you are creating users within your system as follows:

UserManager<applicationuser> userManager = new UserManager<applicationuser>(new UserStore<applicationuser>(new SecurityContext()));
ClaimsIdentity identity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

You should automatically have some Claims populated relating to you Identity.

To add customized claims after a user authenticates you can do this as follows:

var user = userManager.Find(userName, password);
identity.AddClaim(new Claim(ClaimTypes.Email, user.Email));

The claims can be read back out as Darin has answered above or as I have.

The claims are persisted when you call below passing the identity in:

AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = persistCookie }, identity);

Apache: "AuthType not set!" 500 Error

Just remove/comment the following line from your httpd.conf file (etc/httpd/conf)

Require all granted

This is needed till Apache Version 2.2 and is not required from thereon.

New xampp security concept: Access Forbidden Error 403 - Windows 7 - phpMyAdmin

A reason for this could be Skype as well! If you use the default XAMPP settings, they both would run on the same port (80). You can:

  • Turn off Skype
  • Change the XAMPP port

Apache: The requested URL / was not found on this server. Apache

In httpd.conf file you need to remove #

#LoadModule rewrite_module modules/mod_rewrite.so

after removing # line will look like this:

LoadModule rewrite_module modules/mod_rewrite.so

And Apache restart

Could not load file or assembly System.Web.Http.WebHost after published to Azure web site

I had the same problem in my Application.

System.web.http.webhost not found.

You just need to copy the system.web.http.webhost file from your main project which you run in Visual Studio and paste it into your published project bin directory.

After this it may show the same error but the directory name is changed it may be system.web.http. Follow same procedure as above. It will work after all the files are uploaded. This due to the nuget package in Visual Studio they download from the internet but on server it not able to download it.

You can find this file in your project bin directory.

MVC 4 - Return error message from Controller - Show in View

Thanks for all the replies.

I was able to solve this by doing the following:

CONTROLLER:

[HttpPost]       
public ActionResult form_edit(FormModels model)
{
  model.error_msg = model.update_content(model);
  return RedirectToAction("Form_edit", "Form", model);
}

public ActionResult form_edit(FormModels model, string searchString,string id)
{
  string test = model.selectedvalue;
  var bal = new FormModels();
  bal.Countries = bal.get_contentdetails(searchString);
  bal.selectedvalue = id;
  bal.dd_text = "content_name";
  bal.dd_value = "content_id";

  test = model.error_msg;
  ViewBag.head = "Heading";

  if (model.error_msg != null)
  {
    ModelState.AddModelError("error_msg", test);
  }

  model.error_msg = "";
  return View(bal);
}   

VIEW:

@using (Html.BeginForm("form_edit", "Form", FormMethod.Post))
{
  <table>
    <tr>
      <td>
        @ViewBag.error
        @Html.ValidationMessage("error_msg")
      </td>
    </tr>
    <tr>
      <th>
        @Html.DisplayNameFor(model => model.content_name)
        @Html.DropDownListFor(x => x.selectedvalue, new SelectList(Model.Countries, Model.dd_value, Model.dd_text), "-- Select Product--")
      </th>
    </tr>
  </table>
}

Could not load file or assembly 'System.Web.Http 4.0.0 after update from 2012 to 2013

I fixed this by reinstalling the NuGet package, which corrects broken dependencies. From the package manager, run:

Update-Package Microsoft.AspNet.WebApi -reinstall

How to highlight a selected row in ngRepeat?

I needed something similar, the ability to click on a set of icons to indicate a choice, or a text-based choice and have that update the model (2-way-binding) with the represented value and to also a way to indicate which was selected visually. I created an AngularJS directive for it, since it needed to be flexible enough to handle any HTML element being clicked on to indicate a choice.

<ul ng-repeat="vote in votes" ...>
    <li data-choice="selected" data-value="vote.id">...</li>
</ul>

Solution: http://jsfiddle.net/brandonmilleraz/5fr9V/

Will iOS launch my app into the background if it was force-quit by the user?

UPDATE2:

You can achieve this using the new PushKit framework, introduced in iOS 8. Though PushKit is used for VoIP. So your usage should be for VoIP related otherwise there is risk of app rejection. (See this answer).


UDPDATE1:

The documentation has been clarified for iOS8. The documentation can be read here. Here is a relevant excerpt:

Use this method to process incoming remote notifications for your app. Unlike the application:didReceiveRemoteNotification: method, which is called only when your app is running in the foreground, the system calls this method when your app is running in the foreground or background. In addition, if you enabled the remote notifications background mode, the system launches your app (or wakes it from the suspended state) and puts it in the background state when a push notification arrives. However, the system does not automatically launch your app if the user has force-quit it. In that situation, the user must relaunch your app or restart the device before the system attempts to launch your app automatically again.


Although this was not made clear by the WWDC video, a quick search on the developer forums turned this up:

https://devforums.apple.com/message/873265#873265 (login required)

Also keep in mind that if you kill your app from the app switcher (i.e. swiping up to kill the app) then the OS will never relaunch the app regardless of push notification or background fetch. In this case the user has to manually relaunch the app once and then from that point forward the background activities will be invoked. -pmarcos

That post was by an Apple employee so I think i can trust that this information is correct.

So it looks like when the app is killed from the app switcher (by swiping up), the app will never be launched, even for scheduled background fetches.

cannot load such file -- bundler/setup (LoadError)

I had almost precisely the same error, and was able to completely fix it simply by running:

gem install bundler

It's possible your bundler installation is corrupt or missing - that's what happened in my case. Note that if the above fails you can try:

sudo gem install bundler

...but generally you can do it without sudo.

404 Not Found The requested URL was not found on this server

For saving a file as .htaccess, when using windows, you have to open notepad and then saveas .htaccess as windows does not create files starting with a dot. That should get your .htaccess working and it'll clear up the issue.

By the way, in order to receive specific error messages set Configure::write('debug', 0); to '2' in app/config/core.php for development purposes.

A required class was missing while executing org.apache.maven.plugins:maven-war-plugin:2.1.1:war

Make sure your Java version matches the project's Java version requirement. This could be an another cause for such kinds of issues.

Apache is downloading php files instead of displaying them

I had this problem and if you actually never played with your server configuration settings, then your problem is 90% in your .htaccess file

You either modify .htaccess file LOCALLY, ore delete it (LOCALLY)

TimePicker Dialog from clicking EditText

public void onClick1(View v) {
  DatePickerDialog dialog = new DatePickerDialog(this, this, 2013, 2, 18);
  dialog.show();
}

public void onDateSet1(DatePicker view, int year1, int month1, int day1) {
  e1.setText(day1 + "/" + (month1+1) + "/" + year1);
}

jQuery load first 3 elements, click "load more" to display next 5 elements

The expression $(document).ready(function() deprecated in jQuery3.

See working fiddle with jQuery 3 here

Take into account I didn't include the showless button.

Here's the code:

JS

$(function () {
    x=3;
    $('#myList li').slice(0, 3).show();
    $('#loadMore').on('click', function (e) {
        e.preventDefault();
        x = x+5;
        $('#myList li').slice(0, x).slideDown();
    });
});

CSS

#myList li{display:none;
}
#loadMore {
    color:green;
    cursor:pointer;
}
#loadMore:hover {
    color:black;
}

WCF Service, the type provided as the service attribute values…could not be found

Change the following line in your Eval.svc file from:

<%@ ServiceHost Language="C#" Debug="true" Service="EvalServiceLibary.Eval" %> 

to:

<%@ ServiceHost Language="C#" Debug="true" Service="EvalServiceLibary.EvalService" %>

The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception

This weird error happens, when you play around with different versions of EntityFramework versions in Nuget Packages like I did.

First, Uninstall your Entity Framework DLL from NuGet packages and then Clean up app.config. By removing the entry from configSections and entity framework element.

Next, install the desired version. This should fix the problem.

WCF error - There was no endpoint listening at

I had the same issue. For me I noticed that the https is using another Certificate which was invalid in terms of expiration date. Not sure why it happened. I changed the Https port number and a new self signed cert. WCFtestClinet could connect to the server via HTTPS!

"An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page..."

I wasn't using Azure, but I got the same error locally. Using <customErrors mode="Off" /> seemed to have no effect, but checking the Application logs in Event Viewer revealed a warning from ASP.NET which contained all the detail I needed to resolve the issue.

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile)

Maybe you can add this dependency to your pom.xml. I use this method and solve the problem!

<dependency> 
    <groupId>org.apache.maven.plugins</groupId> 
    <artifactId>maven-resources-plugin</artifactId> 
    <version>2.3.2</version> 
</dependency>

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

Kind of late to the party here, but I have just been struggling with the exact same issue (symptoms) and cursing the lack of error detail reporting. It worked fine on IIS 8+ machines but Win 7 got these INSTANT HTTP 500.19 errors. For me it was as silly as having an unsupported configuration element in the config file:

 <applicationInitialization doAppInitAfterRestart="true">
  <add initializationPage="/" />
</applicationInitialization>

So while running old web.config files worked fine, I just diffed them and started chopping away at new blocks until I got the page to start loading. Had I seen this as an answer I would have gone this route immediately as I knew none of the popular solutions were relevant. So there you go :)

Android Studio - Importing external Library/Jar

I'm using Android Studio 0.5.2. So if your version is lower than mine my answer may not work for you.

3 ways to add a new Jar to your project:

  1. Menu under Files-->Project Structure
  2. Just press 'F4'
  3. under Project navigation, right clink on any java library and a context menu will show then click on 'Open Library Settings'

A Project Structure window will popup.

On the left column click on 'Libraries' then look at the right pane where there is a plus sign '+' and click on it then enter the path to your new library.

Make sure the new library is under the 'project\libs\' folder otherwise you may get a broken link when you save your project source code.

DataTables warning: Requested unknown parameter '0' from the data source for row '0'

I face this issue because I messed return keyword in custom rendering in Columns section

columns: [
    {....
        'data': function(row, type, val, meta) {
            if (row.LetterStatus)
                 return '@CultureHelper.GetCurrentCulture()' == 'ar'? row.LetterStatus.NameInArabic: row.LetterStatus.NameInEnglish;
            else row.LetterStatusID.toString();// here is the problem because I messed the Return key keyword
          },
     ......
    }

the problem in my code is because I messed the Return keyword in the else clause

so I changed it to

....
else return row.LetterStatusID.toString();// messed return keyword added
.....

auto run a bat script in windows 7 at login

To run the batch file when the VM user logs in:

Drag the shortcut--the one that's currently on your desktop--(or the batch file itself) to Start - All Programs - Startup. Now when you login as that user, it will launch the batch file.

Another way to do the same thing is to save the shortcut or the batch file in %AppData%\Microsoft\Windows\Start Menu\Programs\Startup\.

As far as getting it to run full screen, it depends a bit what you mean. You can have it launch maximized by editing your batch file like this:

start "" /max "C:\Program Files\Oracle\VirtualBox\VirtualBox.exe" --comment "VM" --startvm "12dada4d-9cfd-4aa7-8353-20b4e455b3fa"

But if VirtualBox has a truly full-screen mode (where it hides even the taskbar), you'll have to look for a command-line parameter on VirtualBox.exe. I'm not familiar with that product.

405 method not allowed Web API

For my part my POST handler was of this form:

[HttpPost("{routeParam}")]
public async Task<ActionResult> PostActuality ([FromRoute] int routeParam, [FromBody] PostData data)

I figured out that I had to swap the arguments, that is to say the body data first then the route parameter, as this:

[HttpPost("{routeParam}")]
public async Task<ActionResult> PostActuality ([FromBody] PostData data, [FromRoute] int routeParam)

Hot to get all form elements values using jQuery?

if you want get all values from form in simple array you may be do something like this.

function getValues(form) {
    var listvalues = new Array();
    var datastring = $("#" + form).serializeArray();
    var data = "{";
    for (var x = 0; x < datastring.length; x++) {
        if (data == "{") {
            data += "\"" + datastring[x].name + "\": \"" + datastring[x].value + "\"";
        }
        else {
            data += ",\"" + datastring[x].name + "\": \"" + datastring[x].value + "\"";
        }
    }
    data += "}";
    data = JSON.parse(data);
    listvalues.push(data);
    return listvalues;
};

Close a MessageBox after several seconds

DMitryG's code "get the return value of the underlying MessageBox" has a bug so the timerResult is never actually correctly returned (MessageBox.Show call returns AFTER OnTimerElapsed completes). My fix is below:

public class TimedMessageBox {
    System.Threading.Timer _timeoutTimer;
    string _caption;
    DialogResult _result;
    DialogResult _timerResult;
    bool timedOut = false;

    TimedMessageBox(string text, string caption, int timeout, MessageBoxButtons buttons = MessageBoxButtons.OK, DialogResult timerResult = DialogResult.None)
    {
        _caption = caption;
        _timeoutTimer = new System.Threading.Timer(OnTimerElapsed,
            null, timeout, System.Threading.Timeout.Infinite);
        _timerResult = timerResult;
        using(_timeoutTimer)
            _result = MessageBox.Show(text, caption, buttons);
        if (timedOut) _result = _timerResult;
    }

    public static DialogResult Show(string text, string caption, int timeout, MessageBoxButtons buttons = MessageBoxButtons.OK, DialogResult timerResult = DialogResult.None) {
        return new TimedMessageBox(text, caption, timeout, buttons, timerResult)._result;
    }

    void OnTimerElapsed(object state) {
        IntPtr mbWnd = FindWindow("#32770", _caption); // lpClassName is #32770 for MessageBox
        if(mbWnd != IntPtr.Zero)
            SendMessage(mbWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
        _timeoutTimer.Dispose();
        timedOut = true;
    }

    const int WM_CLOSE = 0x0010;
    [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
    static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
    [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
    static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
}

Session state can only be used when enableSessionState is set to true either in a configuration

This error was raised for me because of an unhandled exception thrown in the Public Sub New() (Visual Basic) constructor function of the Web Page in the code behind.

If you implement the constructor function wrap the code in a Try/Catch statement and see if it solves the problem.

Change UITableView height dynamically

for resizing my table I went with this solution in my tableview controller witch is perfectly fine:

[objectManager getObjectsAtPath:self.searchURLString
                         parameters:nil
                            success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
                                NSArray* results = [mappingResult array];
                                self.eventArray = results;
                                NSLog(@"Events number at first: %i", [self.eventArray count]);
                                CGRect newFrame = self.activityFeedTableView.frame;
                                newFrame.size.height = self.cellsHeight + 30.0;
                                self.activityFeedTableView.frame = newFrame;

                                self.cellsHeight = 0.0;

                            }
                            failure:^(RKObjectRequestOperation *operation, NSError *error) {
                                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
                                                                                message:[error localizedDescription]
                                                                               delegate:nil
                                                                      cancelButtonTitle:@"OK"
                                                                      otherButtonTitles:nil];
                                [alert show];
                                NSLog(@"Hit error: %@", error);
                            }];

The resizing part is in a method but here is just so you can see it. Now the only problem I haveis resizing the scroll view in the other view controller as I have no idea when the tableview has finished resizing. At the moment I'm doing it with performSelector: afterDelay: but this is really not a good way to do it. Any ideas?

Updating records codeigniter

In codeigniter doc if you update specific field just do this

$data = array(
    'yourfieldname' => value,
    'name' => $name,
    'date' => $date
);

$this->db->where('yourfieldname', yourfieldvalue);
$this->db->update('yourtablename', $data);

Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly 'mscorlib

I just ran into this annoying problem today. We use SmartAssembly to pack/obfuscate our .NET assemblies, but suddenly the final product wasn't working on our test systems. I didn't even think I had .NET 4.5, but apparently something installed it about a month ago.

I uninstalled 4.5 and reinstalled 4.0, and now everything is working again. Not too impressed with having blown an afternoon on this.

SpringMVC RequestMapping for GET parameters

This works in my case:

@RequestMapping(value = "/savedata",
            params = {"textArea", "localKey", "localFile"})
    @ResponseBody
    public void saveData(@RequestParam(value = "textArea") String textArea,
                         @RequestParam(value = "localKey") String localKey,
                         @RequestParam(value = "localFile") String localFile) {
}

How to pass a textbox value from view to a controller in MVC 4?

your link is generated when the page loads therefore it will always have the original value in it. You will need to set the link via javascript

You could also just wrap that in a form and have hidden fields for id, productid, and unitrate

Here's a sample for ya.

HTML

<input type="text" id="ss" value="1"/>
<br/>
<input type="submit" id="go" onClick="changeUrl()"/>
<br/>
<a id="imgUpdate"  href="/someurl?quantity=1">click me</a>

JS

function changeUrl(){
   var url = document.getElementById("imgUpdate").getAttribute('href');
   var inputValue = document.getElementById('ss').value;
   var currentQ = GiveMeTheQueryStringParameterValue("quantity",url);
    url = url.replace("quantity=" + currentQ, "quantity=" + inputValue);
document.getElementById("imgUpdate").setAttribute('href',url)
}

    function GiveMeTheQueryStringParameterValue(parameterName, input) {
    parameterName = parameterName.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + parameterName + "=([^&#]*)");
    var results = regex.exec(input);
    if (results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
}

this could be cleaned up and expanded as you need it but the example works

Error Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35

Was facing the same issue and unfortunately nothing here was working. Finally, I came across this link: https://blogs.msdn.microsoft.com/jjameson/2009/11/18/the-copy-local-bug-in-visual-studio/

Turns out the solution is sort of dumb: set copy-local for the microsoft.web.infrastructure dll to False, then set it back to True.

By the way, I think what is happening is that there are two versions of the microsoft.web.infrastructure dll, one that is pre-installed in the GAC, and another one that is now a nuget package. I think one is masking the other, hence causing issues. In my particular case, on my build server, I need it to be copied over to a folder (this folder is then zipped and sent off to deployment). I guess the system had a copy locally and just thought "nah, it'll be fine"

Error :Request header field Content-Type is not allowed by Access-Control-Allow-Headers

It is most likely due to a cross-origin request, but it may not be. For me, I had been debugging an API and had set the Access-Control-Allow-Origin to *, but it appears that recent versions of Chrome are requiring an extra header. Try prepending the following to your file if you are using PHP:

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

Make sure that you haven't already used header in another file, or you will get a nasty error. See the docs for more.

2D cross-platform game engine for Android and iOS?

I currently use Corona for business applications with great success. As far as games go, I'm under the impression that it doesn't provide the performance that some of the other cross-platform development engines do. It is worth noting that Carlos (founder of Ansca Mobile/Corona SDK) has started another company on a competing engine; Lanica Platino Engine for Appcelerator Titanium. While I haven't worked with this personally, it does look promising. Keep in mind, however, that it comes with a $999/yr price tag.

All that said, I have been researching Moai for a little while now (since I am already familiar with Lua syntax) and it does seem promising. The fact that it can compile for multiple platforms, not limited to mobile environments, is appealing.

Multimedia Fusion 2 is also a worth contender, considering the complexity of games produced and the performance realized from them. Vincere Totus Astrum (http://gamesare.com) comes to mind.

Apache shows PHP code instead of executing it

open the file

/etc/apache2/httpd.conf

and change

#LoadModule php5_module libexec/apache2/libphp5.so

into

LoadModule php5_module libexec/apache2/libphp5.so

So just uncoment the PHP module load in httpd.conf

Add CSS3 transition expand/collapse

this should work, had to try a while too.. :D

_x000D_
_x000D_
function showHide(shID) {_x000D_
  if (document.getElementById(shID)) {_x000D_
    if (document.getElementById(shID + '-show').style.display != 'none') {_x000D_
      document.getElementById(shID + '-show').style.display = 'none';_x000D_
      document.getElementById(shID + '-hide').style.display = 'inline';_x000D_
      document.getElementById(shID).style.height = '100px';_x000D_
    } else {_x000D_
      document.getElementById(shID + '-show').style.display = 'inline';_x000D_
      document.getElementById(shID + '-hide').style.display = 'none';_x000D_
      document.getElementById(shID).style.height = '0px';_x000D_
    }_x000D_
  }_x000D_
}
_x000D_
#example {_x000D_
  background: red;_x000D_
  height: 0px;_x000D_
  overflow: hidden;_x000D_
  transition: height 2s;_x000D_
  -moz-transition: height 2s;_x000D_
  /* Firefox 4 */_x000D_
  -webkit-transition: height 2s;_x000D_
  /* Safari and Chrome */_x000D_
  -o-transition: height 2s;_x000D_
  /* Opera */_x000D_
}_x000D_
_x000D_
a.showLink,_x000D_
a.hideLink {_x000D_
  text-decoration: none;_x000D_
  background: transparent url('down.gif') no-repeat left;_x000D_
}_x000D_
_x000D_
a.hideLink {_x000D_
  background: transparent url('up.gif') no-repeat left;_x000D_
}
_x000D_
Here is some text._x000D_
<div class="readmore">_x000D_
  <a href="#" id="example-show" class="showLink" onclick="showHide('example');return false;">Read more</a>_x000D_
  <div id="example" class="more">_x000D_
    <div class="text">_x000D_
      Here is some more text: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum vitae urna nulla. Vivamus a purus mi. In hac habitasse platea dictumst. In ac tempor quam. Vestibulum eleifend vehicula ligula, et cursus nisl gravida sit amet._x000D_
      Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas._x000D_
    </div>_x000D_
    <p>_x000D_
      <a href="#" id="example-hide" class="hideLink" onclick="showHide('example');return false;">Hide</a>_x000D_
    </p>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to dynamically set bootstrap-datepicker's date value?

You can use this simple method like :

qsFromDate = '2017-05-10';
$("#dtMinDate").datepicker("setDate", new Date(qsFromDate));
$('#dtMinDate').datepicker('update');

java.lang.UnsupportedClassVersionError Unsupported major.minor version 51.0

Make sure you're using the correct SDK when compiling/running and also, make sure you use source/target 1.7.

Dataset - Vehicle make/model/year (free)

These guys have an API that will give the results. It's also free to use.

http://www.carqueryapi.com

Note: they also provide data source download in xls or sql format at a premium price. but these data also provides technical specifications for all the make model and trim options.

The type or namespace name does not exist in the namespace 'System.Web.Mvc'

Running the following command in the nuget package manager fixed it for me:

update-package microsoft.aspnet.mvc -reinstall

WCF service maxReceivedMessageSize basicHttpBinding issue

Removing the name from your binding will make it apply to all endpoints, and should produce the desired results. As so:

<services>
  <service name="Service.IService">
    <clear />
    <endpoint binding="basicHttpBinding" contract="Service.IService" />
  </service>
</services>
<bindings>
  <basicHttpBinding>
    <binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
      <readerQuotas maxDepth="32" maxStringContentLength="2147483647"
        maxArrayLength="16348" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
    </binding>
  </basicHttpBinding>
  <webHttpBinding>
    <binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" />
  </webHttpBinding>
</bindings>

Also note that I removed the bindingConfiguration attribute from the endpoint node. Otherwise you would get an exception.

This same solution was found here : Problem with large requests in WCF

<modules runAllManagedModulesForAllRequests="true" /> Meaning

Modules Preconditions:

The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (precondition="managedHandler") only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:

<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />

If you remove the attribute precondition="managedHandler", Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.

You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "managedHandler" precondition.

To enable all managed modules to run for all requests without configuring each module entry to remove the "managedHandler" precondition, use the runAllManagedModulesForAllRequests property in the <modules> section:

<modules runAllManagedModulesForAllRequests="true" />    

When you use this property, the "managedHandler" precondition has no effect and all managed modules run for all requests.

Copied from IIS Modules Overview: Preconditions

How to implement and do OCR in a C# project?

Some online API's work pretty well: ocr.space and Google Cloud Vision. Both of these are free, as long as you do less than 1000 OCR's per month. You can drag & drop an image to do a quick manual test to see how they perform for your images.

I find OCR.space easier to use (no messing around with nuget libraries), but, for my purpose, Google Cloud Vision provided slightly better results than OCR.space.

Google Cloud Vision example:

GoogleCredential cred = GoogleCredential.FromJson(json);
Channel channel = new Channel(ImageAnnotatorClient.DefaultEndpoint.Host, ImageAnnotatorClient.DefaultEndpoint.Port, cred.ToChannelCredentials());
ImageAnnotatorClient client = ImageAnnotatorClient.Create(channel);
Image image = Image.FromStream(stream);

EntityAnnotation googleOcrText = client.DetectText(image).First();
Console.Write(googleOcrText.Description);

OCR.space example:

string uri = $"https://api.ocr.space/parse/imageurl?apikey=helloworld&url={imageUri}";
string responseString = WebUtilities.DoGetRequest(uri);
OcrSpaceResult result = JsonConvert.DeserializeObject<OcrSpaceResult>(responseString);
if ((!result.IsErroredOnProcessing) && !String.IsNullOrEmpty(result.ParsedResults[0].ParsedText))
  return result.ParsedResults[0].ParsedText;

Error message "Forbidden You don't have permission to access / on this server"

This article Creating virtual hosts on Apache 2.2 helps me (point 9) permissions to the top virtual hosts directory.

I simply add this lines to my vhosts.conf file:

<Directory I:/projects/webserver>
    Order Deny,Allow
    Allow from all
</Directory>

IIS7 - The request filtering module is configured to deny a request that exceeds the request content length

<configuration>
    <system.web>
        <httpRuntime maxRequestLength="1048576" />
    </system.web>
</configuration>

From here.

For IIS7 and above, you also need to add the lines below:

 <system.webServer>
   <security>
      <requestFiltering>
         <requestLimits maxAllowedContentLength="1073741824" />
      </requestFiltering>
   </security>
 </system.webServer>

Using GregorianCalendar with SimpleDateFormat

A SimpleDateFormat, as its name indicates, formats Dates. Not a Calendar. So, if you want to format a GregorianCalendar using a SimpleDateFormat, you must convert the Calendar to a Date first:

dateFormat.format(calendar.getTime());

And what you see printed is the toString() representation of the calendar. It's intended usage is debugging. It's not intended to be used to display a date in a GUI. For that, use a (Simple)DateFormat.

Finally, to convert from a String to a Date, you should also use a (Simple)DateFormat (its parse() method), rather than splitting the String as you're doing. This will give you a Date object, and you can create a Calendar from the Date by instanciating it (Calendar.getInstance()) and setting its time (calendar.setTime()).

My advice would be: Googling is not the solution here. Reading the API documentation is what you need to do.

error: the details of the application error from being viewed remotely

This can be the message you receive even when custom errors is turned off in web.config file. It can mean you have run out of free space on the drive that hosts the application. Clean your log files if you have no other space to gain on the drive.

The Completest Cocos2d-x Tutorial & Guide List

Here you got complementaries discussions about the topic, it can be interesting.

discussion1

discussion2

Assign a synthesizable initial value to a reg in Verilog

The always @* would never trigger as no Right hand arguments change. Why not use a wire with assign?

module top (
    input wire clk,
    output wire [7:0] led   
);

wire [7:0] data_reg ; 
assign data_reg   = 8'b10101011;
assign led        = data_reg;

endmodule

If you actually want a flop where you can change the value, the default would be in the reset clause.

module top
(
    input        clk,
    input        rst_n,
    input  [7:0] data,
    output [7:0] led   
 );

reg [7:0] data_reg ; 
always @(posedge clk or negedge rst_n) begin
  if (!rst_n)
    data_reg <= 8'b10101011;
  else
    data_reg <= data ; 
end

assign led = data_reg;

endmodule

Hope this helps

Write a file in UTF-8 using FileWriter (Java)?

Since Java 7 there is an easy way to handle character encoding of BufferedWriter and BufferedReaders. You can create a BufferedWriter directly by using the Files class instead of creating various instances of Writer. You can simply create a BufferedWriter, which considers character encoding, by calling:

Files.newBufferedWriter(file.toPath(), StandardCharsets.UTF_8);

You can find more about it in JavaDoc:

Insert variable into Header Location PHP

like this?

<?php
$url_endpoint = get_permalink();
$url_endpoint = parse_url( $url_endpoint );
$url_endpoint = $url_endpoint['path'];

header('Location: http://linkhere.com/'. $url_endpoint);

?>

support FragmentPagerAdapter holds reference to old fragments

Global working tested solution.

getSupportFragmentManager() keeps the null reference some times and View pager does not create new since it find reference to same fragment. So to over come this use getChildFragmentManager() solves problem in simple way.

Don't do this:

new PagerAdapter(getSupportFragmentManager(), fragments);

Do this:

new PagerAdapter(getChildFragmentManager() , fragments);

HTTP 404 Page Not Found in Web Api hosted in IIS 7.5

Ensure that not selected Solution -> Project -> Right click Properties -> Application -> Auto-generate binding redirects

How to call URL action in MVC with javascript function?

I'm going to give you 2 way's to call an action from the client side

first

If you just want to navigate to an action you should call just use the follow

window.location = "/Home/Index/" + youid

Notes: that you action need to handle a get type called

Second

If you need to render a View you could make the called by ajax

//this if you want get the html by get
public ActionResult Foo()
{
    return View(); //this return the render html   
}

And the client called like this "Assuming that you're using jquery"

$.get('your controller path', parameters to the controler , function callback)

or

$.ajax({
    type: "GET",
    url: "your controller path",
    data: parameters to the controler
    dataType: "html",
    success: your function
});

or

$('your selector').load('your controller path') 

Update

In your ajax called make this change to pass the data to the action

function onDropDownChange(e) {
var url = '/Home/Index' 
$.ajax({
        type: "GET",
        url: url,
        data: { id = e.value}, <--sending the values to the server
        dataType: "html",
        success : function (data) {
            //put your code here
        }
    });
}

UPDATE 2

You cannot do this in your callback 'windows.location ' if you want it's go render a view, you need to put a div in your view and do something like this

in the view where you are that have the combo in some place

<div id="theNewView"> </div> <---you're going to load the other view here

in the javascript client

$.ajax({
        type: "GET",
        url: url,
        data: { id = e.value}, <--sending the values to the server
        dataType: "html",
        success : function (data) {
            $('div#theNewView').html(data);
        }
    });
}

With this i think that you solve your problem

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated

I had the same issue and resolved by adding "Connection Time" value in web.config file. locate the connectionStrings and add Connection Timeout=3600"

here is the sample

  <connectionStrings>
    <add name="MyConn" providerName="System.Data.SqlClient" connectionString="Data Source=MySQLServer;Initial Catalog=MyDB;User ID=sa;Password=123;Connection Timeout=3600" />
  </connectionStrings>

How can I make my website's background transparent without making the content (images & text) transparent too?

I would agree with @evillinux, It would be best to make your background image semi transparent so it supports < ie8

The other suggestions of using another div are also a great option, and it's the way to go if you want to do this in css. For example if the site had such features as selecting your own background color. I would suggest using a filter for older IE. eg:

filter:Alpha(opacity=50)

apache mod_rewrite is not working or not enabled

Please try

sudo a2enmod rewrite

or use correct apache restart command

sudo /etc/init.d/apache2 restart 

The 'packages' element is not declared

Taken from this answer.

  1. Close your packages.config file.
  2. Build
  3. Warning is gone!

This is the first time I see ignoring a problem actually makes it go away...

Edit in 2020: if you are viewing this warning, consider upgrading to PackageReference if you can

how to solve Error cannot add duplicate collection entry of type add with unique key attribute 'value' in iis 7

For me in windows server 2012 R2 I solved it by removing the duplicates from web.config file i found this line duplicated twice i removed one line and kept the other line

<add name="CrystalImageHandler.aspx_GET" verb="GET" path="CrystalImageHandler.aspx" type="CrystalDecisions.Web.CrystalImageHandler, CrystalDecisions.Web, Version=13.0.4000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" preCondition="integratedMode"/></handlers><validation validateIntegratedModeConfiguration="false"/>

How do I decode a base64 encoded string?

Simple:

byte[] data = Convert.FromBase64String(encodedString);
string decodedString = Encoding.UTF8.GetString(data);

How to add external library in IntelliJ IDEA?

Easier procedure on latest versions:

  • Copy jar to libs directory in the app (you can create the directory it if not there)
  • Refresh project so libs show up in the structure (right click on project top level, refresh/synchronize)
  • Expand libs and right click on the jar
  • Select "Add as Library"

Done

What is the purpose of a plus symbol before a variable?

The + operator returns the numeric representation of the object. So in your particular case, it would appear to be predicating the if on whether or not d is a non-zero number.

Reference here. And, as pointed out in comments, here.

Check date with todays date

to check if a date is today's date or not only check for dates not time included with that so make time 00:00:00 and use the code below

    Calendar c = Calendar.getInstance();

    // set the calendar to start of today
    c.set(Calendar.HOUR_OF_DAY, 0);
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.SECOND, 0);
    c.set(Calendar.MILLISECOND, 0);

    Date today = c.getTime();

    // or as a timestamp in milliseconds
    long todayInMillis = c.getTimeInMillis();


    int dayOfMonth = 24;
    int month = 4;
    int year =2013;

    // reuse the calendar to set user specified date
    c.set(Calendar.YEAR, year);
    c.set(Calendar.MONTH, month - 1);
    c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
    c.set(Calendar.HOUR_OF_DAY, 0);
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.SECOND, 0);
    c.set(Calendar.MILLISECOND, 0);
    // and get that as a Date
    Date dateSpecified = c.getTime();

    // test your condition
    if (dateSpecified.before(today)) {

        Log.v(" date is previou")
    } else if (dateSpecified.equal(today)) {

        Log.v(" date is today ")
    } 
             else if (dateSpecified.after(today)) {

        Log.v(" date is future date ")
    } 

Hope it will help....

Add/Delete table rows dynamically using JavaScript

Here Is full code with HTML,CSS and JS.

<style><style id='generate-style-inline-css' type='text/css'>
    body {
        background-color: #efefef;
        color: #3a3a3a;
    }

    a,
    a:visited {
        color: #1e73be;
    }

    a:hover,
    a:focus,
    a:active {
        color: #000000;
    }

    body .grid-container {
        max-width: 1200px;
    }

    body,
    button,
    input,
    select,
    textarea {
        font-family: "Open Sans", sans-serif;
    }

    .entry-content>[class*="wp-block-"]:not(:last-child) {
        margin-bottom: 1.5em;
    }

    .main-navigation .main-nav ul ul li a {
        font-size: 14px;
    }

    @media (max-width:768px) {
        .main-title {
            font-size: 30px;
        }
        h1 {
            font-size: 30px;
        }
        h2 {
            font-size: 25px;
        }
    }

    .top-bar {
        background-color: #636363;
        color: #ffffff;
    }

    .top-bar a,
    .top-bar a:visited {
        color: #ffffff;
    }

    .top-bar a:hover {
        color: #303030;
    }

    .site-header {
        background-color: #ffffff;
        color: #3a3a3a;
    }

    .site-header a,
    .site-header a:visited {
        color: #3a3a3a;
    }

    .main-title a,
    .main-title a:hover,
    .main-title a:visited {
        color: #222222;
    }

    .site-description {
        color: #757575;
    }

    .main-navigation,
    .main-navigation ul ul {
        background-color: #222222;
    }

    .main-navigation .main-nav ul li a,
    .menu-toggle {
        color: #ffffff;
    }

    .main-navigation .main-nav ul li:hover>a,
    .main-navigation .main-nav ul li:focus>a,
    .main-navigation .main-nav ul li.sfHover>a {
        color: #ffffff;
        background-color: #3f3f3f;
    }

    button.menu-toggle:hover,
    button.menu-toggle:focus,
    .main-navigation .mobile-bar-items a,
    .main-navigation .mobile-bar-items a:hover,
    .main-navigation .mobile-bar-items a:focus {
        color: #ffffff;
    }

    .main-navigation .main-nav ul li[class*="current-menu-"]>a {
        color: #ffffff;
        background-color: #3f3f3f;
    }

    .main-navigation .main-nav ul li[class*="current-menu-"]>a:hover,
    .main-navigation .main-nav ul li[class*="current-menu-"] .sfHover>a {
        color: #ffffff;
        background-color: #3f3f3f;
    }

    .navigation-search input[type="search"],
    .navigation-search input[type="search"]:active {
        color: #3f3f3f;
        background-color: #3f3f3f;
    }

    .navigation-search input[type="search"]:focus {
        color: #ffffff;
        background-color: #3f3f3f;
    }

    .main-navigation ul ul {
        background-color: #3f3f3f;
    }

    .main-navigation .main-nav ul ul li a {
        color: #ffffff;
    }

    .main-navigation .main-nav ul ul li:hover>a,
    .main-navigation .main-nav ul ul li:focus>a,
    .main-navigation .main-nav ul ul li.sfHover>a {
        color: #ffffff;
        background-color: #4f4f4f;
    }

    .main-navigation . main-nav ul ul li[class*="current-menu-"]>a {
        color: #ffffff;
        background-color: #4f4f4f;
    }

    .main-navigation .main-nav ul ul li[class*="current-menu-"]>a:hover,
    .main-navigation .main-nav ul ul li[class*="current-menu-"] .sfHover>a {
        color: #ffffff;
        background-color: #4f4f4f;
    }

    .separate-containers .inside-article,
    .separate-containers .comments-area,
    .separate-containers .page-header,
    .one-container .container,
    .separate-containers .paging-navigation,
    .inside-page-header {
        background-color: #ffffff;
    }

    .entry-meta {
        color: #595959;
    }

    .entry-meta a,
    .entry-meta a:visited {
        color: #595959;
    }

    .entry-meta a:hover {
        color: #1e73be;
    }

    .sidebar .widget {
        background-color: #ffffff;
    }

    .sidebar .widget .widget-title {
        color: #000000;
    }

    .footer-widgets {
        background-color: #ffffff;
    }

    .footer-widgets .widget-title {
        color: #000000;
    }

    .site-info {
        color: #ffffff;
        background-color: #222222;
    }

    .site-info a,
    .site-info a:visited {
        color: #ffffff;
    }

    .site-info a:hover {
        color: #606060;
    }

    .footer-bar .widget_nav_menu .current-menu-item a {
        color: #606060;
    }

    input[type="text"],
    input[type="email"],
    input[type="url"],
    input[type="password"],
    input[type="search"],
    input[type="tel"],
    input[type="number"],
    textarea,
    select {
        color: #666666;
        background-color: #fafafa;
        border-color: #cccccc;
    }

    input[type="text"]:focus,
    input[type="email"]:focus,
    input[type="url"]:focus,
    input[type="password"]:focus,
    input[type="search"]:focus,
    input[type="tel"]:focus,
    input[type="number"]:focus,
    textarea:focus,
    select:focus {
        color: #666666;
        background-color: #ffffff;
        border-color: #bfbfbf;
    }

    button,
    html input[type="button"],
    input[type="reset"],
    input[type="submit"],
    a.button,
    a.button:visited,
    a.wp-block-button__link:not(.has-background) {
        color: #ffffff;
        background-color: #666666;
    }

    button:hover,
    html input[type="button"]:hover,
    input[type="reset"]:hover,
    input[type="submit"]:hover,
    a.button:hover,
    button:focus,
    html input[type="button"]:focus,
    input[type="reset"]:focus,
    input[type="submit"]:focus,
    a.button:focus,
    a.wp-block-button__link:not(.has-background):active,
    a.wp-block-button__link:not(.has-background):focus,
    a.wp-block-button__link:not(.has-background):hover {
        color: #ffffff;
        background-color: #3f3f3f;
    }

    .generate-back-to-top,
    .generate-back-to-top:visited {
        background-color: rgba( 0, 0, 0, 0.4);
        color: #ffffff;
    }

    .generate-back-to-top:hover,
    .generate-back-to-top:focus {
        background-color: rgba( 0, 0, 0, 0.6);
        color: #ffffff;
    }

    .entry-content .alignwide,
    body:not(.no-sidebar) .entry-content .alignfull {
        margin-left: -40px;
        width: calc(100% + 80px);
        max-width: calc(100% + 80px);
    }

    @media (max-width:768px) {
        .separate-containers .inside-article,
        .separate-containers .comments-area,
        .separate-containers .page-header,
        .separate-containers .paging-navigation,
        .one-container .site-content,
        .inside-page-header {
            padding: 30px;
        }
        .entry-content .alignwide,
        body:not(.no-sidebar) .entry-content .alignfull {
            margin-left: -30px;
            width: calc(100% + 60px);
            max-width: calc(100% + 60px);
        }
    }

    .rtl .menu-item-has-children .dropdown-menu-toggle {
        padding-left: 20px;
    }

    .rtl .main-navigation .main-nav ul li.menu-item-has-children>a {
        padding-right: 20px;
    }

    .one-container .sidebar .widget {
        padding: 0px;
    }

    .append_row {
        color: black !important;
        background-color: #FFD6D6 !important;
        border: 1px #ccc solid !important;
    }

    .append_column {
        color: black !important;
        background-color: #D6FFD6 !important;
        border: 1px #ccc solid !important;
    }

    table#my-table td {
        width: 50px;
        height: 27px;
        border: 1px solid #D3D3D3;
        text-align: center;
        padding: 0;
    }

    div#my-container input {
        padding: 5px;
        font-size: 12px !important;
        width: 100px;
        margin: 2px;
    }

    .row {
        background-color: #FFD6D6 !important;
    }

    .col {
        background-color: #D6FFD6 !important;
    }
    </style>
    <script src="https://code.jquery.com/jquery-1.11.0.js"></script>
    <script>

    // append row to the HTML table
    function appendRow() {
        var tbl = document.getElementById('my-table'), // table reference
            row = tbl.insertRow(tbl.rows.length),      // append table row
            i;
        // insert table cells to the new row
        for (i = 0; i < tbl.rows[0].cells.length; i++) {
            createCell(row.insertCell(i), i, 'row');
        }
    }

    // create DIV element and append to the table cell
    function createCell(cell, text, style) {
        var div = document.createElement('div'), // create DIV element
            txt = document.createTextNode(text); // create text node
        div.appendChild(txt);                    // append text node to the DIV
        div.setAttribute('class', style);        // set DIV class attribute
        div.setAttribute('className', style);    // set DIV class attribute for IE (?!)
        cell.appendChild(div);                   // append DIV to the table cell
    }

    // append column to the HTML table
    function appendColumn() {
        var tbl = document.getElementById('my-table'), // table reference
            i;
        // open loop for each row and append cell
        for (i = 0; i < tbl.rows.length; i++) {
            createCell(tbl.rows[i].insertCell(tbl.rows[i].cells.length), i, 'col');
        }
    }

    // delete table rows with index greater then 0
    function deleteRows() {
        var tbl = document.getElementById('my-table'), // table reference
            lastRow = tbl.rows.length - 1,             // set the last row index
            i;
        // delete rows with index greater then 0
        for (i = lastRow; i > 0; i--) {
            tbl.deleteRow(i);
        }
    }

    // delete table columns with index greater then 0
    function deleteColumns() {
        var tbl = document.getElementById('my-table'), // table reference
            lastCol = tbl.rows[0].cells.length - 1,    // set the last column index
            i, j;
        // delete cells with index greater then 0 (for each row)
        for (i = 0; i < tbl.rows.length; i++) {
            for (j = lastCol; j > 0; j--) {
                tbl.rows[i].deleteCell(j);
            }
        }
    }
    </script>
    <div id="my-container">
    <center><br>
    <input type="button" value="Add row" onclick="javascript:appendRow()" class="append_row"><br>
    <input type="button" value="Add column" onclick="javascript:appendColumn()" class="append_column"><br>
    <input type="button" value="Delete rows" onclick="javascript:deleteRows()" class="delete"><br>
    <input type="button" value="Delete columns" onclick="javascript:deleteColumns()" class="delete"><br>
    <input type="button" value="Delete both" onclick="javascript:deleteColumns();deleteRows()" class="delete"><p></p>
    <table id="my-table" align="center" cellspacing="0" cellpadding="0" border="0">
    <tbody><tr>
    <td>Small</td>
    </tr>
    </tbody></table>
    <p></p></center>
    </div>

Mixed mode assembly is built against version ‘v2.0.50727' of the runtime

I actually had this identical issue with the inverse solution. I had upgraded a .NET project to .NET 4.0 and then reverted back to .NET 3.5. The app.config in my project continued to have the following which was causing the above error in question:

<startup>
  <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>

The solution to solve the error for this was to revert it back to the proper 2.0 reference as follows:

<startup>
  <supportedRuntime version="v2.0.50727"/>
</startup>

So if a downgrade is producing the above error, you might need to back up the .NET Framework supported version.

"405 method not allowed" in IIS7.5 for "PUT" method

If IIS app pool is running under classic mode, make sure you have the following in your web.config

<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />

    <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE" modules="IsapiModule" scriptProcessor="c:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" />

How to draw in JPanel? (Swing/graphics Java)

Note the extra comments.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

class JavaPaintUI extends JFrame {

    private int tool = 1;
    int currentX, currentY, oldX, oldY;

    public JavaPaintUI() {
        initComponents();
    }

    private void initComponents() {
        // we want a custom Panel2, not a generic JPanel!
        jPanel2 = new Panel2();

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));
        jPanel2.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
        jPanel2.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent evt) {
                jPanel2MousePressed(evt);
            }
            public void mouseReleased(MouseEvent evt) {
                jPanel2MouseReleased(evt);
            }
        });
        jPanel2.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseDragged(MouseEvent evt) {
                jPanel2MouseDragged(evt);
            }
        });

        // add the component to the frame to see it!
        this.setContentPane(jPanel2);
        // be nice to testers..
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
    }// </editor-fold>

    private void jPanel2MouseDragged(MouseEvent evt) {
        if (tool == 1) {
            currentX = evt.getX();
            currentY = evt.getY();
            oldX = currentX;
            oldY = currentY;
            System.out.println(currentX + " " + currentY);
            System.out.println("PEN!!!!");
        }
    }

    private void jPanel2MousePressed(MouseEvent evt) {
        oldX = evt.getX();
        oldY = evt.getY();
        System.out.println(oldX + " " + oldY);
    }


    //mouse released//
    private void jPanel2MouseReleased(MouseEvent evt) {
        if (tool == 2) {
            currentX = evt.getX();
            currentY = evt.getY();
            System.out.println("line!!!! from" + oldX + "to" + currentX);
        }
    }

    //set ui visible//
    public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                new JavaPaintUI().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private JPanel jPanel2;
    // End of variables declaration

    // This class name is very confusing, since it is also used as the
    // name of an attribute!
    //class jPanel2 extends JPanel {
    class Panel2 extends JPanel {

        Panel2() {
            // set a preferred size for the custom panel.
            setPreferredSize(new Dimension(420,420));
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);

            g.drawString("BLAH", 20, 20);
            g.drawRect(200, 200, 200, 200);
        }
    }
}

Screen Shot

enter image description here

Other examples - more tailored to multiple lines & multiple line segments

HFOE put a good link as the first comment on this thread. Camickr also has a description of active painting vs. drawing to a BufferedImage in the Custom Painting Approaches article.

See also this approach using painting in a BufferedImage.

How to completely hide the navigation bar in iPhone / HTML5

Simple javascript document navigation to "#" will do it.

window.onload = function()
{
document.location.href = "#";
}

This will force the navigation bar to remove itself on load.

Web.Config Debug/Release

It is possible using ConfigTransform build target available as a Nuget package - https://www.nuget.org/packages/CodeAssassin.ConfigTransform/

All "web.*.config" transform files will be transformed and output as a series of "web.*.config.transformed" files in the build output directory regardless of the chosen build configuration.

The same applies to "app.*.config" transform files in non-web projects.

and then adding the following target to your *.csproj.

<Target Name="TransformActiveConfiguration" Condition="Exists('$(ProjectDir)/Web.$(Configuration).config')" BeforeTargets="Compile" >
    <TransformXml Source="$(ProjectDir)/Web.Config" Transform="$(ProjectDir)/Web.$(Configuration).config" Destination="$(TargetDir)/Web.config" />
</Target>

Posting an answer as this is the first Stackoverflow post that appears in Google on the subject.

How do I remove documents using Node.js Mongoose?

UPDATE: Mongoose version (5.5.3)

remove() is deprecated and you can use deleteOne(), deleteMany(), or bulkWrite() instead.

As of "mongoose": ">=2.7.1" you can remove the document directly with the .remove() method rather than finding the document and then removing it which seems to me more efficient and easy to maintain.

See example:

Model.remove({ _id: req.body.id }, function(err) {
    if (!err) {
            message.type = 'notification!';
    }
    else {
            message.type = 'error';
    }
});

UPDATE:

As of mongoose 3.8.1, there are several methods that lets you remove directly a document, say:

  • remove
  • findByIdAndRemove
  • findOneAndRemove

Refer to mongoose API docs for further information.

ModelState.AddModelError - How can I add an error that isn't for a property?

You can add the model error on any property of your model, I suggest if there is nothing related to create a new property.

As an exemple we check if the email is already in use in DB and add the error to the Email property in the action so when I return the view, they know that there's an error and how to show it up by using

<%: Html.ValidationSummary(true)%>
<%: Html.ValidationMessageFor(model => model.Email) %>

and

ModelState.AddModelError("Email", Resources.EmailInUse);

An item with the same key has already been added

I had the same issue , i was foreach looping over my object and adding the result into a Dictionary<string, string> and i had a `Duplicate in the key from the database

 foreach (var item in myObject)
        {
            myDictionary.Add(Convert.ToString(item.x), 
                                   item.y);

        }

item.x had a duplicate value

Configure hibernate to connect to database via JNDI Datasource

Tomcat-7 JNDI configuration:

Steps:

  1. Open the server.xml in the tomcat-dir/conf
  2. Add below <Resource> tag with your DB details inside <GlobalNamingResources>
<Resource name="jdbc/mydb"
          global="jdbc/mydb"
          auth="Container"
          type="javax.sql.DataSource"
          driverClassName="com.mysql.jdbc.Driver"
          url="jdbc:mysql://localhost:3306/test"
          username="root"
          password=""
          maxActive="10"
          maxIdle="10"
          minIdle="5"
          maxWait="10000"/>
  1. Save the server.xml file
  2. Open the context.xml in the tomcat-dir/conf
  3. Add the below <ResourceLink> inside the <Context> tag.
<ResourceLink name="jdbc/mydb" 
              global="jdbc/mydb"
              auth="Container"
              type="javax.sql.DataSource" />
  1. Save the context.xml
  2. Open the hibernate-cfg.xml file and add and remove below properties.
Adding:
-------
<property name="connection.datasource">java:comp/env/jdbc/mydb</property>

Removing:
--------
<!--<property name="connection.url">jdbc:mysql://localhost:3306/mydb</property> -->
<!--<property name="connection.username">root</property> -->
<!--<property name="connection.password"></property> -->
  1. Save the file and put latest .WAR file in tomcat.
  2. Restart the tomcat. the DB connection will work.

Convert String to Calendar Object in Java

SimpleDateFormat is great, just note that HH is different from hh when working with hours. HH will return 24 hour based hours and hh will return 12 hour based hours.

For example, the following will return 12 hour time:

SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");

While this will return 24 hour time:

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");

How to install mod_ssl for Apache httpd?

Try installing mod_ssl using following command:

yum install mod_ssl

and then reload and restart your Apache server using following commands:

systemctl reload httpd.service
systemctl restart httpd.service

This should work for most of the cases.

The type arguments cannot be inferred from the usage. Try specifying the type arguments explicitly

In your example, the compiler has no way of knowing what type should TModel be. You could do something close to what you are probably trying to do with an extension method.

static class ModelExtensions
{
   public static IDictionary<string, object> GetHtmlAttributes<TModel, TProperty>
      (this TModel model, Expression<Func<TModel, TProperty>> propertyExpression)
   {
       return new Dictionary<string, object>();
   }
}

But you wouldn't be able to have anything similar to virtual, I think.

EDIT:

Actually, you can do virtual, using self-referential generics:

class ModelBase<TModel>
{
    public virtual IDictionary<string, object> GetHtmlAttributes<TProperty>
        (Expression<Func<TModel, TProperty>> propertyExpression)
    {
        return new Dictionary<string, object>();
    }
}

class FooModel : ModelBase<FooModel>
{
    public override IDictionary<string, object> GetHtmlAttributes<TProperty>
        (Expression<Func<FooModel, TProperty>> propertyExpression)
    {
        return new Dictionary<string, object> { { "foo", "bar" } };
    }
}

How can I get device ID for Admob

To get the Hash Device ID

inside the oncreate

String android_id = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
        String deviceId = md5(android_id).toUpperCase();
Log.i("device id=",deviceId);

then add this class for md5 ()

public String md5(String s) {
        try {
            // Create MD5 Hash
            MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
            digest.update(s.getBytes());
            byte messageDigest[] = digest.digest();

            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            for (int i=0; i<messageDigest.length; i++)
                hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

How to use .htaccess in WAMP Server?

RewriteEngine on
RewriteBase /basic_test/

RewriteRule ^index.php$ test.php

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode

I ran into this problem and inspired by @Jeremy Cook's answer, I bit the bullet to find out what the heck caused IIS 7 Integrated mode to not like my web.config. Here's my scenario:

  1. Web API (version 4.0.030506.0 aka the old one)
  2. .NET 4.0
  3. Attribute Routing 3.5.6 for Web API [spoiler alert: it was this guy!]

I wanted to use attribute routing in a project that (unfortunately) had to use .NET 4 and hence could not use Web API 2.2 (which needs .NET 4.5). The well meaning NuGet package added this section under the <system.web> section:

<system.web>
<httpHandlers>
      <add verb="*" path="routes.axd" type="AttributeRouting.Web.Logging.LogRoutesHandler, AttributeRouting.Web" />
    </httpHandlers>
</system.web>

[I say well meaning, because this part is required on older versions of IIS]

Removing this section got me past the HTTP 500.23!!

Summary: I second Jeremy's words that it is important to understand why things don't work rather than just "masking the symptom". Even if you have to mask the symptom, you know what you are doing (and why) :-)

mappedBy reference an unknown target entity property

public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "USER_ID")
    Long userId;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "sender", cascade = CascadeType.ALL)
    List<Notification> sender;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "receiver", cascade = CascadeType.ALL)
    List<Notification> receiver;
}

public class Notification implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id

    @Column(name = "NOTIFICATION_ID")
    Long notificationId;

    @Column(name = "TEXT")
    String text;

    @Column(name = "ALERT_STATUS")
    @Enumerated(EnumType.STRING)
    AlertStatus alertStatus = AlertStatus.NEW;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "SENDER_ID")
    @JsonIgnore
    User sender;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "RECEIVER_ID")
    @JsonIgnore
    User receiver;
}

What I understood from the answer. mappedy="sender" value should be the same in the notification model. I will give you an example..

User model:

@OneToMany(fetch = FetchType.LAZY, mappedBy = "**sender**", cascade = CascadeType.ALL)
    List<Notification> sender;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "**receiver**", cascade = CascadeType.ALL)
    List<Notification> receiver;

Notification model:

@OneToMany(fetch = FetchType.LAZY, mappedBy = "sender", cascade = CascadeType.ALL)
    List<Notification> **sender**;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "receiver", cascade = CascadeType.ALL)
    List<Notification> **receiver**;

I gave bold font to user model and notification field. User model mappedBy="sender " should be equal to notification List sender; and mappedBy="receiver" should be equal to notification List receiver; If not, you will get error.

Mobile Redirect using htaccess

Or you may try this:

?php

/**
* Mobile Detect
* @license    http://www.opensource.org/licenses/mit-license.php The MIT License
*/
class Mobile_Detect
{
    protected $accept;
    protected $userAgent;
    protected $isMobile = false;
    protected $isAndroid = null;
    protected $isAndroidtablet = null;
    protected $isIphone = null;
    protected $isIpad = null;
    protected $isBlackberry = null;
    protected $isBlackberrytablet = null;
    protected $isOpera = null;
    protected $isPalm = null;
    protected $isWindows = null;
    protected $isWindowsphone = null;
    protected $isGeneric = null;
    protected $devices = array(
    "android" => "android.*mobile",
    "androidtablet" => "android(?!.*mobile)",
    "blackberry" => "blackberry",
    "blackberrytablet" => "rim tablet os",
    "iphone" => "(iphone|ipod)",
    "ipad" => "(ipad)",
    "palm" => "(avantgo|blazer|elaine|hiptop|palm|plucker|xiino)",
    "windows" => "windows ce; (iemobile|ppc|smartphone)",
    "windowsphone" => "windows phone os",
    "generic" => "(kindle|mobile|mmp|midp|pocket|psp|symbian|smartphone|treo|up.browser|up.link|vodafone|wap|opera mini)");

    public function __construct()
    {
        $this->userAgent = $_SERVER['HTTP_USER_AGENT'];
        $this->accept = $_SERVER['HTTP_ACCEPT'];

        if (isset($_SERVER['HTTP_X_WAP_PROFILE']) || isset($_SERVER['HTTP_PROFILE']))
        {
            $this->isMobile = true;
        }
        elseif (strpos($this->accept, 'text/vnd.wap.wml') > 0 || strpos($this->accept, 'application/vnd.wap.xhtml+xml') > 0)
        {
            $this->isMobile = true;
        }
        else
        {
            foreach ($this->devices as $device => $regexp)
            {
                if ($this->isDevice($device))
                {
                    $this->isMobile = true;
                }
            }
        }
    }

    /**
    * Overloads isAndroid() | isAndroidtablet() | isIphone() | isIpad() | isBlackberry() | isBlackberrytablet() | isPalm() | isWindowsphone() | isWindows() | isGeneric() through isDevice()
    *
    * @param string $name
    * @param array $arguments
    * @return bool
    */
    public function __call($name, $arguments)
    {
        $device = substr($name, 2);
        if ($name == "is" . ucfirst($device) && array_key_exists(strtolower($device), $this->devices))
        {
            return $this->isDevice($device);
        } 
        else
        {
            trigger_error("Method $name not defined", E_USER_WARNING);
        }
    }

    /**
    * Returns true if any type of mobile device detected, including special ones
    * @return bool
    */
    public function isMobile()
    {
        return $this->isMobile;
    }

    protected function isDevice($device)
    {
        $var = "is" . ucfirst($device);
        $return = $this->$var === null ? (bool) preg_match("/" . $this->devices[strtolower($device)] . "/i", $this->userAgent) : $this->$var;
        if ($device != 'generic' && $return == true) {
        $this->isGeneric = false;
    }
    return $return;
}

ASP.NET MVC Html.ValidationSummary(true) does not display model errors

I believe the way the ValidationSummary flag works is it will only display ModelErrors for string.empty as the key. Otherwise it is assumed it is a property error. The custom error you're adding has the key 'error' so it will not display in when you call ValidationSummary(true). You need to add your custom error message with an empty key like this:

ModelState.AddModelError(string.Empty, ex.Message);

Using JQuery to open a popup window and print

Are you sure you can't alter the HTML in the popup window?

If you can, add a <script> tag at the end of the popup's HTML, and call window.print() inside it. Then it won't be called until the HTML has loaded.

LinearLayout not expanding inside a ScrollView

The solution is to use

android:fillViewport="true"

on Scroll view and moreover try to use

"wrap_content" instead of "fill_parent" as "fill_parent"

is deprecated now.

ASP.NET IIS Web.config [Internal Server Error]

I had the same problem.

Solution:

  1. Click the right button in your site folder in "iis"
  2. "Convert to Application".

Web Application Problems (web.config errors) HTTP 500.19 with IIS7.5 and ASP.NET v2

Same issue on Server 2016, IIS 10, 500.19 error. I installed the redirect module and it worked. I do not know why this was not included by default.

https://www.iis.net/downloads/microsoft/url-rewrite#additionalDownloads

To be clear it looks like the web.config from IIS 7 will work, or is designed to work, but the lack of this module gives the really odd and unhelpful error. Googling takes you to a Microsoft page which insists that your site is corrupted or your web.config is corrupted. Neither seems to be the case.

That unhelpful page is here: https://support.microsoft.com/en-us/kb/942055

Error 0x80005000 and DirectoryServices

It's a permission problem.

When you run the console app, that app runs with your credentials, e.g. as "you".

The WCF service runs where? In IIS? Most likely, it runs under a separate account, which is not permissioned to query Active Directory.

You can either try to get the WCF impersonation thingie working, so that your own credentials get passed on, or you can specify a username/password on creating your DirectoryEntry:

DirectoryEntry directoryEntry = 
    new DirectoryEntry("LDAP://someserver.contoso.com/DC=contoso,DC=com", 
                       userName, password);

OK, so it might not be the credentials after all (that's usually the case in over 80% of the cases I see).

What about changing your code a little bit?

DirectorySearcher directorySearcher = new DirectorySearcher(directoryEntry);
directorySearcher.Filter = string.Format("(&(objectClass=user)(objectCategory=user) (sAMAccountName={0}))", username);

directorySearcher.PropertiesToLoad.Add("msRTCSIP-PrimaryUserAddress");

var result = directorySearcher.FindOne();

if(result != null)
{
   if(result.Properties["msRTCSIP-PrimaryUserAddress"] != null)
   {
      var resultValue = result.Properties["msRTCSIP-PrimaryUserAddress"][0];
   }
}

My idea is: why not tell the DirectorySearcher right off the bat what attribute you're interested in? Then you don't need to do another extra step to get the full DirectoryEntry from the search result (should be faster), and since you told the directory searcher to find that property, it's certainly going to be loaded in the search result - so unless it's null (no value set), then you should be able to retrieve it easily.

Marc

How to mark-up phone numbers?

Although Apple recommends tel: in their docs for Mobile Safari, currently (iOS 4.3) it accepts callto: just the same. So I recommend using callto: on a generic web site as it works with both Skype and iPhone and I expect it will work on Android phones, too.

Update (June 2013)

This is still a matter of deciding what you want your web page to offer. On my websites I provide both tel: and callto: links (the latter labeled as being for Skype) since Desktop browsers on Mac don't do anything with tel: links while mobile Android doesn't do anything with callto: links. Even Google Chrome with the Google Talk plugin does not respond to tel: links. Still, I prefer offering both links on the desktop in case someone has gone to the trouble of getting tel: links to work on their computer.

If the site design dictated that I only provide one link, I'd use a tel: link that I would try to change to callto: on desktop browsers.

Correct Way to Load Assembly, Find Class and Call Run() Method

When you build your assembly, you can call AssemblyBuilder.SetEntryPoint, and then get it back from the Assembly.EntryPoint property to invoke it.

Keep in mind you'll want to use this signature, and note that it doesn't have to be named Main:

static void Run(string[] args)

How to dynamically add a style for text-align using jQuery

 $(this).css({'text-align':'center'}); 

You can use class name and id in place of this

$('.classname').css({'text-align':'center'});

or

$('#id').css({'text-align':'center'});

How to enable mod_rewrite for Apache 2.2

Use below command

sudo a2enmod rewrite

And the restart apache through below command

sudo service apache2 restart

Temporary tables in stored procedures

Maybe.

Temporary tables prefixed with one # (#example) are kept on a per session basis. So if your code calls the stored procedure again while another call is running (for example background threads) then the create call will fail because it's already there.

If you're really worried use a table variable instead

DECLARE @MyTempTable TABLE 
(
   someField int,
   someFieldMore nvarchar(50)
)

This will be specific to the "instance" of that stored procedure call.

How to get a Color from hexadecimal Color String

If you define a color in your XML and want to use it to change background color or something this API is the one your are looking for:

 ((TextView) view).setBackgroundResource(R.drawable.your_color_here);

In my sample I used it for TestView

Selecting a row of pandas series/dataframe by integer index

echoing @HYRY, see the new docs in 0.11

http://pandas.pydata.org/pandas-docs/stable/indexing.html

Here we have new operators, .iloc to explicity support only integer indexing, and .loc to explicity support only label indexing

e.g. imagine this scenario

In [1]: df = pd.DataFrame(np.random.rand(5,2),index=range(0,10,2),columns=list('AB'))

In [2]: df
Out[2]: 
          A         B
0  1.068932 -0.794307
2 -0.470056  1.192211
4 -0.284561  0.756029
6  1.037563 -0.267820
8 -0.538478 -0.800654

In [5]: df.iloc[[2]]
Out[5]: 
          A         B
4 -0.284561  0.756029

In [6]: df.loc[[2]]
Out[6]: 
          A         B
2 -0.470056  1.192211

[] slices the rows (by label location) only

what is Promotional and Feature graphic in Android Market/Play Store?

Promo graphic

The promo graphic is used for promotions on older versions of the Android OS (earlier than 4.0). This image is not required to submit an update for your Store Listing.

Requirements

  • JPG or 24-bit PNG (no alpha)
  • Dimensions: 180px by 120px

https://support.google.com/googleplay/android-developer/answer/1078870

Safely turning a JSON string into an object

Just to the cover parse for different input types

Parse the data with JSON.parse(), and the data becomes a JavaScript object.

var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');

When using the JSON.parse() on a JSON derived from an array, the method will return a JavaScript array, instead of a JavaScript object.

var myArr = JSON.parse(this.responseText);
console.log(myArr[0]);

Date objects are not allowed in JSON. For Dates do somthing like this

var text = '{ "name":"John", "birth":"1986-12-14", "city":"New York"}';
var obj = JSON.parse(text);
obj.birth = new Date(obj.birth);

Functions are not allowed in JSON. If you need to include a function, write it as a string.

var text = '{ "name":"John", "age":"function () {return 30;}", "city":"New York"}';
var obj = JSON.parse(text);
obj.age = eval("(" + obj.age + ")");

How to grep, excluding some patterns?

Question: search for 'loom' excluding 'gloom'.
Answer:

grep -w 'loom' ~/projects/**/trunk/src/**/*.@(h|cpp)

Call an overridden method from super class in typescript

If you want a super class to call a function from a subclass, the cleanest way is to define an abstract pattern, in this manner you explicitly know the method exists somewhere and must be overridden by a subclass.

This is as an example, normally you do not call a sub method within the constructor as the sub instance is not initialized yet… (reason why you have an "undefined" in your question's example)

abstract class A {
    // The abstract method the subclass will have to call
    protected abstract doStuff():void;

    constructor(){
     alert("Super class A constructed, calling now 'doStuff'")
     this.doStuff();
    }
}

class B extends A{

    // Define here the abstract method
    protected doStuff()
    {
        alert("Submethod called");
    }
}

var b = new B();

Test it Here

And if like @Max you really want to avoid implementing the abstract method everywhere, just get rid of it. I don't recommend this approach because you might forget you are overriding the method.

abstract class A {
    constructor() {
        alert("Super class A constructed, calling now 'doStuff'")
        this.doStuff();
    }

    // The fallback method the subclass will call if not overridden
    protected doStuff(): void {
        alert("Default doStuff");
    };
}

class B extends A {
    // Override doStuff()
    protected doStuff() {
        alert("Submethod called");
    }
}

class C extends A {
    // No doStuff() overriding, fallback on A.doStuff()
}

var b = new B();
var c = new C();

Try it Here

How to print GETDATE() in SQL Server with milliseconds in time?

SELECT CONVERT( VARCHAR(24), GETDATE(), 113)

UPDATE

PRINT (CONVERT( VARCHAR(24), GETDATE(), 121))

Viewing local storage contents on IE

Edge (as opposed to IE11) has a better UI for Local storage / Session storage and cookies:

  • Open Dev tools (F12)
  • Go to Debugger tab
  • Click the folder icon to show a list of resources - opens in a separate tab

Dev tools screenshot

Right align text in android TextView

Make the (LinearLayout) android:layout_width="match_parent" and the TextView's android:layout_gravity="right"

What do &lt; and &gt; stand for?

in :

&lt=    this is    <=
=&gt    this is    =>

Getting the location from an IP address

I like the free GeoLite City from Maxmind which works for most applications and from which you can upgrade to a paying version if it's not precise enough. There is a PHP API included, as well as for other languages. And if you are running Lighttpd as a webserver, you can even use a module to get the information in the SERVER variable for every visitor if that's what you need.

I should add there is also a free Geolite Country (which would be faster if you don't need to pinpoint the city the IP is from) and Geolite ASN (if you want to know who owns the IP) and that finally all these are downloadable on your own server, are updated every month and are pretty quick to lookup with the provided APIs as they state "thousands of lookups per second".

UnsupportedClassVersionError: JVMCFRE003 bad major version in WebSphere AS 7

You should also make sure you have set appropriate Project Facets Java version. Module Properties -> Project Facets -> Java 1.6 should be checked

Twitter Bootstrap Tabs: Go to Specific Tab on Page Reload or Hyperlink

I came up with a solution that uses the url hash or localStorage depending on the availability of the latter with below code:

$(function(){
    $(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
        localStorage.setItem('activeTab', $(e.target).attr('href'));
    })

    var hash = window.location.hash;
    var activeTab = localStorage.getItem('activeTab');

    if(hash){
          $('#project-tabs  a[href="' + hash + '"]').tab('show');   
    }else if (activeTab){
        $('#project-tabs a[href="' + activeTab + '"]').tab('show');
    }
});

for each loop in Objective-C for accessing NSMutable dictionary

If you need to mutate the dictionary while enumerating:

for (NSString* key in xyz.allKeys) {
    [xyz setValue:[NSNumber numberWithBool:YES] forKey:key];
}

How to find a parent with a known class in jQuery?

<div id="412412412" class="input-group date">
     <div class="input-group-prepend">
          <button class="btn btn-danger" type="button">Button Click</button>
          <input type="text" class="form-control" value="">
      </div>
</div>

In my situation, i use this code:

$(this).parent().closest('.date').attr('id')

Hope this help someone.

Java - Search for files in a directory

Using Java 8+ features we can write the code in few lines:

protected static Collection<Path> find(String fileName, String searchDirectory) throws IOException {
    try (Stream<Path> files = Files.walk(Paths.get(searchDirectory))) {
        return files
                .filter(f -> f.getFileName().toString().equals(fileName))
                .collect(Collectors.toList());

    }
}

Files.walk returns a Stream<Path> which is "walking the file tree rooted at" the given searchDirectory. To select the desired files only a filter is applied on the Stream files. It compares the file name of a Path with the given fileName.

Note that the documentation of Files.walk requires

This method must be used within a try-with-resources statement or similar control structure to ensure that the stream's open directories are closed promptly after the stream's operations have completed.

I'm using the try-resource-statement.


For advanced searches an alternative is to use a PathMatcher:

protected static Collection<Path> find(String searchDirectory, PathMatcher matcher) throws IOException {
    try (Stream<Path> files = Files.walk(Paths.get(searchDirectory))) {
        return files
                .filter(matcher::matches)
                .collect(Collectors.toList());

    }
}

An example how to use it to find a certain file:

public static void main(String[] args) throws IOException {
    String searchDirectory = args[0];
    String fileName = args[1];
    PathMatcher matcher = FileSystems.getDefault().getPathMatcher("regex:.*" + fileName);
    Collection<Path> find = find(searchDirectory, matcher);
    System.out.println(find);
}

More about it: Oracle Finding Files tutorial

HTML - Change\Update page contents without refreshing\reloading the page

jQuery will do the job. You can use either jQuery.ajax function, which is general one for performing ajax calls, or its wrappers: jQuery.get, jQuery.post for getting/posting data. Its very easy to use, for example, check out this tutorial, which shows how to use jQuery with PHP.

How to make jQuery UI nav menu horizontal?

I just been for 3 days looking for a jquery UI and CSS solution, I merge some code I saw, fix a little, and finally (along the other codes) I could make it work!

http://jsfiddle.net/Moatilliatta/97m6ty1a/

<ul id="nav" class="testnav">
    <li><a class="clk" href="#">Item 1</a></li>
    <li><a class="clk" href="#">Item 2</a></li>
    <li><a class="clk" href="#">Item 3</a>
        <ul class="sub-menu">
            <li><a href="#">Item 3-1</a>
                <ul class="sub-menu">
                    <li><a href="#">Item 3-11</a></li>
                    <li><a href="#">Item 3-12</a>
                        <ul>
                            <li><a href="#">Item 3-111</a></li>                         
                            <li><a href="#">Item 3-112</a>
                                <ul>
                                    <li><a href="#">Item 3-1111</a></li>                            
                                    <li><a href="#">Item 3-1112</a></li>                            
                                    <li><a href="#">Item 3-1113</a>
                                        <ul>
                                            <li><a href="#">Item 3-11131</a></li>                           
                                            <li><a href="#">Item 3-11132</a></li>                           
                                        </ul>
                                    </li>                           
                                </ul>
                            </li>
                            <li><a href="#">Item 3-113</a></li>
                        </ul>
                    </li>
                    <li><a href="#">Item 3-13</a></li>
                </ul>
            </li>
            <li><a href="#">Item 3-2</a>
                <ul>
                    <li><a href="#."> Item 3-21 </a></li>
                    <li><a href="#."> Item 3-22 </a></li>
                    <li><a href="#."> Item 3-23 </a></li>
                </ul>   
            </li>
            <li><a href="#">Item 3-3</a></li>
            <li><a href="#">Item 3-4</a></li>
            <li><a href="#">Item 3-5</a></li>
        </ul>
    </li>
    <li><a class="clk" href="#">Item 4</a>
        <ul class="sub-menu">
            <li><a href="#">Item 4-1</a>
                <ul class="sub-menu">
                    <li><a href="#."> Item 4-11 </a></li>
                    <li><a href="#."> Item 4-12 </a></li>
                    <li><a href="#."> Item 4-13 </a>
                        <ul>
                            <li><a href="#."> Item 4-131 </a></li>
                            <li><a href="#."> Item 4-132 </a></li>
                            <li><a href="#."> Item 4-133 </a></li>
                        </ul>
                    </li>
                </ul>
            </li>
            <li><a href="#">Item 4-2</a></li>
            <li><a href="#">Item 4-3</a></li>
        </ul>
    </li>
    <li><a class="clk" href="#">Item 5</a></li>
</ul>

javascript

$(document).ready(function(){

var menu = "#nav";
var position = {my: "left top", at: "left bottom"};

$(menu).menu({

    position: position,
    blur: function() {
        $(this).menu("option", "position", position);
        },
    focus: function(e, ui) {

        if ($(menu).get(0) !== $(ui).get(0).item.parent().get(0)) {
            $(this).menu("option", "position", {my: "left top", at: "right top"});
            }
    }
});     });

CSS

.ui-menu {width: auto;}.ui-menu:after {content: ".";display: block;clear: both;visibility: hidden;line-height: 0;height: 0;}.ui-menu .ui-menu-item {display: inline-block;margin: 0;padding: 0;width: auto;}#nav{text-align: center;font-size: 12px;}#nav li {display: inline-block;}#nav li a span.ui-icon-carat-1-e {float:right;position:static;margin-top:2px;width:16px;height:16px;background:url(https://www.drupal.org/files/issues/ui-icons-222222-256x240.png) no-repeat -64px -16px;}#nav li ul li {width: 120px;border-bottom: 1px solid #ccc;}#nav li ul {width: 120px; }.ui-menu .ui-menu-item li a span.ui-icon-carat-1-e {background:url(https://www.drupal.org/files/issues/ui-icons-222222-256x240.png) no-repeat -32px -16px !important;

How do I use a delimiter with Scanner.useDelimiter in Java?

The scanner can also use delimiters other than whitespace.

Easy example from Scanner API:

 String input = "1 fish 2 fish red fish blue fish";

 // \\s* means 0 or more repetitions of any whitespace character 
 // fish is the pattern to find
 Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");

 System.out.println(s.nextInt());   // prints: 1
 System.out.println(s.nextInt());   // prints: 2
 System.out.println(s.next());      // prints: red
 System.out.println(s.next());      // prints: blue

 // don't forget to close the scanner!!
 s.close(); 

The point is to understand the regular expressions (regex) inside the Scanner::useDelimiter. Find an useDelimiter tutorial here.


To start with regular expressions here you can find a nice tutorial.

Notes

abc…    Letters
123…    Digits
\d      Any Digit
\D      Any Non-digit character
.       Any Character
\.      Period
[abc]   Only a, b, or c
[^abc]  Not a, b, nor c
[a-z]   Characters a to z
[0-9]   Numbers 0 to 9
\w      Any Alphanumeric character
\W      Any Non-alphanumeric character
{m}     m Repetitions
{m,n}   m to n Repetitions
*       Zero or more repetitions
+       One or more repetitions
?       Optional character
\s      Any Whitespace
\S      Any Non-whitespace character
^…$     Starts and ends
(…)     Capture Group
(a(bc)) Capture Sub-group
(.*)    Capture all
(ab|cd) Matches ab or cd

How to query the permissions on an Oracle directory?

Wasn't sure if you meant which Oracle users can read\write with the directory or the correlation of the permissions between Oracle Directory Object and the underlying Operating System Directory.

As DCookie has covered the Oracle side of the fence, the following is taken from the Oracle documentation found here.

Privileges granted for the directory are created independently of the permissions defined for the operating system directory, and the two may or may not correspond exactly. For example, an error occurs if sample user hr is granted READ privilege on the directory object but the corresponding operating system directory does not have READ permission defined for Oracle Database processes.

How to extract the decimal part from a floating point number in C?

You use the modf function:

double integral;
double fractional = modf(some_double, &integral);

You can also cast it to an integer, but be warned you may overflow the integer. The result is not predictable then.

Using generic std::function objects with member functions in one class

Unfortunately, C++ does not allow you to directly get a callable object referring to an object and one of its member functions. &Foo::doSomething gives you a "pointer to member function" which refers to the member function but not the associated object.

There are two ways around this, one is to use std::bind to bind the "pointer to member function" to the this pointer. The other is to use a lambda that captures the this pointer and calls the member function.

std::function<void(void)> f = std::bind(&Foo::doSomething, this);
std::function<void(void)> g = [this](){doSomething();};

I would prefer the latter.

With g++ at least binding a member function to this will result in an object three-pointers in size, assigning this to an std::function will result in dynamic memory allocation.

On the other hand, a lambda that captures this is only one pointer in size, assigning it to an std::function will not result in dynamic memory allocation with g++.

While I have not verified this with other compilers, I suspect similar results will be found there.

C++ - how to find the length of an integer

Most efficient code to find length of a number.. counts zeros as well, note "n" is the number to be given.

#include <iostream>
using namespace std;
int main()
{
    int n,len= 0;
    cin>>n;
while(n!=0)
    {
       len++;
       n=n/10;
    }
    cout<<len<<endl;
    return 0;
}

How to load a resource bundle from a file resource in Java?

For JSF Application

To get resource bundle prop files from a given file path to use them in a JSF app.

  • Set the bundle with URLClassLoader for a class that extends ResourceBundle to load the bundle from the file path.
  • Specify the class at basename property of loadBundle tag. <f:loadBundle basename="Message" var="msg" />

For basic implementation of extended RB please see the sample at Sample Customized Resource Bundle

/* Create this class to make it base class for Loading Bundle for JSF apps */
public class Message extends ResourceBundle {
        public Messages (){
                File file = new File("D:\\properties\\i18n");  
                ClassLoader loader=null;
                   try {
                       URL[] urls = {file.toURI().toURL()};  
                       loader = new URLClassLoader(urls); 
                       ResourceBundle bundle = getBundle("message", FacesContext.getCurrentInstance().getViewRoot().getLocale(), loader);
                       setParent(bundle);
                       } catch (MalformedURLException ex) { }
       }
      .
      .
      .
    }

Otherwise, get the bundle from getBundle method but locale from others source like Locale.getDefault(), the new (RB)class may not require in this case.

How do I add a submodule to a sub-directory?

I had a similar issue, but had painted myself into a corner with GUI tools.

I had a subproject with a few files in it that I had so far just copied around instead of checking into their own git repo. I created a repo in the subfolder, was able to commit, push, etc just fine. But in the parent repo the subfolder wasn't treated as a submodule, and its files were still being tracked by the parent repo - no good.

To get out of this mess I had to tell Git to stop tracking the subfolder (without deleting the files):

proj> git rm -r --cached ./ui/jslib

Then I had to tell it there was a submodule there (which you can't do if anything there is currently being tracked by git):

proj> git submodule add ./ui/jslib

Update

The ideal way to handle this involves a couple more steps. Ideally, the existing repo is moved out to its own directory, free of any parent git modules, committed and pushed, and then added as a submodule like:

proj> git submodule add [email protected]:user/jslib.git ui/jslib

That will clone the git repo in as a submodule - which involves the standard cloning steps, but also several other more obscure config steps that git takes on your behalf to get that submodule to work. The most important difference is that it places a simple .git file there, instead of a .git directory, which contains a path reference to where the real git dir lives - generally at parent project root .git/modules/jslib.

If you don't do things this way they'll work fine for you, but as soon as you commit and push the parent, and another dev goes to pull that parent, you just made their life a lot harder. It will be very difficult for them to replicate the structure you have on your machine so long as you have a full .git dir in a subfolder of a dir that contains its own .git dir.

So, move, push, git add submodule, is the cleanest option.

What does status=canceled for a resource mean in Chrome Developer Tools?

It was as simple as an incorrect path for me. I would suggest the first step in debugging would be to see if you can load the file independently of ajax etc.

Rebasing a Git merge commit

There are two options here.

One is to do an interactive rebase and edit the merge commit, redo the merge manually and continue the rebase.

Another is to use the --rebase-merges option on git rebase, which is described as follows from the manual:

By default, a rebase will simply drop merge commits from the todo list, and put the rebased commits into a single, linear branch. With --rebase-merges, the rebase will instead try to preserve the branching structure within the commits that are to be rebased, by recreating the merge commits. Any resolved merge conflicts or manual amendments in these merge commits will have to be resolved/re-applied manually."

How do I POST JSON data with cURL?

I am using the below format to test with a web server.

use -F 'json data'

Let's assume this JSON dict format:

{
    'comment': {
        'who':'some_one',
        'desc' : 'get it'
    }
}

Full example

curl -XPOST your_address/api -F comment='{"who":"some_one", "desc":"get it"}'

Sort dataGridView columns in C# ? (Windows Form)

Use Datatable.Default.Sort property and then bind it to the datagridview.

How can I store JavaScript variable output into a PHP variable?

<html> 
<head>
    <script>
        var a="Hello";
    </script>

</head> 

<body> 
    <?php 
        echo $variable = "<script>document.write(a)</script>"; //I want above javascript variable 'a' value to be store here
    ?>
</body> 

How do I replicate a \t tab space in HTML?

You can enter the tab character (U+0009 CHARACTER TABULATION, commonly known as TAB or HT) using the character reference &#9;. It is equivalent to the tab character as such. Thus, from the HTML viewpoint, there is no need to “escape” it using the character reference; but you may do so e.g. if your editing program does not let you enter the character conveniently.

On the other hand, the tab character is in most contexts equivalent to a normal space in HTML. It does not “tabulate”, it’s just a word space.

The tab character has, however, special handling in pre elements and (although this not that well described in specifications) in textarea and xmp element (in the latter, character references cannot be used, only the tab character as such). This is described somewhat misleadingly in HTML specifications, e.g. in HTML 4.01: “[Inside the pre element, ] the horizontal tab character (decimal 9 in [ISO10646] and [ISO88591] ) is usually interpreted by visual user agents as the smallest non-zero number of spaces necessary to line characters up along tab stops that are every 8 characters. We strongly discourage using horizontal tabs in preformatted text since it is common practice, when editing, to set the tab-spacing to other values, leading to misaligned documents.”

The warnings are unnecessary except as regards to the potential mismatch of tabbing in your authoring software and HTML rendering in browsers. The real reason for avoiding horizontal tab is that it a coarse and simplistic tool as compared with tables for presenting tabular material. And in displaying computer source programs, it is better to use just spaces inside pre, since the default tab stops at every 8 characters are quite unsuitable for any normal code indentation style.

In addition, in CSS, you can specify white-space: pre (or, with slightly more limited browser support, white-space: pre-wrap) to make a normal HTML element, like div or p, rendered like pre, so that all whitespace is preserved and horizontal tab has the “tabbing” effect.

In CSS Text Module Level 3 (Last Call working draft, i.e. proceeding towards maturity), there is also the tab-size property, which can be used to set the distance between tab stops, e.g. tab-size: 3. It’s supported by newest versions of most browsers, but not IE (not even IE 11).

How can I determine the type of an HTML element in JavaScript?

nodeName is the attribute you are looking for. For example:

var elt = document.getElementById('foo');
console.log(elt.nodeName);

Note that nodeName returns the element name capitalized and without the angle brackets, which means that if you want to check if an element is an <div> element you could do it as follows:

elt.nodeName == "DIV"

While this would not give you the expected results:

elt.nodeName == "<div>"

The mysqli extension is missing. Please check your PHP configuration

  • In your Xampp folder, open php.ini file inside the PHP folder i.e xampp\php\php.ini (with a text editor).

  • Search for extension=mysqli (Ctrl+F), if there are two, look for the one that has been uncommented (without ";" behind)

  • Change the mysqli with the correct path address i.e extension=C:\xampp\php\ext\php_mysqli.dll.

  • On your Xampp control panel, stop and start apache and MySQL

Calling the base constructor in C#

public class Car
{
     public Car(string model)
     {
        Console.WriteLine(model);
     }
}

public class Mercedes : Car
{
     public Mercedes(string model): base(model)
     {

     }
}

Usage:

Mercedes mercedes = new Mercedes("CLA Shooting Brake");

Output: CLA Shooting Brake

PHP error: "The zip extension and unzip command are both missing, skipping."

PHP-ZIP needs some dependancies or library missing, depends on the image from Dockerfile you need to install them first

RUN set -eux \
   && apt-get update \
   && apt-get install -y libzip-dev zlib1g-dev \
   && docker-php-ext-install zip

How to get temporary folder for current user

DO NOT use this:

System.Environment.GetEnvironmentVariable("TEMP")

Environment variables can be overridden, so the TEMP variable is not necessarily the directory.

The correct way is to use System.IO.Path.GetTempPath() as in the accepted answer.

to remove first and last element in array

var resident_array =  ["RC_FRONT", "RC_BACK", "RC_BACK"];
var remove_item = "RC_FRONT";
resident_array = $.grep(resident_array, function(value) {
            return value != remove_item;
    });
resident_array = ["RC_BACK", "RC_BACK"];

Javascript Equivalent to C# LINQ Select

The ES6 way:

let people = [{firstName:'Alice',lastName:'Cooper'},{firstName:'Bob',age:'Dylan'}];
let names = Array.from(people, p => p.firstName);
for (let name of names) {
  console.log(name);
}

also at: https://jsfiddle.net/52dpucey/

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

Primary network interface IP

ifconfig `ip route | grep default | head -1 | sed 's/\(.*dev \)\([a-z0-9]*\)\(.*\)/\2/g'` | grep -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b" | head -1

How to understand nil vs. empty vs. blank in Ruby

I made this useful table with all the cases:

enter image description here

blank?, present? are provided by Rails.

Ignore invalid self-signed ssl certificate in node.js with https.request?

Or you can try to add in local name resolution (hosts file found in the directory etc in most operating systems, details differ) something like this:

192.168.1.1 Linksys 

and next

var req = https.request({ 
    host: 'Linksys', 
    port: 443,
    path: '/',
    method: 'GET'
...

will work.

Dealing with nginx 400 "The plain HTTP request was sent to HTTPS port" error

I ran into a similar problem. It works on one server and does not on another server with same Nginx configuration. Found the the solution which is answered by Igor here http://forum.nginx.org/read.php?2,1612,1627#msg-1627

Yes. Or you may combine SSL/non-SSL servers in one server:

server {
  listen 80;
  listen 443 default ssl;

  # ssl on   - remember to comment this out

}

How do I prompt a user for confirmation in bash script?

read -p "Are you sure? " -n 1 -r
echo    # (optional) move to a new line
if [[ $REPLY =~ ^[Yy]$ ]]
then
    # do dangerous stuff
fi

I incorporated levislevis85's suggestion (thanks!) and added the -n option to read to accept one character without the need to press Enter. You can use one or both of these.

Also, the negated form might look like this:

read -p "Are you sure? " -n 1 -r
echo    # (optional) move to a new line
if [[ ! $REPLY =~ ^[Yy]$ ]]
then
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1 # handle exits from shell or function but don't exit interactive shell
fi

However, as pointed out by Erich, under some circumstances such as a syntax error caused by the script being run in the wrong shell, the negated form could allow the script to continue to the "dangerous stuff". The failure mode should favor the safest outcome so only the first, non-negated if should be used.

Explanation:

The read command outputs the prompt (-p "prompt") then accepts one character (-n 1) and accepts backslashes literally (-r) (otherwise read would see the backslash as an escape and wait for a second character). The default variable for read to store the result in is $REPLY if you don't supply a name like this: read -p "my prompt" -n 1 -r my_var

The if statement uses a regular expression to check if the character in $REPLY matches (=~) an upper or lower case "Y". The regular expression used here says "a string starting (^) and consisting solely of one of a list of characters in a bracket expression ([Yy]) and ending ($)". The anchors (^ and $) prevent matching longer strings. In this case they help reinforce the one-character limit set in the read command.

The negated form uses the logical "not" operator (!) to match (=~) any character that is not "Y" or "y". An alternative way to express this is less readable and doesn't as clearly express the intent in my opinion in this instance. However, this is what it would look like: if [[ $REPLY =~ ^[^Yy]$ ]]

How do I remove the space between inline/inline-block elements?

The CSS Text Module Level 4 specification defines a text-space-collapse property, which allow to control the how white space inside and around an element is processed.

So, regarding your example, you would just have to write this:

p {
  text-space-collapse: discard;
}

Unfortunately, no browser is implementing this property yet (as of September 2016) as mentioned in the comments to the answer of HBP.

Join two sql queries

You can use CTE also like below.

With cte as
(select Activity, SUM(Amount) as "Total Amount 2009"
   from Activities, Incomes
  where Activities.UnitName = ? AND
        Incomes.ActivityId = Activities.ActivityID
  GROUP BY Activity
),
cte1 as 
(select Activity, SUM(Amount) as "Total Amount 2008"
   from Activities, Incomes2008
  where Activities.UnitName = ? AND
        Incomes2008.ActivityId = Activities.ActivityID
  GROUP BY Activity
)
Select cte.Activity, cte.[Total Amount 2009] ,cte1.[Total Amount 2008]      
  from cte join cte1 ON cte.ActivityId = cte1.ActivityID
 WHERE a.UnitName = ?
 ORDER BY cte.Activity 

git pull keeping local changes

Incase their is local uncommitted changes and avoid merge conflict while pulling.

git stash save
git pull
git stash pop

refer - https://happygitwithr.com/pull-tricky.html

How to find indices of all occurrences of one string in another in JavaScript?

Here is a simple code snippet:

_x000D_
_x000D_
function getIndexOfSubStr(str, searchToken, preIndex, output) {
    var result = str.match(searchToken);
    if (result) {
        output.push(result.index +preIndex);
        str=str.substring(result.index+searchToken.length);
        getIndexOfSubStr(str, searchToken, preIndex, output)
    }
    return output;
}

var str = "my name is 'xyz' and my school name is 'xyz' and my area name is 'xyz' ";
var searchToken ="my";
var preIndex = 0;

console.log(getIndexOfSubStr(str, searchToken, preIndex, []));
_x000D_
_x000D_
_x000D_

Facebook api: (#4) Application request limit reached

now Application-Level Rate Limiting 200 calls per hour !

you can look this image.enter image description here

How to read a file line-by-line into a list?

This will yield an "array" of lines from the file.

lines = tuple(open(filename, 'r'))

open returns a file which can be iterated over. When you iterate over a file, you get the lines from that file. tuple can take an iterator and instantiate a tuple instance for you from the iterator that you give it. lines is a tuple created from the lines of the file.

Assign an initial value to radio button as checked

You can just use:

<input type="radio" checked />

Using just the attribute checked without stating a value is the same as checked="checked".

Python datetime to string without microsecond component

Since not all datetime.datetime instances have a microsecond component (i.e. when it is zero), you can partition the string on a "." and take only the first item, which will always work:

unicode(datetime.datetime.now()).partition('.')[0]

How to get source code of a Windows executable?

You can't get the C++ source from an exe, and you can only get some version of the C# source via reflection.

Passing variable number of arguments around

To pass the ellipses on, you have to convert them to a va_list and use that va_list in your second function. Specifically;

void format_string(char *fmt,va_list argptr, char *formatted_string);


void debug_print(int dbg_lvl, char *fmt, ...) 
{    
 char formatted_string[MAX_FMT_SIZE];

 va_list argptr;
 va_start(argptr,fmt);
 format_string(fmt, argptr, formatted_string);
 va_end(argptr);
 fprintf(stdout, "%s",formatted_string);
}

Installing Python packages from local file system folder to virtualenv with pip

I am installing pyfuzzybut is is not in PyPI; it returns the message: No matching distribution found for pyfuzzy.

I tried the accepted answer

pip install  --no-index --find-links=file:///Users/victor/Downloads/pyfuzzy-0.1.0 pyfuzzy

But it does not work either and returns the following error:

Ignoring indexes: https://pypi.python.org/simple Collecting pyfuzzy Could not find a version that satisfies the requirement pyfuzzy (from versions: ) No matching distribution found for pyfuzzy

At last , I have found a simple good way there: https://pip.pypa.io/en/latest/reference/pip_install.html

Install a particular source archive file.
$ pip install ./downloads/SomePackage-1.0.4.tar.gz
$ pip install http://my.package.repo/SomePackage-1.0.4.zip

So the following command worked for me:

pip install ../pyfuzzy-0.1.0.tar.gz.

Hope it can help you.

What is the proper way to comment functions in Python?

I would go for a documentation practice that integrates with a documentation tool such as Sphinx.

The first step is to use a docstring:

def add(self):
 """ Method which adds stuff
 """

How to Auto resize HTML table cell to fit the text size

If you want the cells to resize depending on the content, then you must not specify a width to the table, the rows, or the cells.

If you don't want word wrap, assign the CSS style white-space: nowrap to the cells.

Fatal error: Call to undefined function curl_init()

curl is an extension that needs to be installed, it's got nothing to do with the PHP version.

http://www.php.net/manual/en/curl.setup.php

PowerShell to remove text from a string

$a="some text =keep this,but not this"
$a.split('=')[1].split(',')[0]

returns

keep this

How can I convert a Timestamp into either Date or DateTime object?

java.sql.Timestamp is a subclass of java.util.Date. So, just upcast it.

Date dtStart = resultSet.getTimestamp("dtStart");
Date dtEnd = resultSet.getTimestamp("dtEnd");

Using SimpleDateFormat and creating Joda DateTime should be straightforward from this point on.

Calling remove in foreach loop in Java

Use

.remove() of Interator or

Use

CopyOnWriteArrayList

How to ping ubuntu guest on VirtualBox

In most cases simply switching the virtual machine network adapter to bridged mode is enough to make the guest machine accessible from outside.

Switching virtual machine network adapter type

Sometimes it's possible for the guest machine to not automatically receive an IP which matches the host's IP range after switching to bridged mode (even after rebooting the guest machine). This is often caused by a malfunctioning or badly configured DHCP on the host network.

For example, if the host IP is 192.168.1.1 the guest machine needs to have an IP in the format 192.168.1.* where only the last group of numbers is allowed to be different from the host IP.

You can use a terminal (shell) and type ifconfig (ipconfig for Windows guests) to check what IP is assigned to the guest machine and change it if required.

Getting the guest's machine IP

If the host and guest IPs do not match simply setting a static IP for the guest machine explicitly should resolve the issue.

SQL Server - NOT IN

SELECT  *  FROM Table1 
WHERE MAKE+MODEL+[Serial Number]  not in
    (select make+model+[serial number] from Table2 
     WHERE make+model+[serial number] IS NOT NULL)

That worked for me, where make+model+[serial number] was one field name

Python naming conventions for modules

I would call it nib.py. And I would also name the class Nib.

In a larger python project I'm working on, we have lots of modules defining basically one important class. Classes are named beginning with a capital letter. The modules are named like the class in lowercase. This leads to imports like the following:

from nib import Nib
from foo import Foo
from spam.eggs import Eggs, FriedEggs

It's a bit like emulating the Java way. One class per file. But with the added flexibility, that you can allways add another class to a single file if it makes sense.

Android SDK manager won't open

There are many reasons as to why the SDK Manager won't open. Rather than trying each one of them blindly, I recommend running the android.bat in a command window so you can read the error message and apply the correct fix.

How to get the current location latitude and longitude in android

IMPORTANT:

Please notice this solution is from 2015 might be too old and deprecated.


None of the above worked for me so I made a tutorial and wrote it for myself since I lost many hours trying to implement this. Hope this helps someone:

How to use Google Play Services LOCATION API to get current latitude & longitude

1) Add to your AndroidManifest.xml file the ACCESS_COARSE_LOCATION & ACCESS_FINE_LOCATION:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.appname" >

        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

        <application...

2) Go to app/build.gradlefile and add the following dependency (make sure to use the latest available version):

    dependencies {
        //IMPORTANT: make sure to use the newest version. 11.0.1 is old AF
        compile 'com.google.android.gms:play-services-location:11.0.1
    }

3) In your activity implement the following:

    import com.google.android.gms.common.ConnectionResult;
    import com.google.android.gms.common.api.GoogleApiClient;
    import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
    import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
    import com.google.android.gms.location.LocationListener;
    import com.google.android.gms.location.LocationRequest;
    import com.google.android.gms.location.LocationServices;
    import com.google.android.gms.maps.GoogleMap;

    public class HomeActivity extends AppCompatActivity implements
            ConnectionCallbacks,
            OnConnectionFailedListener,
            LocationListener {

        //Define a request code to send to Google Play services
        private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
        private GoogleApiClient mGoogleApiClient;
        private LocationRequest mLocationRequest;
        private double currentLatitude;
        private double currentLongitude;


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_home);

            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    // The next two lines tell the new client that “this” current class will handle connection stuff
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    //fourth line adds the LocationServices API endpoint from GooglePlayServices
                    .addApi(LocationServices.API)
                    .build();

            // Create the LocationRequest object
            mLocationRequest = LocationRequest.create()
                    .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                    .setInterval(10 * 1000)        // 10 seconds, in milliseconds
                    .setFastestInterval(1 * 1000); // 1 second, in milliseconds

        }

        @Override
        protected void onResume() {
            super.onResume();
            //Now lets connect to the API
            mGoogleApiClient.connect();
        }

        @Override
        protected void onPause() {
            super.onPause();
            Log.v(this.getClass().getSimpleName(), "onPause()");

            //Disconnect from API onPause()
            if (mGoogleApiClient.isConnected()) {
                LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
                mGoogleApiClient.disconnect();
            }


        }

        /**
         * If connected get lat and long
         * 
         */
        @Override
        public void onConnected(Bundle bundle) {
            Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

            if (location == null) {
                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

            } else {
                //If everything went fine lets get latitude and longitude
                currentLatitude = location.getLatitude();
                currentLongitude = location.getLongitude();

                Toast.makeText(this, currentLatitude + " WORKS " + currentLongitude + "", Toast.LENGTH_LONG).show();
            }
        }


        @Override
        public void onConnectionSuspended(int i) {}

        @Override
        public void onConnectionFailed(ConnectionResult connectionResult) {
            /*
             * Google Play services can resolve some errors it detects.
             * If the error has a resolution, try sending an Intent to
             * start a Google Play services activity that can resolve
             * error.
             */
            if (connectionResult.hasResolution()) {
                try {
                    // Start an Activity that tries to resolve the error
                    connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
                    /*
                     * Thrown if Google Play services canceled the original
                     * PendingIntent
                     */
                } catch (IntentSender.SendIntentException e) {
                    // Log the error
                    e.printStackTrace();
                }
            } else {
                /*
                 * If no resolution is available, display a dialog to the
                 * user with the error.
                 */
                Log.e("Error", "Location services connection failed with code " + connectionResult.getErrorCode());
            }
        }

        /**
         * If locationChanges change lat and long
         * 
         * 
         * @param location
         */
        @Override
        public void onLocationChanged(Location location) {
            currentLatitude = location.getLatitude();
            currentLongitude = location.getLongitude();

            Toast.makeText(this, currentLatitude + " WORKS " + currentLongitude + "", Toast.LENGTH_LONG).show();
        }

    }

If you need more info just go to:

The Beginner’s Guide to Location in Android

Note: This doesn't seem to work in the emulator but works just fine on a device

Change private static final field using Java reflection

The accepted answer worked for me until deployed on JDK 1.8u91. Then I realized it failed at field.set(null, newValue); line when I had read the value via reflection before calling of setFinalStatic method.

Probably the read caused somehow different setup of Java reflection internals (namely sun.reflect.UnsafeQualifiedStaticObjectFieldAccessorImpl in failing case instead of sun.reflect.UnsafeStaticObjectFieldAccessorImpl in success case) but I didn't elaborate it further.

Since I needed to temporarily set new value based on old value and later set old value back, I changed signature little bit to provide computation function externally and also return old value:

public static <T> T assignFinalField(Object object, Class<?> clazz, String fieldName, UnaryOperator<T> newValueFunction) {
    Field f = null, ff = null;
    try {
        f = clazz.getDeclaredField(fieldName);
        final int oldM = f.getModifiers();
        final int newM = oldM & ~Modifier.FINAL;
        ff = Field.class.getDeclaredField("modifiers");
        ff.setAccessible(true);
        ff.setInt(f,newM);
        f.setAccessible(true);

        T result = (T)f.get(object);
        T newValue = newValueFunction.apply(result);

        f.set(object,newValue);
        ff.setInt(f,oldM);

        return result;
    } ...

However for general case this would not be sufficient.

Running Facebook application on localhost

In my case the issue revealed to be chrome blocking the CORS request from localhost:4200 to facebook api website. Running Chrome with this setting: "YOUR_PATH_TO_CHROME\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="c:/chrome worked like a charm while developing. Even with no localhost added to facebook app's settings.

html button to send email

You can use an anchor to attempt to open the user's default mail client, prepopulated, with mailto:, but you cannot send the actual email. *Apparently it is possible to do this with a form action as well, but browser support is varied and unreliable, so I do not suggest it.

HTML cannot send mail, you need to use a server side language like php, which is another topic. There are plently of good resources on how to do this here on SO or elsewhere on the internet.

If you are using php, I see SwiftMailer suggested quite a bit.

See full command of running/stopped container in Docker

TL-DR

docker ps --no-trunc and docker inspect CONTAINER provide the entrypoint executed to start the container, along the command passed to, but that may miss some parts such as ${ANY_VAR} because container environment variables are not printed as resolved.

To overcome that, docker inspect CONTAINER has an advantage because it also allow to retrieve separately env variables and their values defined in the container from the Config.Env property.

docker ps and docker inspect provide information about the executed entrypoint and its command. Often, that is a wrapper entrypoint script (.sh) and not the "real" program started by the container. To get information on that, requesting process information with ps or /proc/1/cmdline help.


1) docker ps --no-trunc

It prints the entrypoint and the command executed for all running containers. While it prints the command passed to the entrypoint (if we pass that), it doesn't show value of docker env variables (such as $FOO or ${FOO}).
If our containers use env variables, it may be not enough.

For example, run an alpine container :

docker run --name alpine-example -e MY_VAR=/var alpine:latest sh -c 'ls $MY_VAR'

When use docker -ps such as :

docker ps -a --filter name=alpine-example --no-trunc

It prints :

CONTAINER ID           IMAGE               COMMAND                CREATED             STATUS                     PORTS               NAMES
5b064a6de6d8417...   alpine:latest       "sh -c 'ls $MY_VAR'"   2 minutes ago       Exited (0) 2 minutes ago                       alpine-example

We see the command passed to the entrypoint : sh -c 'ls $MY_VAR' but $MY_VAR is indeed not resolved.

2) docker inspect CONTAINER

When we inspect the alpine-example container :

docker inspect alpine-example | grep -4 Cmd

The command is also there but we don't still see the env variable value :

        "Cmd": [
            "sh",
            "-c",
            "ls $MY_VAR"
        ],

In fact, we could not see interpolated variables with these docker commands.
While as a trade-off, we could display separately both command and env variables for a container with docker inspect :

docker inspect  alpine-example  | grep -4 -E "Cmd|Env"

That prints :

        "Env": [
            "MY_VAR=/var",
            "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
        ],
        "Cmd": [
            "sh",
            "-c",
            "ls $MY_VAR"
        ]

A more docker way would be to use the --format flag of docker inspect that allows to specify JSON attributes to render :

docker inspect --format '{{.Name}} {{.Config.Cmd}}  {{ (.Config.Env) }}'  alpine-example

That outputs :

/alpine-example [sh -c ls $MY_VAR]  [MY_VAR=/var PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin]

3) Retrieve the started process from the container itself for running containers

The entrypoint and command executed by docker may be helpful but in some cases, it is not enough because that is "only" a wrapper entrypoint script (.sh) that is responsible to start the real/core process.
For example when I run a Nexus container, the command executed and shown to run the container is "sh -c ${SONATYPE_DIR}/start-nexus-repository-manager.sh".
For PostgreSQL that is "docker-entrypoint.sh postgres".

To get more information, we could execute on a running container docker exec CONTAINER ps aux.
It may print other processes that may not interest us.
To narrow to the initial process launched by the entrypoint, we could do :

docker exec CONTAINER ps -1

I specify 1 because the process executed by the entrypoint is generally the one with the 1 id.

Without ps, we could still find the information in /proc/1/cmdline (in most of Linux distros but not all). For example :

docker exec CONTAINER cat /proc/1/cmdline | sed -e "s/\x00/ /g"; echo    

If we have access to the docker host that started the container, another alternative to get the full command of the process executed by the entrypoint is : : execute ps -PID where PID is the local process created by the Docker daemon to run the container such as :

ps -$(docker container inspect --format '{{.State.Pid}}'  CONTAINER)

User-friendly formatting with docker ps

docker ps --no-trunc is not always easy to read.
Specifying columns to print and in a tabular format may make it better :

docker ps   --no-trunc  --format "table{{.Names}}\t{{.CreatedAt}}\t{{.Command}}"

Create an alias may help :

alias dps='docker ps   --no-trunc  --format "table{{.Names}}\t{{.CreatedAt}}\t{{.Command}}"'

Spring-Security-Oauth2: Full authentication is required to access this resource

I had the same problem, but I solve this with the following class:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class OAuthSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Bean
    @Override
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }
}

jQuery autohide element after 5 seconds

Please note you may need to display div text again after it has disappeared. So you will need to also empty and then re-show the element at some point.

You can do this with 1 line of code:

$('#element_id').empty().show().html(message).delay(3000).fadeOut(300);

If you're using jQuery you don't need setTimeout, at least not to autohide an element.

How to make use of SQL (Oracle) to count the size of a string?

You can use LENGTH() for CHAR / VARCHAR2 and DBMS_LOB.GETLENGTH() for CLOB. Both functions will count actual characters (not bytes).

See the linked documentation if you do need bytes.

Rename MySQL database

Another way to rename the database or taking image of the database is by using Reverse engineering option in the database tab. It will create a ERR diagram for the database. Rename the schema there.

after that go to file menu and go to export and forward engineer the database.

Then you can import the database.

Why is it faster to check if dictionary contains the key, rather than catch the exception in case it doesn't?

On the one hand, throwing exceptions is inherently expensive, because the stack has to be unwound etc.
On the other hand, accessing a value in a dictionary by its key is cheap, because it's a fast, O(1) operation.

BTW: The correct way to do this is to use TryGetValue

obj item;
if(!dict.TryGetValue(name, out item))
    return null;
return item;

This accesses the dictionary only once instead of twice.
If you really want to just return null if the key doesn't exist, the above code can be simplified further:

obj item;
dict.TryGetValue(name, out item);
return item;

This works, because TryGetValue sets item to null if no key with name exists.

Failed to Connect to MySQL at localhost:3306 with user root

Go to system preferences, then "MySQL"

Click on "Start MySQL Server"

Go to system preferences, then "MySQL". Click on "Start MySQL Server".

Difference between Select Unique and Select Distinct

Unique is a keyword used in the Create Table() directive to denote that a field will contain unique data, usually used for natural keys, foreign keys etc.

For example:

Create Table Employee(   
    Emp_PKey Int Identity(1, 1) Constraint PK_Employee_Emp_PKey Primary Key,  
    Emp_SSN Numeric Not Null Unique,  
    Emp_FName varchar(16),   
    Emp_LName varchar(16) 
)

i.e. Someone's Social Security Number would likely be a unique field in your table, but not necessarily the primary key.

Distinct is used in the Select statement to notify the query that you only want the unique items returned when a field holds data that may not be unique.

Select Distinct Emp_LName
From Employee

You may have many employees with the same last name, but you only want each different last name.

Obviously if the field you are querying holds unique data, then the Distinct keyword becomes superfluous.

String.Format alternative in C++

For completeness, the boost way would be to use boost::format

cout << boost::format("%s %s > %s") % a % b % c;

Take your pick. The boost solution has the advantage of type safety with the sprintf format (for those who find the << syntax a bit clunky).

.gitignore and "The following untracked working tree files would be overwritten by checkout"

Delete .gitignore file from appname/gen/ to solve this issue.

$('body').on('click', '.anything', function(){})

You can try this:

You must follow the following format

    $('element,id,class').on('click', function(){....});

*JQuery code*

    $('body').addClass('.anything').on('click', function(){
      //do some code here i.e
      alert("ok");
    });

How can I select records ONLY from yesterday?

This comment is for readers who have found this entry but are using mysql instead of oracle! on mysql you can do the following: Today

SELECT  * 
FROM 
WHERE date(tran_date) = CURRENT_DATE()

Yesterday

SELECT  * 
FROM yourtable 
WHERE date(tran_date) = DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY)

Java getHours(), getMinutes() and getSeconds()

Java 8

    System.out.println(LocalDateTime.now().getHour());       // 7
    System.out.println(LocalDateTime.now().getMinute());     // 45
    System.out.println(LocalDateTime.now().getSecond());     // 32

Calendar

System.out.println(Calendar.getInstance().get(Calendar.HOUR_OF_DAY));  // 7 
System.out.println(Calendar.getInstance().get(Calendar.MINUTE));       // 45
System.out.println(Calendar.getInstance().get(Calendar.SECOND));       // 32

Joda Time

    System.out.println(new DateTime().getHourOfDay());      // 7
    System.out.println(new DateTime().getMinuteOfHour());   // 45
    System.out.println(new DateTime().getSecondOfMinute()); // 32

Formatted

Java 8

    // 07:48:55.056
    System.out.println(ZonedDateTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME));
    // 7:48:55
    System.out.println(LocalTime.now().getHour() + ":" + LocalTime.now().getMinute() + ":" + LocalTime.now().getSecond());

    // 07:48:55
    System.out.println(new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()));

    // 074855
    System.out.println(new SimpleDateFormat("HHmmss").format(Calendar.getInstance().getTime()));

    // 07:48:55 
    System.out.println(new Date().toString().substring(11, 20));

Insert auto increment primary key to existing table

How to write PHP to ALTER the already existing field (name, in this example) to make it a primary key? W/o, of course, adding any additional 'id' fields to the table..

This a table currently created - Number of Records found: 4 name VARCHAR(20) YES breed VARCHAR(30) YES color VARCHAR(20) YES weight SMALLINT(7) YES

This an end result sought (TABLE DESCRIPTION) -

Number of records found: 4 name VARCHAR(20) NO PRI breed VARCHAR(30) YES color VARCHAR(20) YES weight SMALLINT(7) YES

Instead of getting this -

Number of Records found: 5 id int(11) NO PRI name VARCHAR(20) YES breed VARCHAR(30) YES color VARCHAR(20) YES weight SMALLINT(7) YES

after trying..

$query = "ALTER TABLE racehorses ADD id INT NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY (id)";

how to get this? -

Number of records found: 4 name VARCHAR(20) NO PRI breed VARCHAR(30) YES color VARCHAR(20) YES weight SMALLINT(7) YES

i.e. INSERT/ADD.. etc. the primary key INTO the first field record (w/o adding an additional 'id' field, as stated earlier.

Count the number of times a string appears within a string

Here, I'll over-architect the answer using LINQ. Just shows that there's more than 'n' ways to cook an egg:

public int countTrue(string data)
{
    string[] splitdata = data.Split(',');

    var results = from p in splitdata
            where p.Contains("true")
            select p;

    return results.Count();
}

Increase heap size in Java

I have problem running the py files in my java code using eclipse/STS, getting PyException due to insufficient jvm heap memory. I have done the changes as mentioned below and I'm able to resolve this issue. Below is my System configuration.

enter image description here

And these are the changes I did in my workspace and voila it runs perfect now.

enter image description here enter image description here

Google Map API - Removing Markers

You need to keep an array of the google.maps.Marker objects to hide (or remove or run other operations on them).

In the global scope:

var gmarkers = [];

Then push the markers on that array as you create them:

var marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[i].latitude, locations[i].longitude),
    title: locations[i].title,
    icon: icon,
    map:map
});

// Push your newly created marker into the array:
gmarkers.push(marker);

Then to remove them:

function removeMarkers(){
    for(i=0; i<gmarkers.length; i++){
        gmarkers[i].setMap(null);
    }
}

working example (toggles the markers)

code snippet:

_x000D_
_x000D_
var gmarkers = [];_x000D_
var RoseHulman = new google.maps.LatLng(39.483558, -87.324593);_x000D_
var styles = [{_x000D_
  stylers: [{_x000D_
    hue: "black"_x000D_
  }, {_x000D_
    saturation: -90_x000D_
  }]_x000D_
}, {_x000D_
  featureType: "road",_x000D_
  elementType: "geometry",_x000D_
  stylers: [{_x000D_
    lightness: 100_x000D_
  }, {_x000D_
    visibility: "simplified"_x000D_
  }]_x000D_
}, {_x000D_
  featureType: "road",_x000D_
  elementType: "labels",_x000D_
  stylers: [{_x000D_
    visibility: "on"_x000D_
  }]_x000D_
}];_x000D_
_x000D_
var styledMap = new google.maps.StyledMapType(styles, {_x000D_
  name: "Campus"_x000D_
});_x000D_
var mapOptions = {_x000D_
  center: RoseHulman,_x000D_
  zoom: 15,_x000D_
  mapTypeControl: true,_x000D_
  zoomControl: true,_x000D_
  zoomControlOptions: {_x000D_
    style: google.maps.ZoomControlStyle.SMALL_x000D_
  },_x000D_
  mapTypeControlOptions: {_x000D_
    mapTypeIds: ['map_style', google.maps.MapTypeId.HYBRID],_x000D_
    style: google.maps.MapTypeControlStyle.DROPDOWN_MENU_x000D_
  },_x000D_
  scrollwheel: false,_x000D_
  streetViewControl: true,_x000D_
_x000D_
};_x000D_
_x000D_
var map = new google.maps.Map(document.getElementById('map'), mapOptions);_x000D_
map.mapTypes.set('map_style', styledMap);_x000D_
map.setMapTypeId('map_style');_x000D_
_x000D_
var infowindow = new google.maps.InfoWindow({_x000D_
  maxWidth: 300,_x000D_
  infoBoxClearance: new google.maps.Size(1, 1),_x000D_
  disableAutoPan: false_x000D_
});_x000D_
_x000D_
var marker, i, icon, image;_x000D_
_x000D_
var locations = [{_x000D_
  "id": "1",_x000D_
  "category": "6",_x000D_
  "campus_location": "F2",_x000D_
  "title": "Alpha Tau Omega Fraternity",_x000D_
  "description": "<p>Alpha Tau Omega house</p>",_x000D_
  "longitude": "-87.321133",_x000D_
  "latitude": "39.484092"_x000D_
}, {_x000D_
  "id": "2",_x000D_
  "category": "6",_x000D_
  "campus_location": "B2",_x000D_
  "title": "Apartment Commons",_x000D_
  "description": "<p>The commons area of the apartment-style residential complex</p>",_x000D_
  "longitude": "-87.329282",_x000D_
  "latitude": "39.483599"_x000D_
}, {_x000D_
  "id": "3",_x000D_
  "category": "6",_x000D_
  "campus_location": "B2",_x000D_
  "title": "Apartment East",_x000D_
  "description": "<p>Apartment East</p>",_x000D_
  "longitude": "-87.328809",_x000D_
  "latitude": "39.483748"_x000D_
}, {_x000D_
  "id": "4",_x000D_
  "category": "6",_x000D_
  "campus_location": "B2",_x000D_
  "title": "Apartment West",_x000D_
  "description": "<p>Apartment West</p>",_x000D_
  "longitude": "-87.329732",_x000D_
  "latitude": "39.483429"_x000D_
}, {_x000D_
  "id": "5",_x000D_
  "category": "6",_x000D_
  "campus_location": "C2",_x000D_
  "title": "Baur-Sames-Bogart (BSB) Hall",_x000D_
  "description": "<p>Baur-Sames-Bogart Hall</p>",_x000D_
  "longitude": "-87.325714",_x000D_
  "latitude": "39.482382"_x000D_
}, {_x000D_
  "id": "6",_x000D_
  "category": "6",_x000D_
  "campus_location": "D3",_x000D_
  "title": "Blumberg Hall",_x000D_
  "description": "<p>Blumberg Hall</p>",_x000D_
  "longitude": "-87.328321",_x000D_
  "latitude": "39.483388"_x000D_
}, {_x000D_
  "id": "7",_x000D_
  "category": "1",_x000D_
  "campus_location": "E1",_x000D_
  "title": "The Branam Innovation Center",_x000D_
  "description": "<p>The Branam Innovation Center</p>",_x000D_
  "longitude": "-87.322614",_x000D_
  "latitude": "39.48494"_x000D_
}, {_x000D_
  "id": "8",_x000D_
  "category": "6",_x000D_
  "campus_location": "G3",_x000D_
  "title": "Chi Omega Sorority",_x000D_
  "description": "<p>Chi Omega house</p>",_x000D_
  "longitude": "-87.319905",_x000D_
  "latitude": "39.482071"_x000D_
}, {_x000D_
  "id": "9",_x000D_
  "category": "3",_x000D_
  "campus_location": "D1",_x000D_
  "title": "Cook Stadium/Phil Brown Field",_x000D_
  "description": "<p>Cook Stadium at Phil Brown Field</p>",_x000D_
  "longitude": "-87.325258",_x000D_
  "latitude": "39.485007"_x000D_
}, {_x000D_
  "id": "10",_x000D_
  "category": "1",_x000D_
  "campus_location": "D2",_x000D_
  "title": "Crapo Hall",_x000D_
  "description": "<p>Crapo Hall</p>",_x000D_
  "longitude": "-87.324368",_x000D_
  "latitude": "39.483709"_x000D_
}, {_x000D_
  "id": "11",_x000D_
  "category": "6",_x000D_
  "campus_location": "G3",_x000D_
  "title": "Delta Delta Delta Sorority",_x000D_
  "description": "<p>Delta Delta Delta</p>",_x000D_
  "longitude": "-87.317477",_x000D_
  "latitude": "39.482951"_x000D_
}, {_x000D_
  "id": "12",_x000D_
  "category": "6",_x000D_
  "campus_location": "D2",_x000D_
  "title": "Deming Hall",_x000D_
  "description": "<p>Deming Hall</p>",_x000D_
  "longitude": "-87.325822",_x000D_
  "latitude": "39.483421"_x000D_
}, {_x000D_
  "id": "13",_x000D_
  "category": "5",_x000D_
  "campus_location": "F1",_x000D_
  "title": "Facilities Operations",_x000D_
  "description": "<p>Facilities Operations</p>",_x000D_
  "longitude": "-87.321782",_x000D_
  "latitude": "39.484916"_x000D_
}, {_x000D_
  "id": "14",_x000D_
  "category": "2",_x000D_
  "campus_location": "E3",_x000D_
  "title": "Flame of the Millennium",_x000D_
  "description": "<p>Flame of Millennium sculpture</p>",_x000D_
  "longitude": "-87.323306",_x000D_
  "latitude": "39.481978"_x000D_
}, {_x000D_
  "id": "15",_x000D_
  "category": "5",_x000D_
  "campus_location": "E2",_x000D_
  "title": "Hadley Hall",_x000D_
  "description": "<p>Hadley Hall</p>",_x000D_
  "longitude": "-87.324046",_x000D_
  "latitude": "39.482887"_x000D_
}, {_x000D_
  "id": "16",_x000D_
  "category": "2",_x000D_
  "campus_location": "F2",_x000D_
  "title": "Hatfield Hall",_x000D_
  "description": "<p>Hatfield Hall</p>",_x000D_
  "longitude": "-87.322340",_x000D_
  "latitude": "39.482146"_x000D_
}, {_x000D_
  "id": "17",_x000D_
  "category": "6",_x000D_
  "campus_location": "C2",_x000D_
  "title": "Hulman Memorial Union",_x000D_
  "description": "<p>Hulman Memorial Union</p>",_x000D_
  "longitude": "-87.32698",_x000D_
  "latitude": "39.483574"_x000D_
}, {_x000D_
  "id": "18",_x000D_
  "category": "1",_x000D_
  "campus_location": "E2",_x000D_
  "title": "John T. Myers Center for Technological Research with Industry",_x000D_
  "description": "<p>John T. Myers Center for Technological Research With Industry</p>",_x000D_
  "longitude": "-87.322984",_x000D_
  "latitude": "39.484063"_x000D_
}, {_x000D_
  "id": "19",_x000D_
  "category": "6",_x000D_
  "campus_location": "A2",_x000D_
  "title": "Lakeside Hall",_x000D_
  "description": "<p></p>",_x000D_
  "longitude": "-87.330612",_x000D_
  "latitude": "39.482804"_x000D_
}, {_x000D_
  "id": "20",_x000D_
  "category": "6",_x000D_
  "campus_location": "F2",_x000D_
  "title": "Lambda Chi Alpha Fraternity",_x000D_
  "description": "<p>Lambda Chi Alpha</p>",_x000D_
  "longitude": "-87.320999",_x000D_
  "latitude": "39.48305"_x000D_
}, {_x000D_
  "id": "21",_x000D_
  "category": "1",_x000D_
  "campus_location": "D2",_x000D_
  "title": "Logan Library",_x000D_
  "description": "<p>Logan Library</p>",_x000D_
  "longitude": "-87.324851",_x000D_
  "latitude": "39.483408"_x000D_
}, {_x000D_
  "id": "22",_x000D_
  "category": "6",_x000D_
  "campus_location": "C2",_x000D_
  "title": "Mees Hall",_x000D_
  "description": "<p>Mees Hall</p>",_x000D_
  "longitude": "-87.32778",_x000D_
  "latitude": "39.483533"_x000D_
}, {_x000D_
  "id": "23",_x000D_
  "category": "1",_x000D_
  "campus_location": "E2",_x000D_
  "title": "Moench Hall",_x000D_
  "description": "<p>Moench Hall</p>",_x000D_
  "longitude": "-87.323695",_x000D_
  "latitude": "39.483471"_x000D_
}, {_x000D_
  "id": "24",_x000D_
  "category": "1",_x000D_
  "campus_location": "G4",_x000D_
  "title": "Oakley Observatory",_x000D_
  "description": "<p>Oakley Observatory</p>",_x000D_
  "longitude": "-87.31616",_x000D_
  "latitude": "39.483789"_x000D_
}, {_x000D_
  "id": "25",_x000D_
  "category": "1",_x000D_
  "campus_location": "D2",_x000D_
  "title": "Olin Hall and Olin Advanced Learning Center",_x000D_
  "description": "<p>Olin Hall</p>",_x000D_
  "longitude": "-87.324550",_x000D_
  "latitude": "39.482796"_x000D_
}, {_x000D_
  "id": "26",_x000D_
  "category": "6",_x000D_
  "campus_location": "C3",_x000D_
  "title": "Percopo Hall",_x000D_
  "description": "<p>Percopo Hall</p>",_x000D_
  "longitude": "-87.328182",_x000D_
  "latitude": "39.482121"_x000D_
}, {_x000D_
  "id": "27",_x000D_
  "category": "6",_x000D_
  "campus_location": "G3",_x000D_
  "title": "Public Safety Office",_x000D_
  "description": "<p>The Office of Public Safety</p>",_x000D_
  "longitude": "-87.320377",_x000D_
  "latitude": "39.48191"_x000D_
}, {_x000D_
  "id": "28",_x000D_
  "category": "1",_x000D_
  "campus_location": "E2",_x000D_
  "title": "Rotz Mechanical Engineering Lab",_x000D_
  "description": "<p>Rotz Lab</p>",_x000D_
  "longitude": "-87.323247",_x000D_
  "latitude": "39.483711"_x000D_
}, {_x000D_
  "id": "28",_x000D_
  "category": "6",_x000D_
  "campus_location": "C2",_x000D_
  "title": "Scharpenberg Hall",_x000D_
  "description": "<p>Scharpenberg Hall</p>",_x000D_
  "longitude": "-87.328139",_x000D_
  "latitude": "39.483582"_x000D_
}, {_x000D_
  "id": "29",_x000D_
  "category": "6",_x000D_
  "campus_location": "G2",_x000D_
  "title": "Sigma Nu Fraternity",_x000D_
  "description": "<p>The Sigma Nu house</p>",_x000D_
  "longitude": "-87.31999",_x000D_
  "latitude": "39.48374"_x000D_
}, {_x000D_
  "id": "30",_x000D_
  "category": "6",_x000D_
  "campus_location": "E4",_x000D_
  "title": "South Campus / Rose-Hulman Ventures",_x000D_
  "description": "<p></p>",_x000D_
  "longitude": "-87.330623",_x000D_
  "latitude": "39.417646"_x000D_
}, {_x000D_
  "id": "31",_x000D_
  "category": "6",_x000D_
  "campus_location": "C3",_x000D_
  "title": "Speed Hall",_x000D_
  "description": "<p>Speed Hall</p>",_x000D_
  "longitude": "-87.326632",_x000D_
  "latitude": "39.482121"_x000D_
}, {_x000D_
  "id": "32",_x000D_
  "category": "3",_x000D_
  "campus_location": "C1",_x000D_
  "title": "Sports and Recreation Center",_x000D_
  "description": "<p></p>",_x000D_
  "longitude": "-87.3272",_x000D_
  "latitude": "39.484874"_x000D_
}, {_x000D_
  "id": "33",_x000D_
  "category": "6",_x000D_
  "campus_location": "F2",_x000D_
  "title": "Triangle Fraternity",_x000D_
  "description": "<p>Triangle fraternity</p>",_x000D_
  "longitude": "-87.32113",_x000D_
  "latitude": "39.483659"_x000D_
}, {_x000D_
  "id": "34",_x000D_
  "category": "6",_x000D_
  "campus_location": "B3",_x000D_
  "title": "White Chapel",_x000D_
  "description": "<p>The White Chapel</p>",_x000D_
  "longitude": "-87.329367",_x000D_
  "latitude": "39.482481"_x000D_
}, {_x000D_
  "id": "35",_x000D_
  "category": "6",_x000D_
  "campus_location": "F2",_x000D_
  "title": "Women's Fraternity Housing",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.320753",_x000D_
  "latitude": "39.482401"_x000D_
}, {_x000D_
  "id": "36",_x000D_
  "category": "3",_x000D_
  "campus_location": "E1",_x000D_
  "title": "Intramural Fields",_x000D_
  "description": "<p></p>",_x000D_
  "longitude": "-87.321267",_x000D_
  "latitude": "39.485934"_x000D_
}, {_x000D_
  "id": "37",_x000D_
  "category": "3",_x000D_
  "campus_location": "A3",_x000D_
  "title": "James Rendel Soccer Field",_x000D_
  "description": "<p></p>",_x000D_
  "longitude": "-87.332135",_x000D_
  "latitude": "39.480933"_x000D_
}, {_x000D_
  "id": "38",_x000D_
  "category": "3",_x000D_
  "campus_location": "B2",_x000D_
  "title": "Art Nehf Field",_x000D_
  "description": "<p>Art Nehf Field</p>",_x000D_
  "longitude": "-87.330923",_x000D_
  "latitude": "39.48022"_x000D_
}, {_x000D_
  "id": "39",_x000D_
  "category": "3",_x000D_
  "campus_location": "B2",_x000D_
  "title": "Women's Softball Field",_x000D_
  "description": "<p></p>",_x000D_
  "longitude": "-87.329904",_x000D_
  "latitude": "39.480278"_x000D_
}, {_x000D_
  "id": "40",_x000D_
  "category": "3",_x000D_
  "campus_location": "D1",_x000D_
  "title": "Joy Hulbert Tennis Courts",_x000D_
  "description": "<p>The Joy Hulbert Outdoor Tennis Courts</p>",_x000D_
  "longitude": "-87.323767",_x000D_
  "latitude": "39.485595"_x000D_
}, {_x000D_
  "id": "41",_x000D_
  "category": "6",_x000D_
  "campus_location": "B2",_x000D_
  "title": "Speed Lake",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.328134",_x000D_
  "latitude": "39.482779"_x000D_
}, {_x000D_
  "id": "42",_x000D_
  "category": "5",_x000D_
  "campus_location": "F1",_x000D_
  "title": "Recycling Center",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.320098",_x000D_
  "latitude": "39.484593"_x000D_
}, {_x000D_
  "id": "43",_x000D_
  "category": "1",_x000D_
  "campus_location": "F3",_x000D_
  "title": "Army ROTC",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.321342",_x000D_
  "latitude": "39.481992"_x000D_
}, {_x000D_
  "id": "44",_x000D_
  "category": "2",_x000D_
  "campus_location": "  ",_x000D_
  "title": "Self Made Man",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.326272",_x000D_
  "latitude": "39.484481"_x000D_
}, {_x000D_
  "id": "P1",_x000D_
  "category": "4",_x000D_
  "title": "Percopo Parking",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.328756",_x000D_
  "latitude": "39.481587"_x000D_
}, {_x000D_
  "id": "P2",_x000D_
  "category": "4",_x000D_
  "title": "Speed Parking",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.327361",_x000D_
  "latitude": "39.481694"_x000D_
}, {_x000D_
  "id": "P3",_x000D_
  "category": "4",_x000D_
  "title": "Main Parking",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.326245",_x000D_
  "latitude": "39.481446"_x000D_
}, {_x000D_
  "id": "P4",_x000D_
  "category": "4",_x000D_
  "title": "Lakeside Parking",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.330848",_x000D_
  "latitude": "39.483284"_x000D_
}, {_x000D_
  "id": "P5",_x000D_
  "category": "4",_x000D_
  "title": "Hatfield Hall Parking",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.321417",_x000D_
  "latitude": "39.482398"_x000D_
}, {_x000D_
  "id": "P6",_x000D_
  "category": "4",_x000D_
  "title": "Women's Fraternity Parking",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.320977",_x000D_
  "latitude": "39.482315"_x000D_
}, {_x000D_
  "id": "P7",_x000D_
  "category": "4",_x000D_
  "title": "Myers and Facilities Parking",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.322243",_x000D_
  "latitude": "39.48417"_x000D_
}, {_x000D_
  "id": "P8",_x000D_
  "category": "4",_x000D_
  "title": "",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.323241",_x000D_
  "latitude": "39.484758"_x000D_
}, {_x000D_
  "id": "P9",_x000D_
  "category": "4",_x000D_
  "title": "",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.323617",_x000D_
  "latitude": "39.484311"_x000D_
}, {_x000D_
  "id": "P10",_x000D_
  "category": "4",_x000D_
  "title": "",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.325714",_x000D_
  "latitude": "39.484584"_x000D_
}, {_x000D_
  "id": "P11",_x000D_
  "category": "4",_x000D_
  "title": "",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.32778",_x000D_
  "latitude": "39.484145"_x000D_
}, {_x000D_
  "id": "P12",_x000D_
  "category": "4",_x000D_
  "title": "",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.329035",_x000D_
  "latitude": "39.4848"_x000D_
}];_x000D_
_x000D_
for (i = 0; i < locations.length; i++) {_x000D_
_x000D_
  var marker = new google.maps.Marker({_x000D_
    position: new google.maps.LatLng(locations[i].latitude, locations[i].longitude),_x000D_
    title: locations[i].title,_x000D_
    map: map_x000D_
  });_x000D_
  gmarkers.push(marker);_x000D_
  google.maps.event.addListener(marker, 'click', (function(marker, i) {_x000D_
    return function() {_x000D_
      if (locations[i].description !== "" || locations[i].title !== "") {_x000D_
        infowindow.setContent('<div class="content" id="content-' + locations[i].id +_x000D_
          '" style="max-height:300px; font-size:12px;"><h3>' + locations[i].title + '</h3>' +_x000D_
          '<hr class="grey" />' +_x000D_
          hasImage(locations[i]) +_x000D_
          locations[i].description) + '</div>';_x000D_
        infowindow.open(map, marker);_x000D_
      }_x000D_
    }_x000D_
  })(marker, i));_x000D_
}_x000D_
_x000D_
function toggleMarkers() {_x000D_
  for (i = 0; i < gmarkers.length; i++) {_x000D_
    if (gmarkers[i].getMap() != null) gmarkers[i].setMap(null);_x000D_
    else gmarkers[i].setMap(map);_x000D_
  }_x000D_
}_x000D_
_x000D_
function hasImage(location) {_x000D_
  return '';_x000D_
}
_x000D_
html,_x000D_
body,_x000D_
#map {_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>_x000D_
<div id="controls">_x000D_
  <input type="button" value="Toggle All Markers" onClick="toggleMarkers()" />_x000D_
</div>_x000D_
<div id="map"></div>
_x000D_
_x000D_
_x000D_

Fatal error: Call to a member function fetch_assoc() on a non-object

Most likely your query failed, and the query call returned a boolean FALSE (or an error object of some sort), which you then try to use as if was a resultset object, causing the error. Try something like var_dump($result) to see what you really got.

Check for errors after EVERY database query call. Even if the query itself is syntactically valid, there's far too many reasons for it to fail anyways - checking for errors every time will save you a lot of grief at some point.

Create controller for partial view in ASP.NET MVC

If it were me, I would simply create a new Controller with a Single Action and then use RenderAction in place of Partial:

// Assuming the controller is named NewController
@{Html.RenderAction("ActionName", 
                     "New", 
                      new { routeValueOne = "SomeValue" });
}

Setting a minimum/maximum character count for any character using a regular expression

It's usually the metacharacter . when not inside a character class.

So use ^.{1,35}$. However, dot does not include newlines unless the dot-all modifier is applied against it.

You can use ^[\S\s]{1,35}$ without any modifiers, and this includes newlines as well.

Error: Failed to lookup view in Express

It is solved by adding the following code in app.js file

app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.set('views', __dirname);

app.get('/', function(req, res){
    res.render("index");
});

How to get json key and value in javascript?

var data = {"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"}

var parsedData = JSON.parse(data);
alert(parsedData.name);
alert(parsedData.skills);
alert(parsedData.jobtitel);
alert(parsedData.res_linkedin);

Why does "pip install" inside Python raise a SyntaxError?

To run pip in Python 3.x, just follow the instructions on Python's page: Installing Python Modules.

python -m pip install SomePackage

Note that this is run from the command line and not the python shell (the reason for syntax error in the original question).

Convert a matrix to a 1 dimensional array

It might be so late, anyway here is my way in converting Matrix to vector:

library(gdata)
vector_data<- unmatrix(yourdata,byrow=T))

hope that will help

UnsupportedClassVersionError unsupported major.minor version 51.0 unable to load class

java_home environment variable should point to the location of the proper version of java installation directory, so that tomcat starts with the right version. for example it you built the project with java 1.7 , then make sure that JAVA_HOME environment variable points to the jdk 1.7 installation directory in your machine.

I had same problem , when i deploy the war in tomcat and run, the link throws the error. But pointing the variable - JAVA_HOME to jdk 1.7 resolved the issue, as my war file was built in java 1.7 environment.

Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?

To use arrow functions with function.prototype.call, I made a helper function on the object prototype:

  // Using
  // @func = function() {use this here} or This => {use This here}
  using(func) {
    return func.call(this, this);
  }

usage

  var obj = {f:3, a:2}
  .using(This => This.f + This.a) // 5

Edit

You don't NEED a helper. You could do:

var obj = {f:3, a:2}
(This => This.f + This.a).call(undefined, obj); // 5

How to get jQuery dropdown value onchange event

Try like this

 $("#drop").change(function () {
        var end = this.value;
        var firstDropVal = $('#pick').val();
    });

Remove last commit from remote git repository

If nobody has pulled it, you can probably do something like

git push remote +branch^1:remotebranch

which will forcibly update the remote branch to the last but one commit of your branch.

Search for highest key/index in an array

You can get the maximum key this way:

<?php
$arr = array("a"=>"test", "b"=>"ztest");
$max = max(array_keys($arr));
?>

How to create a MySQL hierarchical recursive query?

Simple query to list child's of first recursion:

select @pv:=id as id, name, parent_id
from products
join (select @pv:=19)tmp
where parent_id=@pv

Result:

id  name        parent_id
20  category2   19
21  category3   20
22  category4   21
26  category24  22

... with left join:

select
    @pv:=p1.id as id
  , p2.name as parent_name
  , p1.name name
  , p1.parent_id
from products p1
join (select @pv:=19)tmp
left join products p2 on p2.id=p1.parent_id -- optional join to get parent name
where p1.parent_id=@pv

The solution of @tincot to list all child's:

select  id,
        name,
        parent_id 
from    (select * from products
         order by parent_id, id) products_sorted,
        (select @pv := '19') initialisation
where   find_in_set(parent_id, @pv) > 0
and     @pv := concat(@pv, ',', id)

Test it online with Sql Fiddle and see all results.

http://sqlfiddle.com/#!9/a318e3/4/0

Disable Laravel's Eloquent timestamps

just declare the public timestamps variable in your Model to false and everything will work great.

public $timestamps = false;

How can I combine multiple nested Substitute functions in Excel?

=SUBSTITUTE(text, old_text, new_text)

if: a=!, b=@, c=#,... x=>, y=?, z=~, " "="     "
then: abcdefghijklmnopqrstuvwxyz ... try this out
equals: !@#$%^&*()-=+[]\{}|;:/<>?~     ...     ;}?     ;*(|     ]:;

RULES:

(1) text to substitute is in cell A1
(2) max 64 substitution levels (the formula below only has 27 levels [alphabet + space])
(2) "old_text" cannot also be a "new_text" (ie: if a=z .: z cannot be "old text")

---so if a=z,b=y,...y=b,z=a, then the result is 
---abcdefghijklmnopqrstuvwxyz = zyxwvutsrqponnopqrstuvwxyz (and z changes to a then changes back to z) ... (pattern starts to fail after m=n, n=m... and n becomes n)

The formula is:

=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,"a","!"),"b","@"),"c","#"),"d","$"),"e","%"),"f","^"),"g","&"),"h","*"),"i","("),"j",")"),"k","-"),"l","="),"m","+"),"n","["),"o","]"),"p","\"),"q","{"),"r","}"),"s","|"),"t",";"),"u",":"),"v","/"),"w","<"),"x",">"),"y","?"),"z","~")," ","     ")

ComboBox.SelectedText doesn't give me the SelectedText

From the documentation:

You can use the SelectedText property to retrieve or change the currently selected text in a ComboBox control. However, you should be aware that the selection can change automatically because of user interaction. For example, if you retrieve the SelectedText value in a button Click event handler, the value will be an empty string. This is because the selection is automatically cleared when the input focus moves from the combo box to the button.

When the combo box loses focus, the selection point moves to the beginning of the text and any selected text becomes unselected. In this case, getting the SelectedText property retrieves an empty string, and setting the SelectedText property adds the specified value to the beginning of the text.

How to restrict UITextField to take only numbers in Swift?

Updated Cian's response above to Swift 3:

func textField(textField: UITextField,shouldChangeCharactersInRange range: NSRange,replacementString string: String) -> Bool { let newCharacters = NSCharacterSet(charactersIn: string) let boolIsNumber = NSCharacterSet.decimalDigits.isSuperset(of:newCharacters as CharacterSet) if boolIsNumber == true { return true } else { if string == "." { let countdots = textField.text!.components(separatedBy:".").count - 1 if countdots == 0 { return true } else { if countdots > 0 && string == "." { return false } else { return true } } } else { return false } } }

Disable Tensorflow debugging information

I was struggling from this for a while, tried almost all the solutions here but could not get rid of debugging info in TF 1.14, I have tried following multiple solutions:

import os
import logging
import sys

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'  # FATAL
stderr = sys.stderr
sys.stderr = open(os.devnull, 'w')

import tensorflow as tf
tf.get_logger().setLevel(tf.compat.v1.logging.FATAL)
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
logging.getLogger('tensorflow').setLevel(tf.compat.v1.logging.FATAL)

sys.stderr = stderr

import absl.logging
logging.root.removeHandler(absl.logging._absl_handler)
absl.logging._warn_preinit_stderr = False

The debugging info still showed up, what finally helped was restarting my pc (actually restarting the kernel should work). So if somebody has similar problem, try restart kernel after you set your environment vars, simple but might not come in mind.

A hex viewer / editor plugin for Notepad++?

There is an old plugin called HEX Editor here.

According to this question on Super User it does not work on newer versions of Notepad++ and might have some stability issues, but it still could be useful depending on your needs.

Angular.js: How does $eval work and why is it different from vanilla eval?

From the test,

it('should allow passing locals to the expression', inject(function($rootScope) {
  expect($rootScope.$eval('a+1', {a: 2})).toBe(3);

  $rootScope.$eval(function(scope, locals) {
    scope.c = locals.b + 4;
  }, {b: 3});
  expect($rootScope.c).toBe(7);
}));

We also can pass locals for evaluation expression.

JavaScript associative array to JSON

Arrays should only have entries with numerical keys (arrays are also objects but you really should not mix these).

If you convert an array to JSON, the process will only take numerical properties into account. Other properties are simply ignored and that's why you get an empty array as result. Maybe this more obvious if you look at the length of the array:

> AssocArray.length
0

What is often referred to as "associative array" is actually just an object in JS:

var AssocArray = {};  // <- initialize an object, not an array
AssocArray["a"] = "The letter A"

console.log("a = " + AssocArray["a"]); // "a = The letter A"
JSON.stringify(AssocArray); // "{"a":"The letter A"}"

Properties of objects can be accessed via array notation or dot notation (if the key is not a reserved keyword). Thus AssocArray.a is the same as AssocArray['a'].

Java best way for string find and replace?

Try this:

public static void main(String[] args) {
    String str = "My name is Milan, people know me as Milan Vasic.";

    Pattern p = Pattern.compile("(Milan)(?! Vasic)");
    Matcher m = p.matcher(str);

    StringBuffer sb = new StringBuffer();

    while(m.find()) {
        m.appendReplacement(sb, "Milan Vasic");
    }

    m.appendTail(sb);
    System.out.println(sb);
}

How to remove blank lines from a Unix file

sed -i '/^$/d' foo

This tells sed to delete every line matching the regex ^$ i.e. every empty line. The -i flag edits the file in-place, if your sed doesn't support that you can write the output to a temporary file and replace the original:

sed '/^$/d' foo > foo.tmp
mv foo.tmp foo

If you also want to remove lines consisting only of whitespace (not just empty lines) then use:

sed -i '/^[[:space:]]*$/d' foo

Edit: also remove whitespace at the end of lines, because apparently you've decided you need that too:

sed -i '/^[[:space:]]*$/d;s/[[:space:]]*$//' foo

Set a thin border using .css() in javascript

Current Example:

You need to define border-width:1px

Your code should read:

$(this).css({"border-color": "#C1E0FF", 
             "border-width":"1px", 
             "border-style":"solid"});

Suggested Example:

You should ideally use a class and addClass/removeClass

$(this).addClass('borderClass'); $(this).removeClass('borderClass');

and in your CSS:

.borderClass{
  border-color: #C1E0FF;
  border-width:1px;
  border-style: solid;
  /** OR USE INLINE
  border: 1px solid #C1E0FF;
  **/
}

jsfiddle working example: http://jsfiddle.net/gorelative/tVbvF/\

jsfiddle with animate: http://jsfiddle.net/gorelative/j9Xxa/ This just gives you an example of how it could work, you should get the idea.. There are better ways of doing this most likely.. like using a toggle()

MySQL joins and COUNT(*) from another table

SELECT DISTINCT groups.id, 
       (SELECT COUNT(*) FROM group_members
        WHERE member_id = groups.id) AS memberCount
FROM groups

Retrieving the output of subprocess.call()

The following captures stdout and stderr of the process in a single variable. It is Python 2 and 3 compatible:

from subprocess import check_output, CalledProcessError, STDOUT

command = ["ls", "-l"]
try:
    output = check_output(command, stderr=STDOUT).decode()
    success = True 
except CalledProcessError as e:
    output = e.output.decode()
    success = False

If your command is a string rather than an array, prefix this with:

import shlex
command = shlex.split(command)

How can I create a dynamic button click event on a dynamic button?

Button button = new Button();
button.Click += (s,e) => { your code; };
//button.Click += new EventHandler(button_Click);
container.Controls.Add(button);

//protected void button_Click (object sender, EventArgs e) { }

Fluid width with equally spaced DIVs

If css3 is an option, this can be done using the css calc() function.

Case 1: Justifying boxes on a single line ( FIDDLE )

Markup is simple - a bunch of divs with some container element.

CSS looks like this:

div
{
    height: 100px;
    float: left;
    background:pink;
    width: 50px;
    margin-right: calc((100% - 300px) / 5 - 1px); 
}
div:last-child
{
    margin-right:0;
}

where -1px to fix an IE9+ calc/rounding bug - see here

Case 2: Justifying boxes on multiple lines ( FIDDLE )

Here, in addition to the calc() function, media queries are necessary.

The basic idea is to set up a media query for each #columns states, where I then use calc() to work out the margin-right on each of the elements (except the ones in the last column).

This sounds like a lot of work, but if you're using LESS or SASS this can be done quite easily

(It can still be done with regular css, but then you'll have to do all the calculations manually, and then if you change your box width - you have to work out everything again)

Below is an example using LESS: (You can copy/paste this code here to play with it, [it's also the code I used to generate the above mentioned fiddle])

@min-margin: 15px;
@div-width: 150px;

@3divs: (@div-width * 3);
@4divs: (@div-width * 4);
@5divs: (@div-width * 5);
@6divs: (@div-width * 6);
@7divs: (@div-width * 7);

@3divs-width: (@3divs + @min-margin * 2);
@4divs-width: (@4divs + @min-margin * 3);
@5divs-width: (@5divs + @min-margin * 4);
@6divs-width: (@6divs + @min-margin * 5);
@7divs-width: (@7divs + @min-margin * 6);


*{margin:0;padding:0;}

.container
{
    overflow: auto;
    display: block;
    min-width: @3divs-width;
}
.container > div
{
    margin-bottom: 20px;
    width: @div-width;
    height: 100px;
    background: blue;
    float:left;
    color: #fff;
    text-align: center;
}

@media (max-width: @3divs-width) {
    .container > div {  
        margin-right: @min-margin;
    }
    .container > div:nth-child(3n) {  
        margin-right: 0;
    }
}

@media (min-width: @3divs-width) and (max-width: @4divs-width) {
    .container > div {  
        margin-right: ~"calc((100% - @{3divs})/2 - 1px)";
    }
    .container > div:nth-child(3n) {  
        margin-right: 0;
    }
}

@media (min-width: @4divs-width) and (max-width: @5divs-width) {
    .container > div {  
        margin-right: ~"calc((100% - @{4divs})/3 - 1px)";
    }
    .container > div:nth-child(4n) {  
        margin-right: 0;
    }
}

@media (min-width: @5divs-width) and (max-width: @6divs-width) {
    .container > div {  
        margin-right: ~"calc((100% - @{5divs})/4 - 1px)";
    }
    .container > div:nth-child(5n) {  
        margin-right: 0;
    }
}

@media (min-width: @6divs-width){
    .container > div {  
        margin-right: ~"calc((100% - @{6divs})/5 - 1px)";
    }
    .container > div:nth-child(6n) {  
        margin-right: 0;
    }
}

So basically you first need to decide a box-width and a minimum margin that you want between the boxes.

With that, you can work out how much space you need for each state.

Then, use calc() to calcuate the right margin, and nth-child to remove the right margin from the boxes in the final column.

The advantage of this answer over the accepted answer which uses text-align:justify is that when you have more than one row of boxes - the boxes on the final row don't get 'justified' eg: If there are 2 boxes remaining on the final row - I don't want the first box to be on the left and the next one to be on the right - but rather that the boxes follow each other in order.

Regarding browser support: This will work on IE9+,Firefox,Chrome,Safari6.0+ - (see here for more details) However i noticed that on IE9+ there's a bit of a glitch between media query states. [if someone knows how to fix this i'd really like to know :) ] <-- FIXED HERE

Is there a typescript List<> and/or Map<> class/library?

Did they add a runtime List<> and/or Map<> type class to typepad 1.0

No, providing a runtime is not the focus of the TypeScript team.

is there a solid library out there someone wrote that provides this functionality?

I wrote (really just ported over buckets to typescript): https://github.com/basarat/typescript-collections

Update

JavaScript / TypeScript now support this natively and you can enable them with lib.d.ts : https://basarat.gitbooks.io/typescript/docs/types/lib.d.ts.html along with a polyfill if you want

visual c++: #include files from other projects in the same solution

Expanding on @Benav's answer, my preferred approach is to:

  1. Add the solution directory to your include paths:
    • right click on your project in the Solution Explorer
    • select Properties
    • select All Configurations and All Platforms from the drop-downs
    • select C/C++ > General
    • add $(SolutionDir) to the Additional Include Directories
  2. Add references to each project you want to use:
    • right click on your project's References in the Solution Explorer
    • select Add Reference...
    • select the project(s) you want to refer to

Now you can include headers from your referenced projects like so:

#include "OtherProject/Header.h"

Notes:

  • This assumes that your solution file is stored one folder up from each of your projects, which is the default organization when creating projects with Visual Studio.
  • You could now include any file from a path relative to the solution folder, which may not be desirable but for the simplicity of the approach I'm ok with this.
  • Step 2 isn't necessary for #includes, but it sets the correct build dependencies, which you probably want.

How do I remove a library from the arduino environment?

In Elegoo Super Starter Kit, Part 2, Lesson 2.12, IR Receiver Module, I hit the problem that the lesson's IRremote library has a hard conflict with the built-in Arduino RobotIRremote library. I am using the Win10 IDE App, and it was non-trivial to "move the RobotIRremote" folder like the pre-Win10 instructions said. The built-in Libraries are saved at a path like: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\libraries You won't be able to see WindowsApps unless you show hidden files, and you can't do anything in that folder structure until you are the owner. Carefully follow these directions to make that happen: https://www.youtube.com/watch?v=PmrOzBDZTzw
After hours of frustration, the process above finally resulted in success for me. Elegoo gets an F+ for modern instructions on this lesson.

jQuery load first 3 elements, click "load more" to display next 5 elements

The expression $(document).ready(function() deprecated in jQuery3.

See working fiddle with jQuery 3 here

Take into account I didn't include the showless button.

Here's the code:

JS

$(function () {
    x=3;
    $('#myList li').slice(0, 3).show();
    $('#loadMore').on('click', function (e) {
        e.preventDefault();
        x = x+5;
        $('#myList li').slice(0, x).slideDown();
    });
});

CSS

#myList li{display:none;
}
#loadMore {
    color:green;
    cursor:pointer;
}
#loadMore:hover {
    color:black;
}

Observable Finally on Subscribe

The only thing which worked for me is this

fetchData()
  .subscribe(
    (data) => {
       //Called when success
     },
    (error) => {
       //Called when error
    }
  ).add(() => {
       //Called when operation is complete (both success and error)
  });

Using FFmpeg in .net?

GPL-compiled ffmpeg can be used from non-GPL program (commercial project) only if it is invoked in the separate process as command line utility; all wrappers that are linked with ffmpeg library (including Microsoft's FFMpegInterop) can use only LGPL build of ffmpeg.

You may try my .NET wrapper for FFMpeg: Video Converter for .NET (I'm an author of this library). It embeds FFMpeg.exe into the DLL for easy deployment and doesn't break GPL rules (FFMpeg is NOT linked and wrapper invokes it in the separate process with System.Diagnostics.Process).

Copy file(s) from one project to another using post build event...VS2010

If you want to take into consideration the platform (x64, x86 etc) and the configuration (Debug or Release) it would be something like this:

xcopy "$(SolutionDir)\$(Platform)\$(Configuration)\$(TargetName).dll" "$(SolutionDir)TestDirectory\bin\$(Platform)\$(Configuration)\" /F /Y 

Better way to remove specific characters from a Perl string

With a character class this big it is easier to say what you want to keep. A caret in the first position of a character class inverts its sense, so you can write

$varTemp =~ s/[^"%'+\-0-9<=>a-z_{|}]+//gi

or, using the more efficient tr

$varTemp =~ tr/"%'+\-0-9<=>A-Z_a-z{|}//cd

tr docs

Spring MVC: How to return image in @ResponseBody?

In your application context declare a AnnotationMethodHandlerAdapter and registerByteArrayHttpMessageConverter:

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
  <property name="messageConverters">
    <util:list>
      <bean id="byteArrayMessageConverter" class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
    </util:list>
  </property>
</bean> 

also in the handler method set appropriate content type for your response.

Selector on background color of TextView

The problem here is that you cannot define the background color using a color selector, you need a drawable selector. So, the necessary changes would look like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_pressed="true"
        android:drawable="@drawable/selected_state" />
</selector>

You would also need to move that resource to the drawable directory where it would make more sense since it's not a color selector per se.

Then you would have to create the res/drawable/selected_state.xml file like this:

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle">
    <solid android:color="@color/semitransparent_white" />
</shape>

and finally, you would use it like this:

android:background="@drawable/selector"

Note: the reason why the OP was getting an image resource drawn is probably because he tried to just reference his resource that was still in the color directory but using @drawable so he ended up with an ID collision, selecting the wrong resource.

Hope this can still help someone even if the OP probably has, I hope, solved his problem by now.

CSS3 Box Shadow on Top, Left, and Right Only

It's better if you just cover the bottom part with another div and you will get consistent drop shadow across the board.

#servicesContainer {
  /*your css*/
  position: relative;
}

and it's fixed! like magic!

How do I do top 1 in Oracle?

To select the first row from a table and to select one row from a table are two different tasks and need a different query. There are many possible ways to do so. Four of them are:

First

select  max(Fname) from MyTbl;

Second

select  min(Fname) from MyTbl;

Third

select  Fname from MyTbl  where rownum = 1;

Fourth

select  max(Fname) from MyTbl where rowid=(select  max(rowid) from MyTbl)

File path for project files?

Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"JukeboxV2.0\JukeboxV2.0\Datos\ich will.mp3")

base directory + your filename

ArrayList insertion and retrieval order

Yes it remains the same. but why not easily test it? Make an ArrayList, fill it and then retrieve the elements!

`React/RCTBridgeModule.h` file not found

I receive this error in any new module I create with create-react-native-module. None of the posted solutions worked for me.

What worked for me was first making sure to run yarn in the newly created module folder in order to create node_modules/ (this step is probably obvious). Then, in XCode, select Product -> Scheme -> React instead of the default selection of MyModuleName.

Facebook Oauth Logout

A note for Christoph's answer: Facebook Oauth Logout The logout function requires a callback function to be specified and will fail without it, at least on Firefox. Chrome works without the callback.

FB.logout(function(response) {});

Plotting images side by side using matplotlib

You are plotting all your images on one axis. What you want ist to get a handle for each axis individually and plot your images there. Like so:

fig = plt.figure()
ax1 = fig.add_subplot(2,2,1)
ax1.imshow(...)
ax2 = fig.add_subplot(2,2,2)
ax2.imshow(...)
ax3 = fig.add_subplot(2,2,3)
ax3.imshow(...)
ax4 = fig.add_subplot(2,2,4)
ax4.imshow(...)

For more info have a look here: http://matplotlib.org/examples/pylab_examples/subplots_demo.html

For complex layouts, you should consider using gridspec: http://matplotlib.org/users/gridspec.html

How to position background image in bottom right corner? (CSS)

Did you try something like:

body {background: url('[url to your image]') no-repeat right bottom;}

How to check the maximum number of allowed connections to an Oracle database?

Use gv$session for RAC, if you want get the total number of session across the cluster.

PySpark 2.0 The size or shape of a DataFrame

print((df.count(), len(df.columns)))

is easier for smaller datasets.

However if the dataset is huge, an alternative approach would be to use pandas and arrows to convert the dataframe to pandas df and call shape

spark.conf.set("spark.sql.execution.arrow.enabled", "true")
spark.conf.set("spark.sql.crossJoin.enabled", "true")
print(df.toPandas().shape)

jQuery - disable selected options

This seems to work:

$("#theSelect").change(function(){          
    var value = $("#theSelect option:selected").val();
    var theDiv = $(".is" + value);

    theDiv.slideDown().removeClass("hidden");
    //Add this...
    $("#theSelect option:selected").attr('disabled', 'disabled');
});


$("div a.remove").click(function () {     
    $(this).parent().slideUp(function() { $(this).addClass("hidden"); });
    //...and this.
    $("#theSelect option:disabled").removeAttr('disabled');
});

java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory

I ran into this problem when using tomcat-embed-core::7.0.47, from Maven. I'm not sure why they didn't add tomcat-util as a runtime dependency, so I added my own runtime dependency to my own project.

<dependency>
  <groupId>org.apache.tomcat</groupId>
  <artifactId>tomcat-util</artifactId>
  <version><!-- version from tomcat-embed-core --></version>
  <scope>runtime</scope>
</dependency>

How to remove duplicate white spaces in string using Java?

Though it is too late, I have found a better solution (that works for me) that will replace all consecutive same type white spaces with one white space of its type. That is:

   Hello!\n\n\nMy    World  

will be

 Hello!\nMy World 

Notice there are still leading and trailing white spaces. So my complete solution is:

str = str.trim().replaceAll("(\\s)+", "$1"));

Here, trim() replaces all leading and trailing white space strings with "". (\\s) is for capturing \\s (that is white spaces such as ' ', '\n', '\t') in group #1. + sign is for matching 1 or more preceding token. So (\\s)+ can be consecutive characters (1 or more) among any single white space characters (' ', '\n' or '\t'). $1 is for replacing the matching strings with the group #1 string (which only contains 1 white space character) of the matching type (that is the single white space character which has matched). The above solution will change like this:

   Hello!\n\n\nMy    World  

will be

Hello!\nMy World

I have not found my above solution here so I have posted it.

what is the difference between XSD and WSDL

If someone is looking for analogy , this answer might be helpful.

WSDL is like 'SHOW TABLE STATUS' command in mysql. It defines all the elements(request type, response type, format of URL to hit request,etc.,) which should be part of XML. By definition I mean: 1) Names of request or response 2) What should be treated as input , what should be treated as output.

XSD is like DESCRIBE command in mysql. It tells what all variables and their types, a request and response contains.

Downloading jQuery UI CSS from Google's CDN

As Obama says "Yes We Can". Here is the link to it. developers.google.com/#jquery

You need to use

Google

ajax.googleapis.com/ajax/libs/jqueryui/[VERSION NO]/jquery-ui.min.js
ajax.googleapis.com/ajax/libs/jqueryui/[VERSION NO]/themes/[THEME NAME]/jquery-ui.min.css

jQuery CDN

code.jquery.com/ui/[VERSION NO]/jquery-ui.min.js
code.jquery.com/ui/[VERSION NO]/themes/[THEME NAME]/jquery-ui.min.css

Microsoft

ajax.aspnetcdn.com/ajax/jquery.ui/[VERSION NO]/jquery-ui.min.js
ajax.aspnetcdn.com/ajax/jquery.ui/[VERSION NO]/themes/[THEME NAME]/jquery-ui.min.css

Find theme names here http://jqueryui.com/themeroller/ in gallery subtab

.

But i would not recommend you hosting from cdn for the following reasons

  1. Although your chance of hit rate is good in case of Google CDN compared to others but it's still abysmally low.(any cdn not just google).
  2. Loading via cdn you will have 3 requests one for jQuery.js, one for jQueryUI.js and one for your code. You might as will compress it on your local and load it as one single resource.

http://zoompf.com/blog/2010/01/should-you-use-javascript-library-cdns

PHP AES encrypt / decrypt

If you are using MCRYPT_RIJNDAEL_128, try rtrim($output, "\0\3"). If the length of the string is less than 16, the decrypt function will return a string with length of 16 characters, adding 03 at the end.

You can easily check this, e.g. by trying:

$string = "TheString";
$decrypted_string = decrypt_function($stirng, $key);

echo bin2hex($decrypted_string)."=".bin2hex("TheString");

Programmatically navigate using react router V4

You can also simply use props to access history object: this.props.history.push('new_url')

Do we need to execute Commit statement after Update in SQL Server

Sql server unlike oracle does not need commits unless you are using transactions.
Immediatly after your update statement the table will be commited, don't use the commit command in this scenario.

HTML5: Slider with two inputs possible?

I've been looking for a lightweight, dependency free dual slider for some time (it seemed crazy to import jQuery just for this) and there don't seem to be many out there. I ended up modifying @Wildhoney's code a bit and really like it.

_x000D_
_x000D_
function getVals(){_x000D_
  // Get slider values_x000D_
  var parent = this.parentNode;_x000D_
  var slides = parent.getElementsByTagName("input");_x000D_
    var slide1 = parseFloat( slides[0].value );_x000D_
    var slide2 = parseFloat( slides[1].value );_x000D_
  // Neither slider will clip the other, so make sure we determine which is larger_x000D_
  if( slide1 > slide2 ){ var tmp = slide2; slide2 = slide1; slide1 = tmp; }_x000D_
  _x000D_
  var displayElement = parent.getElementsByClassName("rangeValues")[0];_x000D_
      displayElement.innerHTML = slide1 + " - " + slide2;_x000D_
}_x000D_
_x000D_
window.onload = function(){_x000D_
  // Initialize Sliders_x000D_
  var sliderSections = document.getElementsByClassName("range-slider");_x000D_
      for( var x = 0; x < sliderSections.length; x++ ){_x000D_
        var sliders = sliderSections[x].getElementsByTagName("input");_x000D_
        for( var y = 0; y < sliders.length; y++ ){_x000D_
          if( sliders[y].type ==="range" ){_x000D_
            sliders[y].oninput = getVals;_x000D_
            // Manually trigger event first time to display values_x000D_
            sliders[y].oninput();_x000D_
          }_x000D_
        }_x000D_
      }_x000D_
}
_x000D_
  section.range-slider {_x000D_
    position: relative;_x000D_
    width: 200px;_x000D_
    height: 35px;_x000D_
    text-align: center;_x000D_
}_x000D_
_x000D_
section.range-slider input {_x000D_
    pointer-events: none;_x000D_
    position: absolute;_x000D_
    overflow: hidden;_x000D_
    left: 0;_x000D_
    top: 15px;_x000D_
    width: 200px;_x000D_
    outline: none;_x000D_
    height: 18px;_x000D_
    margin: 0;_x000D_
    padding: 0;_x000D_
}_x000D_
_x000D_
section.range-slider input::-webkit-slider-thumb {_x000D_
    pointer-events: all;_x000D_
    position: relative;_x000D_
    z-index: 1;_x000D_
    outline: 0;_x000D_
}_x000D_
_x000D_
section.range-slider input::-moz-range-thumb {_x000D_
    pointer-events: all;_x000D_
    position: relative;_x000D_
    z-index: 10;_x000D_
    -moz-appearance: none;_x000D_
    width: 9px;_x000D_
}_x000D_
_x000D_
section.range-slider input::-moz-range-track {_x000D_
    position: relative;_x000D_
    z-index: -1;_x000D_
    background-color: rgba(0, 0, 0, 1);_x000D_
    border: 0;_x000D_
}_x000D_
section.range-slider input:last-of-type::-moz-range-track {_x000D_
    -moz-appearance: none;_x000D_
    background: none transparent;_x000D_
    border: 0;_x000D_
}_x000D_
  section.range-slider input[type=range]::-moz-focus-outer {_x000D_
  border: 0;_x000D_
}
_x000D_
<!-- This block can be reused as many times as needed -->_x000D_
<section class="range-slider">_x000D_
  <span class="rangeValues"></span>_x000D_
  <input value="5" min="0" max="15" step="0.5" type="range">_x000D_
  <input value="10" min="0" max="15" step="0.5" type="range">_x000D_
</section>
_x000D_
_x000D_
_x000D_

PostgreSQL : cast string to date DD/MM/YYYY

In case you need to convert the returned date of a select statement to a specific format you may use the following:

select to_char(DATE (*date_you_want_to_select*)::date, 'DD/MM/YYYY') as "Formated Date"

Convert a timedelta to days, hours and minutes

I used the following:

delta = timedelta()
totalMinute, second = divmod(delta.seconds, 60)
hour, minute = divmod(totalMinute, 60)
print(f"{hour}h{minute:02}m{second:02}s")

How do I download code using SVN/Tortoise from Google Code?

After you install Tortoise (separate SVN client not required), create a new empty folder for the project somewhere and right click it in Windows. There should be an option for SVN Checkout. Choosing that option will open a dialog box. Paste the URL you posted above in the first textbox of that dialog box and click "OK".

How could others, on a local network, access my NodeJS app while it's running on my machine?

The port is probably blocked by your local firewall or router. Hard to tell without details.

But there is a simple solution for which you don't have to mess with firewall rules, run node as a privileded process to serve on port 80, etc...

Check out Localtunnel. Its a great Ruby script/service, which allows you to make any local port available on the internet within seconds. It's certainly not useful for a production setup, but to try out a game with colleagues, it should work just fine!

Exec : display stdout "live"

Inspired by Nathanael Smith's answer and Eric Freese's comment, it could be as simple as:

var exec = require('child_process').exec;
exec('coffee -cw my_file.coffee').stdout.pipe(process.stdout);

How to set a ripple effect on textview or imageview on Android?

for circle ripple : android:background="?attr/selectableItemBackgroundBorderless"

for rectangle ripple : android:background="?attr/selectableItemBackground"

How to run PyCharm in Ubuntu - "Run in Terminal" or "Run"?

First, go to that folder which is containing pycharm.sh and open terminal from there. Then type

./pycharm.sh

this will open pycharm.

bin folder contains pycharm.sh file.

Is It Possible to NSLog C Structs (Like CGRect or CGPoint)?

NSLog(@"%@",CGRectCreateDictionaryRepresentation(rect));

What are some good Python ORM solutions?

SQLAlchemy's declarative extension, which is becoming standard in 0.5, provides an all in one interface very much like that of Django or Storm. It also integrates seamlessly with classes/tables configured using the datamapper style:

Base = declarative_base()

class Foo(Base):
    __tablename__ = 'foos'
    id = Column(Integer, primary_key=True)

class Thing(Base):
    __tablename__ = 'things'

    id = Column(Integer, primary_key=True)
    name = Column(Unicode)
    description = Column(Unicode)
    foo_id = Column(Integer, ForeignKey('foos.id'))
    foo = relation(Foo)

engine = create_engine('sqlite://')

Base.metadata.create_all(engine)  # issues DDL to create tables

session = sessionmaker(bind=engine)()

foo = Foo()
session.add(foo)
thing = Thing(name='thing1', description='some thing')
thing.foo = foo  # also adds Thing to session
session.commit()

Can I avoid the native fullscreen video player with HTML5 on iPhone or android?

There's a property that enables/disables in line media playback in the iOS web browser (if you were writing a native app, it would be the allowsInlineMediaPlayback property of a UIWebView). By default on iPhone this is set to NO, but on iPad it's set to YES.

Fortunately for you, you can also adjust this behaviour in HTML as follows:

<video id="myVideo" width="280" height="140" webkit-playsinline>

...that should hopefully sort it out for you. I don't know if it will work on your Android devices. It's a webkit property, so it might. Worth a go, anyway.

How to prevent custom views from losing state across screen orientation changes

I had the problem that onRestoreInstanceState restored all my custom views with the state of the last view. I solved it by adding these two methods to my custom view:

@Override
protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
    dispatchFreezeSelfOnly(container);
}

@Override
protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
    dispatchThawSelfOnly(container);
}

Comparing arrays for equality in C++

if (iar1 == iar2)

Here iar1 and iar2 are decaying to pointers to the first elements of the respective arrays. Since they are two distinct arrays, the pointer values are, of course, different and your comparison tests not equal.

To do an element-wise comparison, you must either write a loop; or use std::array instead

std::array<int, 5> iar1 {1,2,3,4,5};
std::array<int, 5> iar2 {1,2,3,4,5};

if( iar1 == iar2 ) {
  // arrays contents are the same

} else {
  // not the same

}

How to preserve insertion order in HashMap?

HashMap is unordered per the second line of the documentation:

This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

Perhaps you can do as aix suggests and use a LinkedHashMap, or another ordered collection. This link can help you find the most appropriate collection to use.

Pass a JavaScript function as parameter

I suggest to put the parameters in an array, and then split them up using the .apply() function. So now we can easily pass a function with lots of parameters and execute it in a simple way.

function addContact(parameters, refreshCallback) {
    refreshCallback.apply(this, parameters);
}

function refreshContactList(int, int, string) {
    alert(int + int);
    console.log(string);
}

addContact([1,2,"str"], refreshContactList); //parameters should be putted in an array

Handling MySQL datetimes and timestamps in Java

The MySQL documentation has information on mapping MySQL types to Java types. In general, for MySQL datetime and timestamps you should use java.sql.Timestamp. A few resources include:

http://dev.mysql.com/doc/refman/5.1/en/datetime.html

http://www.coderanch.com/t/304851/JDBC/java/Java-date-MySQL-date-conversion

How to store Java Date to Mysql datetime...?

http://www.velocityreviews.com/forums/t599436-the-best-practice-to-deal-with-datetime-in-mysql-using-jdbc.html

EDIT:

As others have indicated, the suggestion of using strings may lead to issues.

What is the difference between Trap and Interrupt?

Generally speaking, terms like exceptions, faults, aborts, Traps, and Interrupts all mean the same thing and are called "Interrupts".

Coming to the difference between Trap and Interrupt:

Trap: Is a programmer initiated and expected transfer of control to a special handler routine. (For ex: 80x86 INT instruction is a good example)

Where as

Interrupt(Hardware): Is a program control interruption based on an external hardware event external to the CPU (For ex: Pressing a key on the keyboard or a time out on a timer chip)

C++, How to determine if a Windows Process is running?

TL;DR Use GetProcessVersion.

All of these function are available in Windows XP [desktop apps | UWP apps].

GetProcessVersion uses a Process ID and returns 0 if the process of the given id is not running.

GetExitCodeProcess uses a Process handle and gives you the process exit code, if the code is STILL_ACTIVE (259) the process is still running so you could check if it is not STILL_ACTIVE (259) meaning that the process is not running. This is likely to work in basically every situation, unless the process exits with code 259.

WaitForSingleObject uses a Process handle with the SYNCHRONIZE access right and returns 0 if the process is not running. You should not specify INFINITE for the dwMilliseconds parameter because the function would not return until the process state became signaled(process is terminated).

Amazon S3 boto - how to create a folder?

Although you can create a folder by appending "/" to your folder_name. Under the hood, S3 maintains flat structure unlike your regular NFS.

var params = {
            Bucket : bucketName,
            Key : folderName + "/"
        };
s3.putObject(params, function (err, data) {});

JQuery: detect change in input field

Use jquery change event

Description: Bind an event handler to the "change" JavaScript event, or trigger that event on an element.

An example

$("input[type='text']").change( function() {
  // your code
});

The advantage that .change has over .keypress , .focus , .blur is that .change event will fire only when input has changed

Best data type to store money values in MySQL

I prefer to use BIGINT, and store the values in by multiply with 100, so that it will become integer.

For e.g., to represent a currency value of 93.49, the value shall be stored as 9349, while displaying the value we can divide by 100 and display. This will occupy less storage space.

Caution:
Mostly we don't perform currency * currency multiplication, in case if we are doing it then divide the result with 100 and store, so that it returns to proper precision.

Vector of Vectors to create matrix

You have to initialize the vector of vectors to the appropriate size before accessing any elements. You can do it like this:

// assumes using std::vector for brevity
vector<vector<int>> matrix(RR, vector<int>(CC));

This creates a vector of RR size CC vectors, filled with 0.

How can I read a text file in Android?

Try this

try {
        reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
      String line="";
      String s ="";
   try 
   {
       line = reader.readLine();
   } 
   catch (IOException e) 
   {
       e.printStackTrace();
   }
      while (line != null) 
      {
       s = s + line;
       s =s+"\n";
       try 
       {
           line = reader.readLine();
       } 
       catch (IOException e) 
       {
           e.printStackTrace();
       }
    }
    tv.setText(""+s);
  }

How to fix corrupted git repository?

I experienced similar issues using git version 2.7.1 under Ubuntu 18.04.3 lately. Here is how I did:

sudo apt install git-repair
git-repair  # fix a broken git repository
or
git-repair --force  # force repair, even if data is lost
git fsck  # to verify it was fixed

Most of the time the recovery process was successful

Add views in UIStackView programmatically

In Swift 4.2

let redView = UIView()
redView.backgroundColor = .red

let blueView = UIView()
blueView.backgroundColor = .blue

let stackView = UIStackView(arrangedSubviews: [redView, blueView])
stackView.axis = .vertical
stackView.distribution = .fillEqually

view.addSubview(stackView)

// stackView.frame = CGRect(x: 0, y: 0, width: 200, height: 200)

// autolayout constraint
stackView.translatesAutoresizingMaskIntoConstraints = false

NSLayoutConstraint.activate([
    stackView.topAnchor.constraint(equalTo: view.topAnchor),
    stackView.leftAnchor.constraint(equalTo: view.leftAnchor),
    stackView.rightAnchor.constraint(equalTo: view.rightAnchor),
    stackView.heightAnchor.constraint(equalToConstant: 200)
])

Logging in Scala

Logging in 2020

I was really surprised that Scribe logging framework that I use at work isn't even mentioned here. What is more, it doesn't even appear on the first page in Google after searching "scala logging". But this page appears when googling it! So let me leave that here.

Main advantages of Scribe:

Getting an odd error, SQL Server query using `WITH` clause

;WITH 
    CteProductLookup(ProductId, oid) 
    AS 
...

Delete topic in Kafka 0.8.1.1

Adding to above answers one has to delete the meta data associated with that topic in zookeeper consumer offset path.

bin/zookeeper-shell.sh zookeeperhost:port

rmr /consumers/<sample-consumer-1>/offsets/<deleted-topic>

Otherwise the lag will be negative in kafka-monitoring tools based on zookeeper.

What is the equivalent of "!=" in Excel VBA?

In VBA, the != operator is the Not operator, like this:

If Not strTest = "" Then ...

How to create an object property from a variable value in JavaScript?

The following demonstrates an alternative approach for returning a key pair object using the form of (a, b). The first example uses the string 'key' as the property name, and 'val' as the value.

Example #1:

(function(o,a,b){return o[a]=b,o})({},'key','val');

Example: #2:

var obj = { foo: 'bar' };
(function(o,a,b){return o[a]=b,o})(obj,'key','val');

As shown in the second example, this can modify existing objects, too (if property is already defined in the object, value will be overwritten).

Result #1: { key: 'val' }

Result #2: { foo: 'bar', key: 'val' }

Show animated GIF

Using swing you could simply use a JLabel

 public static void main(String[] args) throws MalformedURLException {

        URL url = new URL("<URL to your Animated GIF>");
        Icon icon = new ImageIcon(url);
        JLabel label = new JLabel(icon);

        JFrame f = new JFrame("Animation");
        f.getContentPane().add(label);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

What is a Java String's default initial value?

There are three types of variables:

  • Instance variables: are always initialized
  • Static variables: are always initialized
  • Local variables: must be initialized before use

The default values for instance and static variables are the same and depends on the type:

  • Object type (String, Integer, Boolean and others): initialized with null
  • Primitive types:
    • byte, short, int, long: 0
    • float, double: 0.0
    • boolean: false
    • char: '\u0000'

An array is an Object. So an array instance variable that is declared but no explicitly initialized will have null value. If you declare an int[] array as instance variable it will have the null value.

Once the array is created all of its elements are assiged with the default type value. For example:

private boolean[] list; // default value is null

private Boolean[] list; // default value is null

once is initialized:

private boolean[] list = new boolean[10]; // all ten elements are assigned to false

private Boolean[] list = new Boolean[10]; // all ten elements are assigned to null (default Object/Boolean value)

Bold & Non-Bold Text In A Single UILabel?

There's category based on bbrame's category. It works similar, but allows you boldify same UILabel multiple times with cumulative results.

UILabel+Boldify.h

@interface UILabel (Boldify)
- (void) boldSubstring: (NSString*) substring;
- (void) boldRange: (NSRange) range;
@end

UILabel+Boldify.m

@implementation UILabel (Boldify)
- (void)boldRange:(NSRange)range {
    if (![self respondsToSelector:@selector(setAttributedText:)]) {
        return;
    }
    NSMutableAttributedString *attributedText;
    if (!self.attributedText) {
        attributedText = [[NSMutableAttributedString alloc] initWithString:self.text];
    } else {
        attributedText = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
    }
    [attributedText setAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:self.font.pointSize]} range:range];
    self.attributedText = attributedText;
}

- (void)boldSubstring:(NSString*)substring {
    NSRange range = [self.text rangeOfString:substring];
    [self boldRange:range];
}
@end

With this corrections you may use it multiple times, eg:

myLabel.text = @"Updated: 2012/10/14 21:59 PM";
[myLabel boldSubstring: @"Updated:"];
[myLabel boldSubstring: @"21:59 PM"];

will result with: "Updated: 2012/10/14 21:59 PM".

Java stack overflow error - how to increase the stack size in Eclipse?

You need to have a launch configuration inside Eclipse in order to adjust the JVM parameters.

After running your program with either F11 or Ctrl-F11, open the launch configurations in Run -> Run Configurations... and open your program under "Java Applications". Select the Arguments pane, where you will find "VM arguments".

This is where -Xss1024k goes.

If you want the launch configuration to be a file in your workspace (so you can right click and run it), select the Common pane, and check the Save as -> Shared File checkbox and browse to the location you want the launch file. I usually have them in a separate folder, as we check them into CVS.

Convert Set to List without creating new List

Also from Guava Collect library, you can use newArrayList(Collection):

Lists.newArrayList([your_set])

This would be very similar to the previous answer from amit, except that you do not need to declare (or instanciate) any list object.

Adding double quote delimiters into csv file

In Excel for Mac at least, you can do this by saving as "CSV for MS DOS" which adds double quotes for any field which needs them.

How to move a file?

After Python 3.4, you can also use pathlib's class Path to move file.

from pathlib import Path

Path("path/to/current/file.foo").rename("path/to/new/destination/for/file.foo")

https://docs.python.org/3.4/library/pathlib.html#pathlib.Path.rename

How to change the ROOT application?

ROOT default app is usually Tomcat Manager - which can be useful so I felt like keeping it around.

So the way i made my app ROOT and kept TCmgr was like this.

renamed ROOT to something else

mv ROOT TCmgr

then created a symbolic link whereby ROOT points to the app i want to make the default.

ln -s <your app> ROOT

worked for me and seemed the easiest approach.

Saving ssh key fails

You have to create the .ssh folder yourself for saving ssh keys.

By the way, I used this path style: C:/Users/you/.ssh/id_rsa

How to get a substring of text?

Use String#slice, also aliased as [].

a = "hello there"
a[1]                   #=> "e"
a[1,3]                 #=> "ell"
a[1..3]                #=> "ell"
a[6..-1]               #=> "there"
a[6..]                 #=> "there" (requires Ruby 2.6+)
a[-3,2]                #=> "er"
a[-4..-2]              #=> "her"
a[12..-1]              #=> nil
a[-2..-4]              #=> ""
a[/[aeiou](.)\1/]      #=> "ell"
a[/[aeiou](.)\1/, 0]   #=> "ell"
a[/[aeiou](.)\1/, 1]   #=> "l"
a[/[aeiou](.)\1/, 2]   #=> nil
a["lo"]                #=> "lo"
a["bye"]               #=> nil

How to change option menu icon in the action bar?

This works properly in my case:

Drawable drawable = ContextCompat.getDrawable(getApplicationContext(),
                                              R.drawable.change_pass);
toolbar.setOverflowIcon(drawable);

How do I run a program from command prompt as a different user and as an admin

In my case I was already logged in as a local administrator and I needed to run CMD as a domain admin so what worked for me was running the below from a powershell window:

runas /noprofile /user:DOMAIN\USER "cmd"

How do I choose grid and block dimensions for CUDA kernels?

The blocksize is usually selected to maximize the "occupancy". Search on CUDA Occupancy for more information. In particular, see the CUDA Occupancy Calculator spreadsheet.

Default keystore file does not exist?

For Mac Users: The debug.keystore file exists in ~/.android directory. Sometimes, due to the relative path, the above mentioned error keeps on popping up.

"The Controls collection cannot be modified because the control contains code blocks"

Keep the java script code inside the body tag

<body> 
   <script type="text/javascript">
   </script>
</body>

Add/delete row from a table

Hi I would do something like this:

var id = 4; // inital number of rows plus one
function addRow(){
   // add a new tr with id 
   // increment id;
}

function deleteRow(id){
   $("#" + id).remove();
}

and i would have a table like this:

<table id = 'dsTable' >
      <tr id=1>
         <td> Relationship Type </td>
         <td> Date of Birth </td>
         <td> Gender </td>
      </tr>
      <tr id=2>
         <td> Spouse </td>
         <td> 1980-22-03 </td>
         <td> female </td>
         <td> <input type="button" id ="addDep" value="Add" onclick = "add()" </td>
         <td> <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(2)"  </td>
      </tr>
       <tr id=3>
         <td> Child </td>
         <td> 2008-23-06 </td>
         <td> female </td>
         <td> <input type="button" id ="addDep" value="Add" onclick = "add()"</td>
         <td>  <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(3)" </td>
      </tr>
   </table>

Also if you want you can make a loop to build up the table. So it will be easy to build the table. The same you can do with edit:)

Can I stretch text using CSS?

I'll answer for horizontal stretching of text, since the vertical is the easy part - just use "transform: scaleY()"

_x000D_
_x000D_
.stretched-text {
  letter-spacing: 2px;
  display: inline-block;
  font-size: 32px;
  transform: scaleY(0.5);
  transform-origin: 0 0;
  margin-bottom: -50%;
}
span {
  font-size: 16px;
  vertical-align: top;
}
_x000D_
<span class="stretched-text">this is some stretched text</span>
<span>and this is some random<br />triple line <br />not stretched text</span>
_x000D_
_x000D_
_x000D_

letter-spacing just adds space between letters, stretches nothing, but it's kinda relative

inline-block because inline elements are too restrictive and the code below wouldn't work otherwise

Now the combination that makes the difference

font-size to get to the size we want - that way the text will really be of the length it's supposed to be and the text before and after it will appear next to it (scaleX is just for show, the browser still sees the element at its original size when positioning other elements).

scaleY to reduce the height of the text, so that it's the same as the text beside it.

transform-origin to make the text scale from the top of the line.

margin-bottom set to a negative value, so that the next line will not be far below - preferably percentage, so that we won't change the line-height property. vertical-align set to top, to prevent the text before or after from floating to other heights (since the stretched text has a real size of 32px)

-- The simple span element has a font-size, only as a reference.

The question asked for a way to prevent the boldness of the text caused by the stretch and I still haven't given one, BUT the font-weight property has more values than just normal and bold.

I know, you just can't see that, but if you search for the appropriate fonts, you can use the more values.

Axios handling errors

call the request function from anywhere without having to use catch().

First, while handling most errors in one place is a good Idea, it's not that easy with requests. Some errors (e.g. 400 validation errors like: "username taken" or "invalid email") should be passed on.

So we now use a Promise based function:

const baseRequest = async (method: string, url: string, data: ?{}) =>
  new Promise<{ data: any }>((resolve, reject) => {
    const requestConfig: any = {
      method,
      data,
      timeout: 10000,
      url,
      headers: {},
    };

    try {
      const response = await axios(requestConfig);
      // Request Succeeded!
      resolve(response);
    } catch (error) {
      // Request Failed!

      if (error.response) {
        // Request made and server responded
        reject(response);
      } else if (error.request) {
        // The request was made but no response was received
        reject(response);
      } else {
        // Something happened in setting up the request that triggered an Error
        reject(response);
      }
    }
  };

you can then use the request like

try {
  response = await baseRequest('GET', 'https://myApi.com/path/to/endpoint')
} catch (error) {
  // either handle errors or don't
}

What is an "index out of range" exception, and how do I fix it?

Why does this error occur?

Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.

The first element in a collection is generally located at index 0. The last element is at index n-1, where n is the Size of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1, you're going to get an error.

How indexing arrays works

When you declare an array like this:

var array = new int[6]

The first and last elements in the array are

var firstElement = array[0];
var lastElement = array[5];

So when you write:

var element = array[5];

you are retrieving the sixth element in the array, not the fifth one.

Typically, you would loop over an array like this:

for (int index = 0; index < array.Length; index++)
{
    Console.WriteLine(array[index]);
}

This works, because the loop starts at zero, and ends at Length-1 because index is no longer less than Length.

This, however, will throw an exception:

for (int index = 0; index <= array.Length; index++)
{
    Console.WriteLine(array[index]);
}

Notice the <= there? index will now be out of range in the last loop iteration, because the loop thinks that Length is a valid index, but it is not.

How other collections work

Lists work the same way, except that you generally use Count instead of Length. They still start at zero, and end at Count - 1.

for (int index = 0; i < list.Count; index++)
{
    Console.WriteLine(list[index]);
} 

However, you can also iterate through a list using foreach, avoiding the whole problem of indexing entirely:

foreach (var element in list)
{
    Console.WriteLine(element.ToString());
}

You cannot index an element that hasn't been added to a collection yet.

var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]);  // Throws exception.

Quadratic and cubic regression in Excel

I know that this question is a little old, but I thought that I would provide an alternative which, in my opinion, might be a little easier. If you're willing to add "temporary" columns to a data set, you can use Excel's Analysis ToolPak?Data Analysis?Regression. The secret to doing a quadratic or a cubic regression analysis is defining the Input X Range:.

If you're doing a simple linear regression, all you need are 2 columns, X & Y. If you're doing a quadratic, you'll need X_1, X_2, & Y where X_1 is the x variable and X_2 is x^2; likewise, if you're doing a cubic, you'll need X_1, X_2, X_3, & Y where X_1 is the x variable, X_2 is x^2 and X_3 is x^3. Notice how the Input X Range is from A1 to B22, spanning 2 columns.

Input for Quadratic Regression Analysis in Excel

The following image the output of the regression analysis. I've highlighted the common outputs, including the R-Squared values and all the coefficients.

Coefficients of Quadratic Regression Analysis in Excel

How to simulate a touch event in Android?

When using Monkey Script I noticed that DispatchPress(KEYCODE_BACK) is doing nothing which really suck. In many cases this is due to the fact that the Activity doesn't consume the Key event. The solution to this problem is to use a mix of monkey script and adb shell input command in a sequence.

1 Using monkey script gave some great timing control. Wait a certain amount of second for the activity and is a blocking adb call.
2 Finally sending adb shell input keyevent 4 will end the running APK.

EG

adb shell monkey -p com.my.application -v -v -v -f /sdcard/monkey_script.txt 1
adb shell input keyevent 4

ObservableCollection not noticing when Item in it changes (even with INotifyPropertyChanged)

I've put together what I hope is a pretty robust solution, including some of the techniques in other answers. It is a new class derived from ObservableCollection<>, which I'm calling FullyObservableCollection<>

It has the following features:

  • It adds a new event, ItemPropertyChanged. I've deliberately kept this separate from the existing CollectionChanged:
    • To aid backward compatibility.
    • So more relevant detail can be given in the new ItemPropertyChangedEventArgs that accompanies it: the original PropertyChangedEventArgs and the index within the collection.
  • It replicates all the constructors from ObservableCollection<>.
  • It correctly handles the list being reset (ObservableCollection<>.Clear()), avoiding a possible memory leak.
  • It overrides the base class's OnCollectionChanged(), rather than a more resource-intensive subscription to the CollectionChanged event.

Code

The complete .cs file follows. Note that a few features of C# 6 have been used, but it should be fairly simple to backport it:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;

namespace Utilities
{
    public class FullyObservableCollection<T> : ObservableCollection<T>
        where T : INotifyPropertyChanged
    {
        /// <summary>
        /// Occurs when a property is changed within an item.
        /// </summary>
        public event EventHandler<ItemPropertyChangedEventArgs> ItemPropertyChanged;

        public FullyObservableCollection() : base()
        { }

        public FullyObservableCollection(List<T> list) : base(list)
        {
            ObserveAll();
        }

        public FullyObservableCollection(IEnumerable<T> enumerable) : base(enumerable)
        {
            ObserveAll();
        }

        protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Remove ||
                e.Action == NotifyCollectionChangedAction.Replace)
            {
                foreach (T item in e.OldItems)
                    item.PropertyChanged -= ChildPropertyChanged;
            }

            if (e.Action == NotifyCollectionChangedAction.Add ||
                e.Action == NotifyCollectionChangedAction.Replace)
            {
                foreach (T item in e.NewItems)
                    item.PropertyChanged += ChildPropertyChanged;
            }

            base.OnCollectionChanged(e);
        }

        protected void OnItemPropertyChanged(ItemPropertyChangedEventArgs e)
        {
            ItemPropertyChanged?.Invoke(this, e);
        }

        protected void OnItemPropertyChanged(int index, PropertyChangedEventArgs e)
        {
            OnItemPropertyChanged(new ItemPropertyChangedEventArgs(index, e));
        }

        protected override void ClearItems()
        {
            foreach (T item in Items)
                item.PropertyChanged -= ChildPropertyChanged;

            base.ClearItems();
        }

        private void ObserveAll()
        {
            foreach (T item in Items)
                item.PropertyChanged += ChildPropertyChanged;
        }

        private void ChildPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            T typedSender = (T)sender;
            int i = Items.IndexOf(typedSender);

            if (i < 0)
                throw new ArgumentException("Received property notification from item not in collection");

            OnItemPropertyChanged(i, e);
        }
    }

    /// <summary>
    /// Provides data for the <see cref="FullyObservableCollection{T}.ItemPropertyChanged"/> event.
    /// </summary>
    public class ItemPropertyChangedEventArgs : PropertyChangedEventArgs
    {
        /// <summary>
        /// Gets the index in the collection for which the property change has occurred.
        /// </summary>
        /// <value>
        /// Index in parent collection.
        /// </value>
        public int CollectionIndex { get; }

        /// <summary>
        /// Initializes a new instance of the <see cref="ItemPropertyChangedEventArgs"/> class.
        /// </summary>
        /// <param name="index">The index in the collection of changed item.</param>
        /// <param name="name">The name of the property that changed.</param>
        public ItemPropertyChangedEventArgs(int index, string name) : base(name)
        {
            CollectionIndex = index;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ItemPropertyChangedEventArgs"/> class.
        /// </summary>
        /// <param name="index">The index.</param>
        /// <param name="args">The <see cref="PropertyChangedEventArgs"/> instance containing the event data.</param>
        public ItemPropertyChangedEventArgs(int index, PropertyChangedEventArgs args) : this(index, args.PropertyName)
        { }
    }
}

NUnit Tests

So you can check changes you might make (and see what I tested in the first place!), I've also included my NUnit test class. Obviously, the following code is not necessary just to use FullyObservableCollection<T> in your project.

NB The test class uses BindableBase from PRISM to implement INotifyPropertyChanged. There is no dependency on PRISM from the main code.

using NUnit.Framework;
using Utilities;
using Microsoft.Practices.Prism.Mvvm;
using System.Collections.Specialized;
using System.Collections.Generic;

namespace Test_Utilities
{
    [TestFixture]
    public class Test_FullyObservableCollection : AssertionHelper
    {
        public class NotifyingTestClass : BindableBase
        {
            public int Id
            {
                get { return _Id; }
                set { SetProperty(ref _Id, value); }
            }
            private int _Id;

            public string Name
            {
                get { return _Name; }
                set { SetProperty(ref _Name, value); }
            }
            private string _Name;

        }

        FullyObservableCollection<NotifyingTestClass> TestCollection;
        NotifyingTestClass Fred;
        NotifyingTestClass Betty;
        List<NotifyCollectionChangedEventArgs> CollectionEventList;
        List<ItemPropertyChangedEventArgs> ItemEventList;

        [SetUp]
        public void Init()
        {
            Fred = new NotifyingTestClass() { Id = 1, Name = "Fred" };
            Betty = new NotifyingTestClass() { Id = 4, Name = "Betty" };

            TestCollection = new FullyObservableCollection<NotifyingTestClass>()
                {
                    Fred,
                    new NotifyingTestClass() {Id = 2, Name = "Barney" },
                    new NotifyingTestClass() {Id = 3, Name = "Wilma" }
                };

            CollectionEventList = new List<NotifyCollectionChangedEventArgs>();
            ItemEventList = new List<ItemPropertyChangedEventArgs>();
            TestCollection.CollectionChanged += (o, e) => CollectionEventList.Add(e);
            TestCollection.ItemPropertyChanged += (o, e) => ItemEventList.Add(e);
        }

        // Change existing member property: just ItemPropertyChanged(IPC) should fire
        [Test]
        public void DetectMemberPropertyChange()
        {
            TestCollection[0].Id = 7;

            Expect(CollectionEventList.Count, Is.EqualTo(0));

            Expect(ItemEventList.Count, Is.EqualTo(1), "IPC count");
            Expect(ItemEventList[0].PropertyName, Is.EqualTo(nameof(Fred.Id)), "Field Name");
            Expect(ItemEventList[0].CollectionIndex, Is.EqualTo(0), "Collection Index");
        }


        // Add new member, change property: CollectionPropertyChanged (CPC) and IPC should fire
        [Test]
        public void DetectNewMemberPropertyChange()
        {
            TestCollection.Add(Betty);

            Expect(TestCollection.Count, Is.EqualTo(4));
            Expect(TestCollection[3].Name, Is.EqualTo("Betty"));

            Expect(ItemEventList.Count, Is.EqualTo(0), "Item Event count");

            Expect(CollectionEventList.Count, Is.EqualTo(1), "Collection Event count");
            Expect(CollectionEventList[0].Action, Is.EqualTo(NotifyCollectionChangedAction.Add), "Action (add)");
            Expect(CollectionEventList[0].OldItems, Is.Null, "OldItems count");
            Expect(CollectionEventList[0].NewItems.Count, Is.EqualTo(1), "NewItems count");
            Expect(CollectionEventList[0].NewItems[0], Is.EqualTo(Betty), "NewItems[0] dereference");

            CollectionEventList.Clear();      // Empty for next operation
            ItemEventList.Clear();

            TestCollection[3].Id = 7;
            Expect(CollectionEventList.Count, Is.EqualTo(0), "Collection Event count");

            Expect(ItemEventList.Count, Is.EqualTo(1), "Item Event count");
            Expect(TestCollection[ItemEventList[0].CollectionIndex], Is.EqualTo(Betty), "Collection Index dereference");
        }


        // Remove member, change property: CPC should fire for removel, neither CPC nor IPC should fire for change
        [Test]
        public void CeaseListentingWhenMemberRemoved()
        {
            TestCollection.Remove(Fred);

            Expect(TestCollection.Count, Is.EqualTo(2));
            Expect(TestCollection.IndexOf(Fred), Is.Negative);

            Expect(ItemEventList.Count, Is.EqualTo(0), "Item Event count (pre change)");

            Expect(CollectionEventList.Count, Is.EqualTo(1), "Collection Event count (pre change)");
            Expect(CollectionEventList[0].Action, Is.EqualTo(NotifyCollectionChangedAction.Remove), "Action (remove)");
            Expect(CollectionEventList[0].OldItems.Count, Is.EqualTo(1), "OldItems count");
            Expect(CollectionEventList[0].NewItems, Is.Null, "NewItems count");
            Expect(CollectionEventList[0].OldItems[0], Is.EqualTo(Fred), "OldItems[0] dereference");

            CollectionEventList.Clear();      // Empty for next operation
            ItemEventList.Clear();

            Fred.Id = 7;
            Expect(CollectionEventList.Count, Is.EqualTo(0), "Collection Event count (post change)");
            Expect(ItemEventList.Count, Is.EqualTo(0), "Item Event count (post change)");
        }


        // Move member in list, change property: CPC should fire for move, IPC should fire for change
        [Test]
        public void MoveMember()
        {
            TestCollection.Move(0, 1);

            Expect(TestCollection.Count, Is.EqualTo(3));
            Expect(TestCollection.IndexOf(Fred), Is.GreaterThan(0));

            Expect(ItemEventList.Count, Is.EqualTo(0), "Item Event count (pre change)");

            Expect(CollectionEventList.Count, Is.EqualTo(1), "Collection Event count (pre change)");
            Expect(CollectionEventList[0].Action, Is.EqualTo(NotifyCollectionChangedAction.Move), "Action (move)");
            Expect(CollectionEventList[0].OldItems.Count, Is.EqualTo(1), "OldItems count");
            Expect(CollectionEventList[0].NewItems.Count, Is.EqualTo(1), "NewItems count");
            Expect(CollectionEventList[0].OldItems[0], Is.EqualTo(Fred), "OldItems[0] dereference");
            Expect(CollectionEventList[0].NewItems[0], Is.EqualTo(Fred), "NewItems[0] dereference");

            CollectionEventList.Clear();      // Empty for next operation
            ItemEventList.Clear();

            Fred.Id = 7;
            Expect(CollectionEventList.Count, Is.EqualTo(0), "Collection Event count (post change)");

            Expect(ItemEventList.Count, Is.EqualTo(1), "Item Event count (post change)");
            Expect(TestCollection[ItemEventList[0].CollectionIndex], Is.EqualTo(Fred), "Collection Index dereference");
        }


        // Clear list, chnage property: only CPC should fire for clear and neither for property change
        [Test]
        public void ClearList()
        {
            TestCollection.Clear();

            Expect(TestCollection.Count, Is.EqualTo(0));

            Expect(ItemEventList.Count, Is.EqualTo(0), "Item Event count (pre change)");

            Expect(CollectionEventList.Count, Is.EqualTo(1), "Collection Event count (pre change)");
            Expect(CollectionEventList[0].Action, Is.EqualTo(NotifyCollectionChangedAction.Reset), "Action (reset)");
            Expect(CollectionEventList[0].OldItems, Is.Null, "OldItems count");
            Expect(CollectionEventList[0].NewItems, Is.Null, "NewItems count");

            CollectionEventList.Clear();      // Empty for next operation
            ItemEventList.Clear();

            Fred.Id = 7;
            Expect(CollectionEventList.Count, Is.EqualTo(0), "Collection Event count (post change)");
            Expect(ItemEventList.Count, Is.EqualTo(0), "Item Event count (post change)");
        }
    }
}

Post form data using HttpWebRequest

Try this:

var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");

var postData = "thing1=hello";
    postData += "&thing2=world";
var data = Encoding.ASCII.GetBytes(postData);

request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;

using (var stream = request.GetRequestStream())
{
    stream.Write(data, 0, data.Length);
}

var response = (HttpWebResponse)request.GetResponse();

var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

How do you search an amazon s3 bucket?

Not a technical answer, but I have built an application which allows for wildcard search: https://bucketsearch.net/

It will asynchronously index your bucket and then allow you to search the results.

It's free to use (donationware).

EC2 Instance Cloning

You can make an AMI of an existing instance, and then launch other instances using that AMI.

1064 error in CREATE TABLE ... TYPE=MYISAM

As documented under CREATE TABLE Syntax:

Note
The older TYPE option was synonymous with ENGINE. TYPE was deprecated in MySQL 4.0 and removed in MySQL 5.5. When upgrading to MySQL 5.5 or later, you must convert existing applications that rely on TYPE to use ENGINE instead.

Therefore, you want:

CREATE TABLE dave_bannedwords(
  id   INT(11)     NOT NULL AUTO_INCREMENT,
  word VARCHAR(60) NOT NULL DEFAULT '',
  PRIMARY KEY (id),
  KEY id(id) -- this is superfluous in the presence of your PK, ergo unnecessary
) ENGINE = MyISAM ;