Programs & Examples On #Xpo

XPO is a DevExpress ORM library for .NET.

Querying date field in MongoDB with Mongoose

{ "date" : "1000000" } in your Mongo doc seems suspect. Since it's a number, it should be { date : 1000000 }

It's probably a type mismatch. Try post.findOne({date: "1000000"}, callback) and if that works, you have a typing issue.

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0

This error occurs when versions of NodeJS and Node Sass are not matched.

you can resolve your issue by doing as below:

- Step 1: Remove Nodejs from your computer

- Step 2: Reinstall Nodejs version 14.15.1.

- Step 3: Uninstall Node sass by run the command npm uninstall node-sass

- Step 4: Reinstall Node sass version 4.14.1 by run the command npm install [email protected]

After all steps, you can run command ng serve -o to run your application.

Node sass version 5.0.0 is incompatible with ^4.0.0.

TS1086: An accessor cannot be declared in ambient context

In my case downgrading @angular/animations worked, if you can afford to do that, run the command

npm i @angular/[email protected]

Or use another version that might work for you from the Versions tab here: https://www.npmjs.com/package/@angular/animations

SyntaxError: Cannot use import statement outside a module

Verify that you have the latest version of Node installed (or, at least 13.2.0+). Then do one of the following, as described in the documentation:

Option 1

In the nearest parent package.json file, add the top-level "type" field with a value of "module". This will ensure that all .js and .mjs files are interpreted as ES modules. You can interpret individual files as CommonJS by using the .cjs extension.

// package.json
{
  "type": "module"
}

Option 2

Explicitly name files with the .mjs extension. All other files, such as .js will be interpreted as CommonJS, which is the default if type is not defined in package.json.

What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

I experienced a similar problem, I was getting ERR_HTTP2_PROTOCOL_ERROR on one of the HTTP GET requests.

I noticed that the Chrome update was pending, so I updated the Chrome browser to the latest version and the error was gone next time when I relaunched the browser.

"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6

I got this error because I forgot the type="module" inside the script tag:

<script type="module" src="milsymbol-2.0.0/src/milsymbol.js"></script>

Element implicitly has an 'any' type because expression of type 'string' can't be used to index

I made some small changes to Alex McKay's function/usage that I think make it a little easier to follow why it works and also adheres to the no-use-before-define rule.

First, define this function to use:

const getKeyValue = function<T extends object, U extends keyof T> (obj: T, key: U) { return obj[key] }

In the way I've written it, the generic for the function lists the object first, then the property on the object second (these can occur in any order, but if you specify U extends key of T before T extends object you break the no-use-before-define rule, and also it just makes sense to have the object first and its' property second. Finally, I've used the more common function syntax instead of the arrow operators (=>).

Anyways, with those modifications you can just use it like this:

interface User {
  name: string;
  age: number;
}

const user: User = {
  name: "John Smith",
  age: 20
};

getKeyValue(user, "name")

Which, again, I find to be a bit more readable.

Angular @ViewChild() error: Expected 2 arguments, but got 1

it is because view child require two argument try like this

@ViewChild('nameInput', { static: false, }) nameInputRef: ElementRef;

@ViewChild('amountInput', { static: false, }) amountInputRef: ElementRef;

Invalid hook call. Hooks can only be called inside of the body of a function component

complementing the following comment

For those who use redux:

class AllowanceClass extends Component{
    ...
    render() {
        const classes = this.props.classes;
        ...
    }
}
    
const COMAllowanceClass = (props) =>
{
    const classes = useStyles();
    return (<AllowanceClass classes={classes} {...props} />);
};

const mapStateToProps = ({ InfoReducer }) => ({
    token: InfoReducer.token,
    user: InfoReducer.user,
    error: InfoReducer.error
});
export default connect(mapStateToProps, { actions })(COMAllowanceClass);

Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; }

This will eliminate the error and is type safe:

this.DNATranscriber[character as keyof typeof DNATranscriber]

Access blocked by CORS policy: Response to preflight request doesn't pass access control check

You may need to config the CORS at Spring Boot side. Please add below class in your Project.

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
public class WebConfig implements Filter,WebMvcConfigurer {



    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
      HttpServletResponse response = (HttpServletResponse) res;
      HttpServletRequest request = (HttpServletRequest) req;
      System.out.println("WebConfig; "+request.getRequestURI());
      response.setHeader("Access-Control-Allow-Origin", "*");
      response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
      response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With,observe");
      response.setHeader("Access-Control-Max-Age", "3600");
      response.setHeader("Access-Control-Allow-Credentials", "true");
      response.setHeader("Access-Control-Expose-Headers", "Authorization");
      response.addHeader("Access-Control-Expose-Headers", "responseType");
      response.addHeader("Access-Control-Expose-Headers", "observe");
      System.out.println("Request Method: "+request.getMethod());
      if (!(request.getMethod().equalsIgnoreCase("OPTIONS"))) {
          try {
              chain.doFilter(req, res);
          } catch(Exception e) {
              e.printStackTrace();
          }
      } else {
          System.out.println("Pre-flight");
          response.setHeader("Access-Control-Allow-Origin", "*");
          response.setHeader("Access-Control-Allow-Methods", "POST,GET,DELETE,PUT");
          response.setHeader("Access-Control-Max-Age", "3600");
          response.setHeader("Access-Control-Allow-Headers", "Access-Control-Expose-Headers"+"Authorization, content-type," +
          "USERID"+"ROLE"+
                  "access-control-request-headers,access-control-request-method,accept,origin,authorization,x-requested-with,responseType,observe");
          response.setStatus(HttpServletResponse.SC_OK);
      }

    }

}

UPDATE:

To append Token to each request you can create one Interceptor as below.

import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token = window.localStorage.getItem('tokenKey'); // you probably want to store it in localStorage or something


    if (!token) {
      return next.handle(req);
    }

    const req1 = req.clone({
      headers: req.headers.set('Authorization', `${token}`),
    });

    return next.handle(req1);
  }

}

Example

How to style components using makeStyles and still have lifecycle methods in Material UI?

I used withStyles instead of makeStyle

EX :

import { withStyles } from '@material-ui/core/styles';
import React, {Component} from "react";

const useStyles = theme => ({
        root: {
           flexGrow: 1,
         },
  });

class App extends Component {
       render() {
                const { classes } = this.props;
                return(
                    <div className={classes.root}>
                       Test
                </div>
                )
          }
} 

export default withStyles(useStyles)(App)

Understanding esModuleInterop in tsconfig file

in your tsconfig you have to add: "esModuleInterop": true - it should help.

How to set value to form control in Reactive Forms in Angular

To assign value to a single Form control/individually, I propose to use setValue in the following way:

this.editqueForm.get('user').setValue(this.question.user);

this.editqueForm.get('questioning').setValue(this.question.questioning);

Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop

I suspect that the problem lies in the fact that you are calling your state setter immediately inside the function component body, which forces React to re-invoke your function again, with the same props, which ends up calling the state setter again, which triggers React to call your function again.... and so on.

const SingInContainer = ({ message, variant}) => {
    const [open, setSnackBarState] = useState(false);
    const handleClose = (reason) => {
        if (reason === 'clickaway') {
          return;
        }
        setSnackBarState(false)

      };

    if (variant) {
        setSnackBarState(true); // HERE BE DRAGONS
    }
    return (
        <div>
        <SnackBar
            open={open}
            handleClose={handleClose}
            variant={variant}
            message={message}
            />
        <SignInForm/>
        </div>
    )
}

Instead, I recommend you just conditionally set the default value for the state property using a ternary, so you end up with:

const SingInContainer = ({ message, variant}) => {
    const [open, setSnackBarState] = useState(variant ? true : false); 
                                  // or useState(!!variant); 
                                  // or useState(Boolean(variant));
    const handleClose = (reason) => {
        if (reason === 'clickaway') {
          return;
        }
        setSnackBarState(false)

      };

    return (
        <div>
        <SnackBar
            open={open}
            handleClose={handleClose}
            variant={variant}
            message={message}
            />
        <SignInForm/>
        </div>
    )
}

Comprehensive Demo

See this CodeSandbox.io demo for a comprehensive demo of it working, plus the broken component you had, and you can toggle between the two.

How can I solve the error 'TS2532: Object is possibly 'undefined'?

With the release of TypeScript 3.7, optional chaining (the ? operator) is now officially available.

As such, you can simplify your expression to the following:

const data = change?.after?.data();

You may read more about it from that version's release notes, which cover other interesting features released on that version.

Run the following to install the latest stable release of TypeScript.

npm install typescript

That being said, Optional Chaining can be used alongside Nullish Coalescing to provide a fallback value when dealing with null or undefined values

const data = change?.after?.data() ?? someOtherData();

Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740]

I had the same problem and I solved as follows define an interface like mine

export class Notification {
    id: number;
    heading: string;
    link: string;
}

and in nofificationService write

allNotifications: Notification[]; 
  //NotificationDetail: Notification;  
  private notificationsUrl = 'assets/data/notification.json';  // URL to web api 
  private downloadsUrl = 'assets/data/download.json';  // URL to web api 

  constructor(private httpClient: HttpClient ) { }

  getNotifications(): Observable<Notification[]> {    
       //return this.allNotifications = this.NotificationDetail.slice(0);  
     return this.httpClient.get<Notification[]>

(this.notificationsUrl).pipe(map(res => this.allNotifications = res))
      } 

and in component write

 constructor(private notificationService: NotificationService) {
   }

  ngOnInit() {
      /* get Notifications */
      this.notificationService.getNotifications().subscribe(data => this.notifications = data);
}

How do I prevent Conda from activating the base environment by default?

The answer depends a little bit on the version of conda that you have installed. For versions of conda >= 4.4, it should be enough to deactivate the conda environment after the initialization, so add

conda deactivate

right underneath

# <<< conda initialize <<<

React Hooks useState() with Object

If anyone is searching for useState() hooks update for object

- Through Input

        const [state, setState] = useState({ fName: "", lName: "" });
        const handleChange = e => {
            const { name, value } = e.target;
            setState(prevState => ({
                ...prevState,
                [name]: value
            }));
        };

        <input
            value={state.fName}
            type="text"
            onChange={handleChange}
            name="fName"
        />
        <input
            value={state.lName}
            type="text"
            onChange={handleChange}
            name="lName"
        />
   ***************************

 - Through onSubmit or button click
    
        setState(prevState => ({
            ...prevState,
            fName: 'your updated value here'
         }));

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

Inspired by the accepted answer by @ford04 I had even better approach dealing with it, instead of using useEffect inside useAsync create a new function that returns a callback for componentWillUnmount :

function asyncRequest(asyncRequest, onSuccess, onError, onComplete) {
  let isMounted=true
  asyncRequest().then((data => isMounted ? onSuccess(data):null)).catch(onError).finally(onComplete)
  return () => {isMounted=false}
}

...

useEffect(()=>{
        return asyncRequest(()=>someAsyncTask(arg), response=> {
            setSomeState(response)
        },onError, onComplete)
    },[])

TypeScript and React - children type?

In order to use <Aux> in your JSX, it needs to be a function that returns ReactElement<any> | null. That's the definition of a function component.

However, it's currently defined as a function that returns React.ReactNode, which is a much wider type. As React typings say:

type ReactNode = ReactChild | ReactFragment | ReactPortal | boolean | null | undefined;

Make sure the unwanted types are neutralized by wrapping the returned value into React Fragment (<></>):

const aux: React.FC<AuxProps> = props =>
  <>{props.children}</>;

Why do I keep getting Delete 'cr' [prettier/prettier]?

Change file type from tsx -> ts, jsx -> js

You can get this error if you are working on .tsx or .jsx file and you are just exporting styles etc and not jsx. In this case the error is solved by changing the file type to .ts or .js

Receiving "Attempted import error:" in react app

I guess I am coming late, but this info might be useful to anyone I found out something, which might be simple but important. if you use export on a function directly i.e

export const addPost = (id) =>{
  ...
 }

Note while importing you need to wrap it in curly braces i.e. import {addPost} from '../URL';

But when using export default i.e

const addPost = (id) =>{
  ...
 }

export default addPost,

Then you can import without curly braces i.e. import addPost from '../url';

export default addPost

I hope this helps anyone who got confused as me.

expected assignment or function call: no-unused-expressions ReactJS

This happens because you put bracket of return on the next line. That might be a common mistake if you write js without semicolons and use a style where you put opened braces on the next line.

Interpreter thinks that you return undefined and doesn't check your next line. That's the return operator thing.

Put your opened bracket on the same line with the return.

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

Well in my case the data which I wanted to render contained an Object inside that of the array so due to this it was giving error, so for other people out there please check your data also once and if it contains an object, you need to convert it to array to print all of its values or if you need a specific value then use.

My data :

body: " d fvsdv"

photo: "http://res.cloudinary.com/imvr7/image/upload/v1591563988/hhanfhiyalwnv231oweg.png"

postedby: {_id: "5edbf948cdfafc4e38e74081", name: "vit"} //this is the object I am talking about.

title: "c sx "

__v: 0

_id: "5edd56d7e64a9e58acfd499f"

proto: Object

To Print only a single value

<h5>{item.postedby.name}</h5>

Xcode 10, Command CodeSign failed with a nonzero exit code

In my case, some special marks in the png files output by Paint.app causes this happen.

I try all answers, but none works for me.

My solution is

step 1. drag the png files(if you do not know which png, please drag all png files in your project resource folder/group) caused the error happens to Preview.app

enter image description here

step 2. adjust image size,

enter image description here

step 3. enlarge 2 times for width and height, click 'Ok' button

enter image description here

step 4. set back to original width and height, click 'Ok' button

enter image description here

step 5. repeat step 3 and step 4 for all png images

step 6. clean project and build again

Done! good luck

DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server

var userPasswordString = new Buffer(baseAuth, 'base64').toString('ascii');

Change this line from your code to this -

var userPasswordString = Buffer.from(baseAuth, 'base64').toString('ascii');

or in my case, I gave the encoding in reverse order

var userPasswordString = Buffer.from(baseAuth, 'utf-8').toString('base64');

ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

In case you need the [] syntax, useful for "edit forms" when you need to pass parameters like id with the route, you would do something like:

[routerLink]="['edit', business._id]"

As for an "about page" with no parameters like yours,

[routerLink]="/about"

or

[routerLink]=['about']

will do the trick.

standard_init_linux.go:190: exec user process caused "no such file or directory" - Docker

Add this to your Dockerfile

RUN cat /run.sh | tr -d '\r' > /run.sh

How can I add raw data body to an axios request?

How about using direct axios API?

axios({
  method: 'post',
  url: baseUrl + 'applications/' + appName + '/dataexport/plantypes' + plan,
  headers: {}, 
  data: {
    foo: 'bar', // This is the body part
  }
});

Source: axios api

What is the point of WORKDIR on Dockerfile?

You can think of WORKDIR like a cd inside the container (it affects commands that come later in the Dockerfile, like the RUN command). If you removed WORKDIR in your example above, RUN npm install wouldn't work because you would not be in the /usr/src/app directory inside your container.

I don't see how this would be related to where you put your Dockerfile (since your Dockerfile location on the host machine has nothing to do with the pwd inside the container). You can put the Dockerfile wherever you'd like in your project. However, the first argument to COPY is a relative path, so if you move your Dockerfile you may need to update those COPY commands.

Angular 6: How to set response type as text while making http call

By Default angular return responseType as Json, but we can configure below types according to your requirement.

responseType: 'arraybuffer'|'blob'|'json'|'text'

Ex:

this.http.post(
    'http://localhost:8080/order/addtocart', 
    { dealerId: 13, createdBy: "-1", productId, quantity }, 
    { headers, responseType: 'text'});

phpMyAdmin - Error > Incorrect format parameter?

If you prefer to edit the file php.ini in your favorite editor than the Editor created by MAMP, you would need to stop the Servers first.

Then head to Library->Application Support->appsolute->MAMP PRO->templates->php{version_number}.ini.temp and effect any change you would want to have especially the below

max_execution_time = 3000
max_input_time = 60
memory_limit = 128M
post_max_size = 256M
upload_max_filesize 256M

And also make changes in your PHPMyAdmin if it is what you are using in Cpanel.

$cfg['ExecTimeLimit'] = 300;

Make sure you make a copy of the original file. You can navigate under conf!here

enter image description here

Set focus on <input> element

You should use html autofocus for this:

<input *ngIf="show" #search type="text" autofocus /> 

Note: if your component is persisted and reused it will only autofocus the first time the fragment is attached. This can be overcome by having a global dom listener that checks for autofocus attribute inside a dom fragment when it is attached and then reapplying it or focus via javascript.

Importing json file in TypeScript

It's easy to use typescript version 2.9+. So you can easily import JSON files as @kentor decribed.

But if you need to use older versions:

You can access JSON files in more TypeScript way. First, make sure your new typings.d.ts location is the same as with the include property in your tsconfig.json file.

If you don't have an include property in your tsconfig.json file. Then your folder structure should be like that:

- app.ts
+ node_modules/
- package.json
- tsconfig.json
- typings.d.ts

But if you have an include property in your tsconfig.json:

{
    "compilerOptions": {
    },
    "exclude"        : [
        "node_modules",
        "**/*spec.ts"
    ], "include"        : [
        "src/**/*"
    ]
}

Then your typings.d.ts should be in the src directory as described in include property

+ node_modules/
- package.json
- tsconfig.json
- src/
    - app.ts
    - typings.d.ts

As In many of the response, You can define a global declaration for all your JSON files.

declare module '*.json' {
    const value: any;
    export default value;
}

but I prefer a more typed version of this. For instance, let's say you have configuration file config.json like that:

{
    "address": "127.0.0.1",
    "port"   : 8080
}

Then we can declare a specific type for it:

declare module 'config.json' {
    export const address: string;
    export const port: number;
}

It's easy to import in your typescript files:

import * as Config from 'config.json';

export class SomeClass {
    public someMethod: void {
        console.log(Config.address);
        console.log(Config.port);
    }
}

But in compilation phase, you should copy JSON files to your dist folder manually. I just add a script property to my package.json configuration:

{
    "name"   : "some project",
    "scripts": {
        "build": "rm -rf dist && tsc && cp src/config.json dist/"
    }
}

Axios handling errors

I tried using the try{}catch{} method but it did not work for me. However, when I switched to using .then(...).catch(...), the AxiosError is caught correctly that I can play around with. When I try the former when putting a breakpoint, it does not allow me to see the AxiosError and instead, says to me that the caught error is undefined, which is also what eventually gets displayed in the UI.

Not sure why this happens I find it very trivial. Either way due to this, I suggest using the conventional .then(...).catch(...) method mentioned above to avoid throwing undefined errors to the user.

Angular - "has no exported member 'Observable'"

Update angular-in-memory-web-api version. The default angular-in-memory-web-api version installed during the tutorial angular-tour-of-heroes was 0.4. It worked like a charm in my case. (Using Angular 7 with RxJS 6)

npm i [email protected]

Uncaught (in promise): Error: StaticInjectorError(AppModule)[options]

I had the same error and I solved it by importing HttpModule in app.module.ts

import { HttpModule } from '@angular/http';

and then in the imports[] array:

HttpModule

Property '...' has no initializer and is not definitely assigned in the constructor

I think you are using the latest version of TypeScript. Please see the section "Strict Class Initialization" in the link.

There are two ways to fix this:

A. If you are using VSCode you need to change the TS version that the editor use.

B. Just initialize the array when you declare it inside the constructor,

makes: any[] = [];

constructor(private makeService: MakeService) { 
   // Initialization inside the constructor
   this.makes = [];
}

Angular 5 ngHide ngShow [hidden] not working

If you can not use *ngif, [class.hide] works in angular 7. example:

<mat-select (selectionChange)="changeFilter($event.value)" multiple [(ngModel)]="selected">
          <mat-option *ngFor="let filter of gridOptions.columnDefs"
                      [class.hide]="filter.headerName=='Action'"  [value]="filter.field">{{filter.headerName}}</mat-option>
        </mat-select>

Converting a POSTMAN request to Curl

Starting from Postman 8 you need to visit here

enter image description here

await is only valid in async function

Yes, await / async was a great concept, but the implementation is completely broken.

For whatever reason, the await keyword has been implemented such that it can only be used within an async method. This is in fact a bug, though you will not see it referred to as such anywhere but right here. The fix for this bug would be to implement the await keyword such that it can only be used TO CALL an async function, regardless of whether the calling function is itself synchronous or asynchronous.

Due to this bug, if you use await to call a real asynchronous function somewhere in your code, then ALL of your functions must be marked as async and ALL of your function calls must use await.

This essentially means that you must add the overhead of promises to all of the functions in your entire application, most of which are not and never will be asynchronous.

If you actually think about it, using await in a function should require the function containing the await keyword TO NOT BE ASYNC - this is because the await keyword is going to pause processing in the function where the await keyword is found. If processing in that function is paused, then it is definitely NOT asynchronous.

So, to the developers of javascript and ECMAScript - please fix the await/async implementation as follows...

  • await can only be used to CALL async functions.
  • await can appear in any kind of function, synchronous or asynchronous.
  • Change the error message from "await is only valid in async function" to "await can only be used to call async functions".

did you register the component correctly? For recursive components, make sure to provide the "name" option

Wasted almost one hour, didn't find a solution, so I wanted to contribute =)

In my case, I was importing WRONGLY the component.. like below:

import { MyComponent } from './components/MyComponent'

But the CORRECT is (without curly braces):

import MyComponent from './components/MyComponent'

js 'types' can only be used in a .ts file - Visual Studio Code using @ts-check

I'm using flow with vscode but had the same problem. I solved it with these steps:

  1. Install the extension Flow Language Support

  2. Disable the built-in TypeScript extension:

    1. Go to Extensions tab
    2. Search for @builtin TypeScript and JavaScript Language Features
    3. Click on Disable

Vue 'export default' vs 'new Vue'

When you declare:

new Vue({
    el: '#app',
    data () {
      return {}
    }
)}

That is typically your root Vue instance that the rest of the application descends from. This hangs off the root element declared in an html document, for example:

<html>
  ...
  <body>
    <div id="app"></div>
  </body>
</html>

The other syntax is declaring a component which can be registered and reused later. For example, if you create a single file component like:

// my-component.js
export default {
    name: 'my-component',
    data () {
      return {}
    }
}

You can later import this and use it like:

// another-component.js
<template>
  <my-component></my-component>
</template>
<script>
  import myComponent from 'my-component'
  export default {
    components: {
      myComponent
    }
    data () {
      return {}
    }
    ...
  }
</script>

Also, be sure to declare your data properties as functions, otherwise they are not going to be reactive.

You should not use <Link> outside a <Router>

I kinda come up with this code :

import React from 'react';
import { render } from 'react-dom';

// import componentns
import Main from './components/Main';
import PhotoGrid from './components/PhotoGrid';
import Single from './components/Single';

// import react router
import { Router, Route, IndexRoute, BrowserRouter, browserHistory} from 'react-router-dom'

class MainComponent extends React.Component {
  render() {
    return (
      <div>
        <BrowserRouter history={browserHistory}>
          <Route path="/" component={Main} >
            <IndexRoute component={PhotoGrid}></IndexRoute>
            <Route path="/view/:postId" component={Single}></Route>
          </Route>
        </BrowserRouter>
      </div>
    );
  }
}

render(<MainComponent />, document.getElementById('root'));

I think the error was because you were rendering the Main component, and the Main component didn't know anything about Router, so you have to render its father component.

ReactJS: Maximum update depth exceeded error

that because you calling toggle inside the render method which will cause to re-render and toggle will call again and re-rendering again and so on

this line at your code

{<td><span onClick={this.toggle()}>Details</span></td>}

you need to make onClick refer to this.toggle not calling it

to fix the issue do this

{<td><span onClick={this.toggle}>Details</span></td>}

Functions are not valid as a React child. This may happen if you return a Component instead of from render

I was getting this from webpack lazy loading like this

import Loader from 'some-loader-component';
const WishlistPageComponent = loadable(() => import(/* webpackChunkName: 'WishlistPage' */'../components/WishlistView/WishlistPage'), {
  fallback: Loader, // warning
});
render() {
    return <WishlistPageComponent />;
}


// changed to this then it's suddenly fine
const WishlistPageComponent = loadable(() => import(/* webpackChunkName: 'WishlistPage' */'../components/WishlistView/WishlistPage'), {
  fallback: '', // all good
});    

Import functions from another js file. Javascript

The following works for me in Firefox and Chrome. In Firefox it even works from file:///

models/course.js

export function Course() {
    this.id = '';
    this.name = '';
};

models/student.js

import { Course } from './course.js';

export function Student() {
    this.firstName = '';
    this.lastName = '';
    this.course = new Course();
};

index.html

<div id="myDiv">
</div>
<script type="module">
    import { Student } from './models/student.js';

    window.onload = function () {
        var x = new Student();
        x.course.id = 1;
        document.getElementById('myDiv').innerHTML = x.course.id;
    }
</script>

How to iterate using ngFor loop Map containing key as string and values as map iteration

As people have mentioned in the comments keyvalue pipe does not retain the order of insertion (which is the primary purpose of Map).

Anyhow, looks like if you have a Map object and want to preserve the order, the cleanest way to do so is entries() function:

<ul>
    <li *ngFor="let item of map.entries()">
        <span>key: {{item[0]}}</span>
        <span>value: {{item[1]}}</span>
    </li>
</ul>

how to format date in Component of angular 5

You can find more information about the date pipe here, such as formats.

If you want to use it in your component, you can simply do

pipe = new DatePipe('en-US'); // Use your own locale

Now, you can simply use its transform method, which will be

const now = Date.now();
const myFormattedDate = this.pipe.transform(now, 'short');

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

Check the namespace from where we are importing

import { MatDialogModule } from **"@angular/material/dialog";**
import { MatCardModule } from **"@angular/material/card";**
import { MatButtonModule } from **"@angular/material/button";**

forEach() in React JSX does not output any HTML

You need to pass an array of element to jsx. The problem is that forEach does not return anything (i.e it returns undefined). So it's better to use map because map returns an array:

class QuestionSet extends Component {
render(){ 
    <div className="container">
       <h1>{this.props.question.text}</h1>
       {this.props.question.answers.map((answer, i) => {     
           console.log("Entered");                 
           // Return the element. Also pass key     
           return (<Answer key={answer} answer={answer} />) 
        })}
}

export default QuestionSet;

Failed to load resource: the server responded with a status of 404 (Not Found) css

Use the following Code:-

../css/main.css

Note: The "../" is shorthand for "The containing directory", or "Up one directory".

If you don't know the previous folder this will be very helpful..

No provider for Http StaticInjectorError

In order to use Http in your app you will need to add the HttpModule to your app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, ErrorHandler } from '@angular/core';
import { HttpModule } from '@angular/http';
...
  imports: [
    BrowserModule,
    HttpModule,
    IonicModule.forRoot(MyApp),
    IonicStorageModule.forRoot()
  ]

EDIT

As mentioned in the comment below, HttpModule is deprecated now, use import { HttpClientModule } from '@angular/common/http'; Make sure HttpClientModule in your imports:[] array

How to get query parameters from URL in Angular 5?

Simple Solution

 // in routing file
       {
            path: 'checkout/:cartId/:addressId',
            loadChildren: () => import('./pages/checkout/checkout.module').then(m => m.CheckoutPageModule)
          },

    // in Component file

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

                 constructor(
                      private _Router: ActivatedRoute
                  ) { }

                  ngOnInit() {
                    this.cartId = this._Router.snapshot.params.cartId;
                    this.addressId = this._Router.snapshot.params.addressId;
                    console.log(this.addressId, "addressId")
                    console.log(this.cartId, "cartId")
                  }

NullInjectorError: No provider for AngularFirestore

Open: ./src/app/app.module.ts
And import Firebase Modules at the top:

import { environment } from '../environments/environment';
import { AngularFireModule } from 'angularfire2';
import { AngularFirestoreModule } from 'angularfire2/firestore';

And VERY IMPORTANT:
Remember to update 'imports' in NgModule:

@NgModule({
  declarations: [
    AppComponent,
    OtherComponent // Add other components here
    ...
  ],
  imports: [
    BrowserModule,
    AngularFireModule.initializeApp(environment.firebase, 'your-APP-name-here'),
    AngularFirestoreModule
  ],
  ...
})

Give it a try, it shall now work.
For detailed information follow the angularfire2 documentation:
https://github.com/angular/angularfire2/blob/master/docs/install-and-setup.md
Good luck!

No provider for HttpClient

In angular github page, this problem was discussed and found solution. https://github.com/angular/angular/issues/20355

Angular 5 Service to read local .json file

import data  from './data.json';
export class AppComponent  {
    json:any = data;
}

See this article for more details.

Add items in array angular 4

Your empList is object type but you are trying to push strings

Try this

this.empList.push({this.name,this.empoloyeeID});

Angular 4: no component factory found,did you add it to @NgModule.entryComponents?

Place components which are created dynamically to entryComponents under @NgModuledecorator function.

@NgModule({
    imports: [
        FormsModule,
        CommonModule,
        DashbaordRoutingModule
    ],
    declarations: [
        MainComponent,
        TestDialog
    ],
    entryComponents: [
        TestDialog
    ]
})

How to read file with async/await properly?

You can easily wrap the readFile command with a promise like so:

async function readFile(path) {
    return new Promise((resolve, reject) => {
      fs.readFile(path, 'utf8', function (err, data) {
        if (err) {
          reject(err);
        }
        resolve(data);
      });
    });
  }

then use:

await readFile("path/to/file");

React-Redux: Actions must be plain objects. Use custom middleware for async actions

For future seekers who might have dropped simple details like me, in my case I just have forgotten to call my action function with parentheses.

actions.js:

export function addNewComponent() {
  return {
    type: ADD_NEW_COMPONENT,
  };
}

myComponent.js:

import React, { useEffect } from 'react';
import { addNewComponent } from '../../redux/actions';

  useEffect(() => {
    dispatch(refreshAllComponents); // <= Here was what I've missed.
  }, []);

I've forgotten to dispatch the action function with (). So doing this solved my issue.

  useEffect(() => {
    dispatch(refreshAllComponents());
  }, []);

Again this might have nothing to do with OP's problem, but I hope I helps people with the same problem as mine.

Angular + Material - How to refresh a data source (mat-table)

Best way to do this is by adding an additional observable to your Datasource implementation.

In the connect method you should already be using Observable.merge to subscribe to an array of observables that include the paginator.page, sort.sortChange, etc. You can add a new subject to this and call next on it when you need to cause a refresh.

something like this:

export class LanguageDataSource extends DataSource<any> {

    recordChange$ = new Subject();

    constructor(private languages) {
      super();
    }

    connect(): Observable<any> {

      const changes = [
        this.recordChange$
      ];

      return Observable.merge(...changes)
        .switchMap(() => return Observable.of(this.languages));
    }

    disconnect() {
      // No-op
    }
}

And then you can call recordChange$.next() to initiate a refresh.

Naturally I would wrap the call in a refresh() method and call it off of the datasource instance w/in the component, and other proper techniques.

phpMyAdmin ERROR: mysqli_real_connect(): (HY000/1045): Access denied for user 'pma'@'localhost' (using password: NO)

My default 3306 port was in use, so Ive changed it to 8111, then I had this error. Ive fixed it by adding

$cfg['Servers'][$i]['port'] = '8111';

into config.inc.php . If you are using different port number then set yours.

react-router (v4) how to go back?

Each answer here has parts of the total solution. Here's the complete solution that I used to get it to work inside of components deeper than where Route was used:

import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'

^ You need that second line to import function and to export component at bottom of page.

render() {
  return (
  ...
    <div onClick={() => this.props.history.goBack()}>GO BACK</div>
  )
}

^ Required the arrow function vs simply onClick={this.props.history.goBack()}

export default withRouter(MyPage)

^ wrap your component's name with 'withRouter()'

The difference between "require(x)" and "import x"

The major difference between require and import, is that require will automatically scan node_modules to find modules, but import, which comes from ES6, won't.

Most people use babel to compile import and export, which makes import act the same as require.

The future version of Node.js might support import itself (actually, the experimental version already does), and judging by Node.js' notes, import won't support node_modules, it base on ES6, and must specify the path of the module.

So I would suggest you not use import with babel, but this feature is not yet confirmed, it might support node_modules in the future, who would know?


For reference, below is an example of how babel can convert ES6's import syntax to CommonJS's require syntax.

Say the fileapp_es6.js contains this import:

import format from 'date-fns/format';

This is a directive to import the format function from the node package date-fns.

The related package.json file could contain something like this:

"scripts": {
    "start": "node app.js",
    "build-server-file": "babel app_es6.js --out-file app.js",
    "webpack": "webpack"
}

The related .babelrc file could be something like this:

{
    "presets": [
        [
            "env",
            {
                "targets":
                {
                    "node": "current"
                }
            }
        ]
    ]
}

This build-server-file script defined in the package.json file is a directive for babel to parse the app_es6.js file and output the file app.js.

After running the build-server-file script, if you open app.js and look for the date-fns import, you will see it has been converted into this:

var _format = require("date-fns/format");

var _format2 = _interopRequireDefault(_format);

Most of that file is gobbledygook to most humans, however computers understand it.


Also for reference, as an example of how a module can be created and imported into your project, if you install date-fns and then open node_modules/date-fns/get_year/index.js you can see it contains:

var parse = require('../parse/index.js')

function getYear (dirtyDate) {
  var date = parse(dirtyDate)
  var year = date.getFullYear()
  return year
}

module.exports = getYear

Using the babel process above, your app_es6.js file could then contain:

import getYear from 'date-fns/get_year';

// Which year is 2 July 2014?
var result = getYear(new Date(2014, 6, 2))
//=> 2014

And babel would convert the imports to:

var _get_year = require("date-fns/get_year");

var _get_year2 = _interopRequireDefault(_get_year);

And handle all references to the function accordingly.

Angular - res.json() is not a function

Don't need to use this method:

 .map((res: Response) => res.json() );

Just use this simple method instead of the previous method. hopefully you'll get your result:

.map(res => res );

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

In my case, I accidentally added the package in the declaration but it should be in imports.

React - clearing an input value after form submit

You are having a controlled component where input value is determined by this.state.city. So once you submit you have to clear your state which will clear your input automatically.

onHandleSubmit(e) {
    e.preventDefault();
    const city = this.state.city;
    this.props.onSearchTermChange(city);
    this.setState({
      city: ''
    });
}

ERROR Error: No value accessor for form control with unspecified name attribute on switch

I also received this error when I named one of my component inputs 'formControl'. Probably it's reserved for something else. If you want to pass FormControl object between components, use it like that:

@Input() control: FormControl;

not like this:

@Input() formControl: FormControl;

Weird - but working :)

ERROR in ./node_modules/css-loader?

Laravel Mix 4 switches from node-sass to dart-sass (which may not compile as you would expect, OR you have to deal with the issues one by one)

OR

npm install node-sass


mix.sass('resources/sass/app.sass', 'public/css', {
implementation: require('node-sass')
});

https://laravel-mix.com/docs/4.0/upgrade

Failed to install android-sdk: "java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema"

I faced the same problem. Though I am a little bit backdated developer (Still using windows to develop :P)

To solve this issue on windows :

STEP 1: Install jdk 8 if it wasn't installed (jdk 9 or 11 doesn't work but you may have them installed for using in other dev uses).

Very simple using Chocolatey:

choco install jdk8

(If installed using Chocolatey, skip steps 2 and 3)

STEP 2: Go to the Environment variables settings and set JAVA_HOME TO jdk 8's installation directory.

JAVA_HOME

STEP 3: Go to path variable and add bin directory of jdk 8 and move it to top.

Path_varriable

STEP 4: Close any open terminal sessions and restart a new session

OPTIONAL STEP 5: Depending on your objective in the terminal run (may need to add sdkmanager to path or just navigate to the directory):

sdkmanager --update

That's all! :O Enjoy fluttering! :D

Enable/disable buttons with Angular

Set a property for the current lesson: currentLesson. It will hold, obviously, the 'number' of the choosen lesson. On each button click, set the currentLesson value to 'number'/ order of the button, i.e. for the first button, it will be '1', for the second '2' and so on. Each button now can be disabled with [disabled] attribute, if it the currentLesson is not the same as it's order.

HTML

  <button  (click)="currentLesson = '1'"
         [disabled]="currentLesson !== '1'" class="primair">
           Start lesson</button>
  <button (click)="currentLesson = '2'"
         [disabled]="currentLesson !== '2'" class="primair">
           Start lesson</button>
 .....//so on

Typescript

currentLesson:string;

  classes = [
{
  name: 'string',
  level: 'string',
  code: 'number',
  currentLesson: '1'
}]

constructor(){
  this.currentLesson=this.classes[0].currentLesson
}

DEMO

Putting everything in a loop:

HTML

<div *ngFor="let class of classes; let i = index">
   <button [disabled]="currentLesson !== i + 1" class="primair">
           Start lesson {{i +  1}}</button>
</div>

Typescript

currentLesson:string;

classes = [
{
  name: 'Lesson1',
  level: 1,
  code: 1,
},{
  name: 'Lesson2',
  level: 1,
  code: 2,
},
{
  name: 'Lesson3',
  level: 2,
  code: 3,
}]

DEMO

Vuex - Computed property "name" was assigned to but it has no setter

If you're going to v-model a computed, it needs a setter. Whatever you want it to do with the updated value (probably write it to the $store, considering that's what your getter pulls it from) you do in the setter.

If writing it back to the store happens via form submission, you don't want to v-model, you just want to set :value.

If you want to have an intermediate state, where it's saved somewhere but doesn't overwrite the source in the $store until form submission, you'll need to create such a data item.

Vuex - passing multiple parameters to mutation

Mutations expect two arguments: state and payload, where the current state of the store is passed by Vuex itself as the first argument and the second argument holds any parameters you need to pass.

The easiest way to pass a number of parameters is to destruct them:

mutations: {
    authenticate(state, { token, expiration }) {
        localStorage.setItem('token', token);
        localStorage.setItem('expiration', expiration);
    }
}

Then later on in your actions you can simply

store.commit('authenticate', {
    token,
    expiration,
});

No converter found capable of converting from type to type

Turns out, when the table name is different than the model name, you have to change the annotations to:

@Entity
@Table(name = "table_name")
class WhateverNameYouWant {
    ...

Instead of simply using the @Entity annotation.

What was weird for me, is that the class it was trying to convert to didn't exist. This worked for me.

npm WARN ... requires a peer of ... but none is installed. You must install peer dependencies yourself

I had a similar issue and solved after running these instructions!

npm install npm -g
npm install --save-dev @angular/cli@latest
npm install
npm start

exporting multiple modules in react.js

You can have only one default export which you declare like:

export default App; or export default class App extends React.Component {...

and later do import App from './App'

If you want to export something more you can use named exports which you declare without default keyword like:

export {
  About,
  Contact,
}

or:

export About;
export Contact;

or:

export const About = class About extends React.Component {....
export const Contact = () => (<div> ... </div>);

and later you import them like:

import App, { About, Contact } from './App';

EDIT:

There is a mistake in the tutorial as it is not possible to make 3 default exports in the same main.js file. Other than that why export anything if it is no used outside the file?. Correct main.js :

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Link, browserHistory, IndexRoute  } from 'react-router'

class App extends React.Component {
...
}

class Home extends React.Component {
...
}


class About extends React.Component {
...
}


class Contact extends React.Component {
...
}


ReactDOM.render((
   <Router history = {browserHistory}>
      <Route path = "/" component = {App}>
         <IndexRoute component = {Home} />
         <Route path = "home" component = {Home} />
         <Route path = "about" component = {About} />
         <Route path = "contact" component = {Contact} />
      </Route>
   </Router>

), document.getElementById('app'))

EDIT2:

another thing is that this tutorial is based on react-router-V3 which has different api than v4.

Catching errors in Angular HttpClient

You probably want to have something like this:

this.sendRequest(...)
.map(...)
.catch((err) => {
//handle your error here
})

It highly depends also how do you use your service but this is the basic case.

Angular 4 - Observable catch error

With angular 6 and rxjs 6 Observable.throw(), Observable.off() has been deprecated instead you need to use throwError

ex :

return this.http.get('yoururl')
  .pipe(
    map(response => response.json()),
    catchError((e: any) =>{
      //do your processing here
      return throwError(e);
    }),
  );

How to get param from url in angular 4?

In angular, They separate it into 2 kind of url.

  1. URL pattern /heroes/:limit. Example: /heroes/20

    • You can get raw value by using route.snapshot.paramMap.get.
    • Subscribe from route.paramMap to get params
  2. URL pattern /heroes. Example: /heroes?limit=20

    • You can get raw value by using route.snapshot.queryParamMap

Reference: All you need to know about Angular parameters

webpack: Module not found: Error: Can't resolve (with relative path)

while importing libraries use the exact path to a file, including the directory relative to the current file, for example:

import Footer from './Footer/index.jsx'
import AddTodo from '../containers/AddTodo/index.jsx'
import VisibleTodoList from '../containers/VisibleTodoList/index.jsx'

Hope this may help

React Router Pass Param to Component

Since react-router v5.1 with hooks:

import { useParams } from 'react-router';

export default function DetailsPage() {
  const { id } = useParams();
}

See https://reacttraining.com/blog/react-router-v5-1/

How can I use an ES6 import in Node.js?

Using the .mjs extension (as suggested in the accepted answer) in order to enable ECMAScript modules works. However, with Node.js v12, you can also enable this feature globally in your package.json file.

The official documentation states:

import statements of .js and extensionless files are treated as ES modules if the nearest parent package.json contains "type": "module".

{
  "type": "module",
  "main": "./src/index.js"
}

(Of course you still have to provide the flag --experimental-modules when starting your application.)

Add class to an element in Angular 4

If you need that each div will have its own toggle and don't want clicks to affect other divs, do this:

Here's what I did to solve this...

<div [ngClass]="{'teaser': !teaser_1 }" (click)="teaser_1=!teaser_1">
...content...
</div>

<div [ngClass]="{'teaser': !teaser_2 }" (click)="teaser_2=!teaser_2">
...content...
</div>

<div [ngClass]="{'teaser': !teaser_3 }" (click)="teaser_3=!teaser_3">
...content...
</div>

it requires custom numbering which sucks, but it works.

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'

*NgIf can create problem here , so either use display none css or easier way is to Use [hidden]="!condition"

Refused to load the font 'data:font/woff.....'it violates the following Content Security Policy directive: "default-src 'self'". Note that 'font-src'

To fix this specific error, CSP should include this:

font-src 'self' data:;

So, index.html meta should read:

<meta http-equiv="Content-Security-Policy" content="font-src 'self' data:; img-src 'self' data:; default-src 'self' http://121.0.0:3000/">

How to use paginator from material angular?

Another way to link Angular Paginator with the data table using Slice Pipe.Here data is fetched only once from server.

View:

 <div class="col-md-3" *ngFor="let productObj of productListData | 
     slice: lowValue : highValue">
       //actual data dispaly  
 </div>

<mat-paginator [length]="productListData.length" [pageSize]="pageSize" 
   (page)="pageEvent = getPaginatorData($event)">
</mat-paginator> 

Component

    pageIndex:number = 0;
    pageSize:number = 50;
    lowValue:number = 0;
    highValue:number = 50;       

  getPaginatorData(event){
     console.log(event);
     if(event.pageIndex === this.pageIndex + 1){
        this.lowValue = this.lowValue + this.pageSize;
        this.highValue =  this.highValue + this.pageSize;
       }
    else if(event.pageIndex === this.pageIndex - 1){
       this.lowValue = this.lowValue - this.pageSize;
       this.highValue =  this.highValue - this.pageSize;
      }   
       this.pageIndex = event.pageIndex;
 }

Cannot find the '@angular/common/http' module

Important: HttpClientModule is for Angular 4.3.0 and above. Check @Maximus' comments and @Pengyy's answer for more info.


Original answer:

You need to inject HttpClient in your component/service not the module. If you import HttpClientModule in your @NgModule

// app.module.ts:
 
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
 
// Import HttpClientModule from @angular/common/http
import {HttpClientModule} from '@angular/common/http';
 
@NgModule({
  imports: [
    BrowserModule,
    // Include it under 'imports' in your application module
    // after BrowserModule.
    HttpClientModule,
  ],
})
export class MyAppModule {}

So change

constructor(private httpClient: HttpModule) {}

to

constructor(private httpClient: HttpClient) {}

as it's been written in the documentation


However, since you imported the HttpModule

you need to inject constructor(private httpClient: Http) as @Maximus stated in the comments and @Pengyy in this answer.

And for more info on differences between HttpModule and HttpClientModule, check this answer

Get current url in Angular

With pure JavaScript:

console.log(window.location.href)

Using Angular:

this.router.url

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

@Component({
    template: 'The href is: {{href}}'
    /*
    Other component settings
    */
})
export class Component {
    public href: string = "";

    constructor(private router: Router) {}

    ngOnInit() {
        this.href = this.router.url;
        console.log(this.router.url);
    }
}

The plunkr is here: https://plnkr.co/edit/0x3pCOKwFjAGRxC4hZMy?p=preview

How to import and use image in a Vue single file component?

I encounter a problem in quasar which is a mobile framework based vue, the tidle syntax ~assets/cover.jpg works in normal component, but not in my dynamic defined component, that is defined by

let c=Vue.component('compName',{...})

finally this work:

    computed: {
      coverUri() {
        return require('../assets/cover.jpg');
      }
    }
<q-img class="coverImg" :src="coverUri" :height="uiBook.coverHeight" spinner-color="white"/>

according to the explain at https://quasar.dev/quasar-cli/handling-assets

In *.vue components, all your templates and CSS are parsed by vue-html-loader and css-loader to look for asset URLs. For example, in <img src="./logo.png"> and background: url(./logo.png), "./logo.png" is a relative asset path and will be resolved by Webpack as a module dependency.

phpMyAdmin access denied for user 'root'@'localhost' (using password: NO)

You may had set different passwords for user 'root' or have been changed your password. I had same error as :

mysqli_real_connect(): (HY000/1045): Access denied for user 'root'@'localhost' (using password: YES)

and I found that my root password for phpmyAdmin is not same on both 'mysql' and 'phpmyadmin' databases, so I updated my password for 'phpmyadmin' database same as 'mysql' database as follow:

sudo gedit /etc/phpmyadmin/config-db.php

and update the fields

$dbuser='root';

$dbpass='myNewPassword'; <-- update your new password here

Best wishes!

Specifying onClick event type with Typescript and React.Konva

You should be using event.currentTarget. React is mirroring the difference between currentTarget (element the event is attached to) and target (the element the event is currently happening on). Since this is a mouse event, type-wise the two could be different, even if it doesn't make sense for a click.

https://github.com/facebook/react/issues/5733 https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget

Input type number "only numeric value" validation

In HTML file you can add ngIf for you pattern like this

<div class="form-control-feedback" *ngIf="Mobile.errors && (Mobile.dirty || Mobile.touched)">
        <p *ngIf="Mobile.errors.pattern" class="text-danger">Number Only</p>
      </div>

In .ts file you can add the Validators pattern - "^[0-9]*$"

this.Mobile = new FormControl('', [
  Validators.required,
  Validators.pattern("^[0-9]*$"),
  Validators.minLength(8),
]);

Uncaught Error: Unexpected module 'FormsModule' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation

FormsModule should be added at imports array not declarations array.

  • imports array is for importing modules such as BrowserModule, FormsModule, HttpModule
  • declarations array is for your Components, Pipes, Directives

refer below change:

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

How do I test axios in Jest?

I used axios-mock-adapter. In this case the service is described in ./chatbot. In the mock adapter you specify what to return when the API endpoint is consumed.

import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import chatbot from './chatbot';

describe('Chatbot', () => {
    it('returns data when sendMessage is called', done => {
        var mock = new MockAdapter(axios);
        const data = { response: true };
        mock.onGet('https://us-central1-hutoma-backend.cloudfunctions.net/chat').reply(200, data);

        chatbot.sendMessage(0, 'any').then(response => {
            expect(response).toEqual(data);
            done();
        });
    });
});

You can see it the whole example here:

Service: https://github.com/lnolazco/hutoma-test/blob/master/src/services/chatbot.js

Test: https://github.com/lnolazco/hutoma-test/blob/master/src/services/chatbot.test.js

Vue js error: Component template should contain exactly one root element

Component template should contain exactly one root element. If you are using v-if on multiple elements, use v-else-if to chain them instead.

The right approach is

<template>
  <div> <!-- The root -->
    <p></p> 
    <p></p>
  </div>
</template>

The wrong approach

<template> <!-- No root Element -->
    <p></p> 
    <p></p>
</template>

Multi Root Components

The way around to that problem is using functional components, they are components where you have to pass no reactive data means component will not be watching for any data changes as well as not updating it self when something in parent component changes.

As this is a work around it comes with a price, functional components don't have any life cycle hooks passed to it, they are instance less as well you cannot refer to this anymore and everything is passed with context.

Here is how you can create a simple functional component.

Vue.component('my-component', {
    // you must set functional as true
  functional: true,
  // Props are optional
  props: {
    // ...
  },
  // To compensate for the lack of an instance,
  // we are now provided a 2nd context argument.
  render: function (createElement, context) {
    // ...
  }
})

Now that we have covered functional components in some detail lets cover how to create multi root components, for that I am gonna present you with a generic example.

<template>
 <ul>
     <NavBarRoutes :routes="persistentNavRoutes"/>
     <NavBarRoutes v-if="loggedIn" :routes="loggedInNavRoutes" />
     <NavBarRoutes v-else :routes="loggedOutNavRoutes" />
 </ul>
</template>

Now if we take a look at NavBarRoutes template

<template>
 <li
 v-for="route in routes"
 :key="route.name"
 >
 <router-link :to="route">
 {{ route.title }}
 </router-link>
 </li>
</template>

We cant do some thing like this we will be violating single root component restriction

Solution Make this component functional and use render

{
functional: true,
render(h, { props }) {
 return props.routes.map(route =>
  <li key={route.name}>
    <router-link to={route}>
      {route.title}
    </router-link>
  </li>
 )
}

Here you have it you have created a multi root component, Happy coding

Reference for more details visit: https://blog.carbonteq.com/vuejs-create-multi-root-components/

How to convert Observable<any> to array[]

You will need to subscribe to your observables:

this.CountryService.GetCountries()
    .subscribe(countries => {
        this.myGridOptions.rowData = countries as CountryData[]
    })

And, in your html, wherever needed, you can pass the async pipe to it.

Angular 4: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'

You get this message when you've used async in your template, but are referring to an object that isn't an Observable.

So for examples sake, lets' say I had these properties in my class:

job:Job
job$:Observable<Job>

Then in my template, I refer to it this way:

{{job | async }}

instead of:

{{job$ | async }}

You wouldn't need the job:Job property if you use the async pipe, but it serves to illustrate a cause of the error.

Component is not part of any NgModule or the module has not been imported into your module

Check your Lazy module , i haved imported AppRoutingModule in the lazy module. After removing the import and imports of AppRoutingModule, Mine started working.

import { AppRoutingModule } from '../app-routing.module'; 

Angular CLI - Please add a @NgModule annotation when using latest

In my case, I created a new ChildComponent in Parentcomponent whereas both in the same module but Parent is registered in a shared module so I created ChildComponent using CLI which registered Child in the current module but my parent was registered in the shared module.

So register the ChildComponent in Shared Module manually.

Angular 4 Pipe Filter

Pipes in Angular 2+ are a great way to transform and format data right from your templates.

Pipes allow us to change data inside of a template; i.e. filtering, ordering, formatting dates, numbers, currencies, etc. A quick example is you can transfer a string to lowercase by applying a simple filter in the template code.

List of Built-in Pipes from API List Examples

{{ user.name | uppercase }}

Example of Angular version 4.4.7. ng version


Custom Pipes which accepts multiple arguments.

HTML « *ngFor="let student of students | jsonFilterBy:[searchText, 'name'] "
TS   « transform(json: any[], args: any[]) : any[] { ... }

Filtering the content using a Pipe « json-filter-by.pipe.ts

import { Pipe, PipeTransform, Injectable } from '@angular/core';

@Pipe({ name: 'jsonFilterBy' })
@Injectable()
export class JsonFilterByPipe implements PipeTransform {

  transform(json: any[], args: any[]) : any[] {
    var searchText = args[0];
    var jsonKey = args[1];

    // json = undefined, args = (2) [undefined, "name"]
    if(searchText == null || searchText == 'undefined') return json;
    if(jsonKey    == null || jsonKey    == 'undefined') return json;

    // Copy all objects of original array into new Array.
    var returnObjects = json;
    json.forEach( function ( filterObjectEntery ) {

      if( filterObjectEntery.hasOwnProperty( jsonKey ) ) {
        console.log('Search key is available in JSON object.');

        if ( typeof filterObjectEntery[jsonKey] != "undefined" && 
        filterObjectEntery[jsonKey].toLowerCase().indexOf(searchText.toLowerCase()) > -1 ) {
            // object value contains the user provided text.
        } else {
            // object didn't match a filter value so remove it from array via filter
            returnObjects = returnObjects.filter(obj => obj !== filterObjectEntery);
        }
      } else {
        console.log('Search key is not available in JSON object.');
      }

    })
    return returnObjects;
  }
}

Add to @NgModule « Add JsonFilterByPipe to your declarations list in your module; if you forget to do this you'll get an error no provider for jsonFilterBy. If you add to module then it is available to all the component's of that module.

@NgModule({
  imports: [
    CommonModule,
    RouterModule,
    FormsModule, ReactiveFormsModule,
  ],
  providers: [ StudentDetailsService ],
  declarations: [
    UsersComponent, UserComponent,

    JsonFilterByPipe,
  ],
  exports : [UsersComponent, UserComponent]
})
export class UsersModule {
    // ...
}

File Name: users.component.ts and StudentDetailsService is created from this link.

import { MyStudents } from './../../services/student/my-students';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { StudentDetailsService } from '../../services/student/student-details.service';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: [ './users.component.css' ],

  providers:[StudentDetailsService]
})
export class UsersComponent implements OnInit, OnDestroy  {

  students: MyStudents[];
  selectedStudent: MyStudents;

  constructor(private studentService: StudentDetailsService) { }

  ngOnInit(): void {
    this.loadAllUsers();
  }
  ngOnDestroy(): void {
    // ONDestroy to prevent memory leaks
  }

  loadAllUsers(): void {
    this.studentService.getStudentsList().then(students => this.students = students);
  }

  onSelect(student: MyStudents): void {
    this.selectedStudent = student;
  }

}

File Name: users.component.html

<div>
    <br />
    <div class="form-group">
        <div class="col-md-6" >
            Filter by Name: 
            <input type="text" [(ngModel)]="searchText" 
                   class="form-control" placeholder="Search By Category" />
        </div>
    </div>

    <h2>Present are Students</h2>
    <ul class="students">
    <li *ngFor="let student of students | jsonFilterBy:[searchText, 'name'] " >
        <a *ngIf="student" routerLink="/users/update/{{student.id}}">
            <span class="badge">{{student.id}}</span> {{student.name | uppercase}}
        </a>
    </li>
    </ul>
</div>

Jest spyOn function called

You're almost there. Although I agree with @Alex Young answer about using props for that, you simply need a reference to the instance before trying to spy on the method.

describe('my sweet test', () => {
 it('clicks it', () => {
    const app = shallow(<App />)
    const instance = app.instance()
    const spy = jest.spyOn(instance, 'myClickFunc')

    instance.forceUpdate();    

    const p = app.find('.App-intro')
    p.simulate('click')
    expect(spy).toHaveBeenCalled()
 })
})

Docs: http://airbnb.io/enzyme/docs/api/ShallowWrapper/instance.html

How to listen for 'props' changes

I use props and variables computed properties if I need create logic after to receive the changes

export default {
name: 'getObjectDetail',
filters: {},
components: {},
props: {
    objectDetail: {
      type: Object,
      required: true
    }
},
computed: {
    _objectDetail: {
        let value = false
        ...

        if (someValidation)
        ...
    }
}

'router-outlet' is not a known element

There are two ways. 1. if you want to implement app.module.ts file then:

_x000D_
_x000D_
import { Routes, RouterModule } from '@angular/router';_x000D_
_x000D_
const appRoutes: Routes = [_x000D_
  { path: '', component: HomeComponent },_x000D_
  { path: 'user', component: UserComponent },_x000D_
  { path: 'server', component: ServerComponent }_x000D_
];_x000D_
_x000D_
@NgModule({_x000D_
  imports: [_x000D_
    RouterModule.forRoot(appRoutes)_x000D_
  ]_x000D_
})_x000D_
export class AppModule { }
_x000D_
_x000D_
_x000D_

  1. if you want to implement app-routing.module.ts (Separated Routing Module) file then:

_x000D_
_x000D_
//app-routing.module.ts_x000D_
import { NgModule } from '@angular/core';_x000D_
import { Routes, RouterModule } from '@angular/router';_x000D_
_x000D_
const appRoutes: Routes = [_x000D_
  { path: '', component: HomeComponent },_x000D_
  { path: 'users', component: UsersComponent },_x000D_
  { path: 'servers', component: ServersComponent }_x000D_
];_x000D_
_x000D_
@NgModule({_x000D_
  imports: [_x000D_
    RouterModule.forRoot(appRoutes)_x000D_
  ],_x000D_
  exports: [RouterModule]_x000D_
})_x000D_
export class AppRoutingModule { }_x000D_
_x000D_
//................................................................_x000D_
_x000D_
//app.module.ts_x000D_
import { AppRoutingModule } from './app-routing.module';_x000D_
_x000D_
@NgModule({_x000D_
  imports: [_x000D_
    AppRoutingModule_x000D_
  ]_x000D_
})_x000D_
export class AppModule { }
_x000D_
_x000D_
_x000D_

Getter and Setter of Model object in Angular 4

The way you declare the date property as an input looks incorrect but its hard to say if it's the only problem without seeing all your code. Rather than using @Input('date') declare the date property like so: private _date: string;. Also, make sure you are instantiating the model with the new keyword. Lastly, access the property using regular dot notation.

Check your work against this example from https://www.typescriptlang.org/docs/handbook/classes.html :

let passcode = "secret passcode";

class Employee {
    private _fullName: string;

    get fullName(): string {
        return this._fullName;
    }

    set fullName(newName: string) {
        if (passcode && passcode == "secret passcode") {
            this._fullName = newName;
        }
        else {
            console.log("Error: Unauthorized update of employee!");
        }
    }
}

let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
    console.log(employee.fullName);
}

And here is a plunker demonstrating what it sounds like you're trying to do: https://plnkr.co/edit/OUoD5J1lfO6bIeME9N0F?p=preview

React JS Error: is not defined react/jsx-no-undef

its very similar with nodejs

var User= require('./Users');

in this case its React:

import User from './User'

right now you can use

return (
      <Users></Users>
    )

Can't resolve module (not found) in React.js

You need to be in project folder, if you are in src or public you have to come out of those folders. Suppose your react-project name is 'hello-react' then cd hello-react

Angular 2 'component' is not a known element

Route modules (did not saw this as an answer)

First check: if you have declared- and exported the component inside its module, imported the module where you want to use it and named the component correctly inside the HTML.

Otherwise, you might miss a module inside your routing module:
When you have a routing module with a route that routes to a component from another module, it is important that you import that module within that route module. Otherwise the Angular CLI will show the error: component is not a known element.

For example

1) Having the following project structure:

+---core
¦   +---sidebar
¦           sidebar.component.ts
¦           sidebar.module.ts
¦
+---todos
    ¦   todos-routing.module.ts
    ¦   todos.module.ts
    ¦
    +---pages
            edit-todo.component.ts
            edit-todo.module.ts

2) Inside the todos-routing.module.ts you have a route to the edit.todo.component.ts (without importing its module):

  {
    path: 'edit-todo/:todoId',
    component: EditTodoComponent,
  },

The route will just work fine! However when importing the sidebar.module.ts inside the edit-todo.module.ts you will get an error: app-sidebar is not a known element.

Fix: Since you have added a route to the edit-todo.component.ts in step 2, you will have to add the edit-todo.module.ts as an import, after that the imported sidebar component will work!

Room - Schema export directory is not provided to the annotation processor so we cannot export the schema

Above answers are correct. This version is easy to follow:

Because "Schema export directory is not provided to the annotation processor", So we need to provide the directory for schema export:

Step [1] In your file which extends the RoomDatabase, change the line to:

`@Database(entities = ???.class,version = 1, exportSchema = true)`

Or

`@Database(entities = ???.class,version = 1)` 

(because the default value is always true)

Step [2] In your build.gradle(project:????) file, inside the defaultConfig{ } (which is inside android{ } big section), add the javaCompileOptions{ } section, it will be like:

         android{
                defaultConfig{
                      //javaComplieOptions SECTION
                      javaCompileOptions {
                            annotationProcessorOptions {
                                     arguments = ["room.schemaLocation":"$projectDir/schemas".toString()]
                            }
                       }
                      //Other SECTION
                      ...
                }
         }

$projectDir:is a variable name, you cannot change it. it will get your own project directory

schemas:is a string, you can change it to any you like. For example: "$projectDir/MyOwnSchemas".toString()

React-router v4 this.props.history.push(...) not working

You can get access to the history object's properties and the closest 's match via the withRouter higher-order component. withRouter will pass updated match, location, and history props to the wrapped component whenever it renders.

import React, { Component } from 'react'
import { withRouter } from 'react-router'; 
// you can also import "withRouter" from 'react-router-dom';

class Example extends Component {
    render() {
        const { match, location, history } = this.props
        return (
            <div>
                <div>You are now at {location.pathname}</div>
                <button onClick={() => history.push('/')}>{'Home'}</button>
            </div>
        )
    }
}


export default withRouter(Example)

Home does not contain an export named Home

You can use two ways to resolve this problem, first way that i think it as best way is replace importing segment of your code with bellow one:

import Home from './layouts/Home'

or export your component without default which is called named export like this

import React, { Component } from 'react';

class Home extends Component{
    render(){
        return(
        <p className="App-intro">
          Hello Man
        </p>
        )
    }
} 

export {Home};

Android Room - simple select query - Cannot access database on the main thread

As asyncTask are deprecated we may use executor service. OR you can also use ViewModel with LiveData as explained in other answers.

For using executor service, you may use something like below.

public class DbHelper {

    private final Executor executor = Executors.newSingleThreadExecutor();

    public void fetchData(DataFetchListener dataListener){
        executor.execute(() -> {
                Object object = retrieveAgent(agentId);
                new Handler(Looper.getMainLooper()).post(() -> {
                        dataListener.onFetchDataSuccess(object);
                });
        });
    }
}

Main Looper is used, so that you can access UI element from onFetchDataSuccess callback.

Load local images in React.js

In order to load local images to your React.js application, you need to add require parameter in media sections like or Image tags, as below:

image={require('./../uploads/temp.jpg')}

Kubernetes service external ip pending

If it is your private k8s cluster, MetalLB would be a better fit. Below are the steps.

Step 1: Install MetalLB in your cluster

kubectl apply -f https://raw.githubusercontent.com/metallb/metallb/v0.9.3/manifests/namespace.yaml
kubectl apply -f https://raw.githubusercontent.com/metallb/metallb/v0.9.3/manifests/metallb.yaml
# On first install only
kubectl create secret generic -n metallb-system memberlist --from-literal=secretkey="$(openssl rand -base64 128)"

Step 2: Configure it by using a configmap

apiVersion: v1
kind: ConfigMap
metadata:
  namespace: metallb-system
  name: config
data:
  config: |
    address-pools:
    - name: default
      protocol: layer2
      addresses:
      - 172.42.42.100-172.42.42.105 #Update this with your Nodes IP range 

Step 3: Create your service to get an external IP (would be a private IP though).

FYR:

Before MetalLB installation: enter image description here

After MetalLB installation: enter image description here

enter image description here

Could not find com.android.tools.build:gradle:3.0.0-alpha1 in circle ci

I did this:

click SDk Manager:

enter image description here

Change in updates to Canary Channel, check and update it...

enter image description here

After go in build.gradle and change the compile version to 26.0.0-beta2:

enter image description here

After go in gradle/build.gradle and change dependencies classpath 'com.android.tools.build:gradle:3.0.0-alpha7':

enter image description here

After sync the project... It works to me! I hope I've helped... tks!

Load json from local file with http.get() in angular 2

MY OWN SOLUTION

I created a new component called test in this folder:

enter image description here

I also created a mock called test.json in the assests folder created by angular cli (important):

enter image description here

This mock looks like this:

[
        {
            "id": 1,
            "name": "Item 1"
        },
        {
            "id": 2,
            "name": "Item 2"
        },
        {
            "id": 3,
            "name": "Item 3"
        }
]

In the controller of my component test import follow rxjs like this

import 'rxjs/add/operator/map'

This is important, because you have to map your response from the http get call, so you get a json and can loop it in your ngFor. Here is my code how I load the mock data. I used http get and called my path to the mock with this path this.http.get("/assets/mock/test/test.json"). After this i map the response and subscribe it. Then I assign it to my variable items and loop it with ngFor in my template. I also export the type. Here is my whole controller code:

import { Component, OnInit } from "@angular/core";
import { Http, Response } from "@angular/http";
import 'rxjs/add/operator/map'

export type Item = { id: number, name: string };

@Component({
  selector: "test",
  templateUrl: "./test.component.html",
  styleUrls: ["./test.component.scss"]
})
export class TestComponent implements OnInit {
  items: Array<Item>;

  constructor(private http: Http) {}

  ngOnInit() {
    this.http
      .get("/assets/mock/test/test.json")
      .map(data => data.json() as Array<Item>)
      .subscribe(data => {
        this.items = data;
        console.log(data);
      });
  }
}

And my loop in it's template:

<div *ngFor="let item of items">
  {{item.name}}
</div>

It works as expected! I can now add more mock files in the assests folder and just change the path to get it as json. Notice that you have also to import the HTTP and Response in your controller. The same in you app.module.ts (main) like this:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule, JsonpModule } from '@angular/http';


import { AppComponent } from './app.component';
import { TestComponent } from './components/molecules/test/test.component';


@NgModule({
  declarations: [
    AppComponent,
    TestComponent
  ],
  imports: [
    BrowserModule,
    HttpModule,
    JsonpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Angular: 'Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays'

I was the same problem and as Pengyy suggest, that is the fix. Thanks a lot.

My problem on the Browser Console:

Image Problem on Browser Console

PortafolioComponent.html:3 ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed(…)

In my case my code fix was:

//productos.service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

@Injectable()
export class ProductosService {

  productos:any[] = [];
  cargando:boolean = true;

  constructor( private http:Http) {
    this.cargar_productos();
  }

  public cargar_productos(){

    this.cargando = true;

    this.http.get('https://webpage-88888a1.firebaseio.com/productos.json')
      .subscribe( res => {
        console.log(res.json());
        this.cargando = false;
        this.productos = res.json().productos; // Before this.productos = res.json(); 
      });
  }

}

Angular 4/5/6 Global Variables

I use environment for that. It works automatically and you don't have to create new injectable service and most usefull for me, don't need to import via constructor.

1) Create environment variable in your environment.ts

export const environment = {
    ...
    // runtime variables
    isContentLoading: false,
    isDeployNeeded: false
}

2) Import environment.ts in *.ts file and create public variable (i.e. "env") to be able to use in html template

import { environment } from 'environments/environment';

@Component(...)
export class TestComponent {
    ...
    env = environment;
}

3) Use it in template...

<app-spinner *ngIf='env.isContentLoading'></app-spinner>

in *.ts ...

env.isContentLoading = false 

(or just environment.isContentLoading in case you don't need it for template)


You can create your own set of globals within environment.ts like so:

export const globals = {
    isContentLoading: false,
    isDeployNeeded: false
}

and import directly these variables (y)

If '<selector>' is an Angular component, then verify that it is part of this module

Maybe This is for name of html tag component

You use in html something like this <mycomponent></mycomponent>

You must use this <app-mycomponent></app-mycomponent>

Get keys of a Typescript interface as array of strings

This was a tough one! Thank you, everyone, for your assistance.

My need was to get keys of an interface as an array of strings to simplify mocha/chai scripting. Not concerned about using in the app (yet), so didn't need the ts files to be created. Thanks to ford04 for the assistance, his solution above was a huge help and it works perfectly, NO compiler hacks. Here's the modified code:

Option 2: Code generator based on TS compiler API (ts-morph)

Node Module

npm install --save-dev ts-morph

keys.ts

NOTE: this assumes all ts files are located in the root of ./src and there are no subfolders, adjust accordingly

import {
  Project,
  VariableDeclarationKind,
  InterfaceDeclaration,
} from "ts-morph";

// initName is name of the interface file below the root, ./src is considered the root
const Keys = (intName: string): string[] => {
  const project = new Project();
  const sourceFile = project.addSourceFileAtPath(`./src/${intName}.ts`);
  const node = sourceFile.getInterface(intName)!;
  const allKeys = node.getProperties().map((p) => p.getName());

  return allKeys;
};

export default Keys;

usage

import keys from "./keys";

const myKeys = keys("MyInterface") //ts file name without extension

console.log(myKeys)

Cast object to interface in TypeScript

Here's another way to force a type-cast even between incompatible types and interfaces where TS compiler normally complains:

export function forceCast<T>(input: any): T {

  // ... do runtime checks here

  // @ts-ignore <-- forces TS compiler to compile this as-is
  return input;
}

Then you can use it to force cast objects to a certain type:

import { forceCast } from './forceCast';

const randomObject: any = {};
const typedObject = forceCast<IToDoDto>(randomObject);

Note that I left out the part you are supposed to do runtime checks before casting for the sake of reducing complexity. What I do in my project is compiling all my .d.ts interface files into JSON schemas and using ajv to validate in runtime.

Import data.sql MySQL Docker Container

combine https://stackoverflow.com/a/51837876/1078784 and answers in this question, I think the best answer is:

cat {SQL FILE NAME} | docker exec -i {MYSQL CONTAINER NAME} {MYSQL PATH IN CONTAINER} --init-command="SET autocommit=0;"

for example in my system this command should look like:

cat temp.sql | docker exec -i mysql.master /bin/mysql --init-command="SET autocommit=0;"

also you can use pv to moniter progress:

cat temp.sql | pv | docker exec -i mysql.master /bin/mysql --init-command="SET autocommit=0;"

And the most important thing here is "--init-command" which will speed up the import progress 10 times fast.

How can I get (query string) parameters from the URL in Next.js?

If you need to retrieve a URL query from outside a component:

import router from 'next/router'

console.log(router.query)

How to import image (.svg, .png ) in a React Component

There are few steps if we dont use "create-react-app",([email protected]) first we should install file-loader as devDedepencie,next step is to add rule in webpack.config

_x000D_
_x000D_
{
    test: /\.(png|jpe?g|gif)$/i,
    loader: 'file-loader',
}
_x000D_
_x000D_
_x000D_

, then in our src directory we should make file called declarationFiles.d.ts(for example) and register modules inside

_x000D_
_x000D_
declare module '*.jpg';
declare module '*.png';
_x000D_
_x000D_
_x000D_

,then restart dev-server. After these steps we can import and use images like in code bellow

_x000D_
_x000D_
import React from 'react';
import image from './img1.png';
import './helloWorld.scss';

const HelloWorld = () => (
  <>
    <h1 className="main">React TypeScript Starter</h1>
        <img src={image} alt="some example image" />
  </>
);
export default HelloWorld;
_x000D_
_x000D_
_x000D_

Works in typescript and also in javacript,just change extension from .ts to .js

Cheers.

Check if value exists in enum in TypeScript

If you want this to work with string enums, you need to use Object.values(ENUM).includes(ENUM.value) because string enums are not reverse mapped, according to https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-4.html:

Enum Vehicle {
    Car = 'car',
    Bike = 'bike',
    Truck = 'truck'
}

becomes:

{
    Car: 'car',
    Bike: 'bike',
    Truck: 'truck'
}

So you just need to do:

if (Object.values(Vehicle).includes('car')) {
    // Do stuff here
}

If you get an error for: Property 'values' does not exist on type 'ObjectConstructor', then you are not targeting ES2017. You can either use this tsconfig.json config:

"compilerOptions": {
    "lib": ["es2017"]
}

Or you can just do an any cast:

if ((<any>Object).values(Vehicle).includes('car')) {
    // Do stuff here
}

React JS get current date

OPTION 1: if you want to make a common utility function then you can use this

export function getCurrentDate(separator=''){

let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();

return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}

and use it by just importing it as

import {getCurrentDate} from './utils'
console.log(getCurrentDate())

OPTION 2: or define and use in a class directly

getCurrentDate(separator=''){

let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();

return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}

How to loop through a JSON object with typescript (Angular2)

Assuming your json object from your GET request looks like the one you posted above simply do:

let list: string[] = [];

json.Results.forEach(element => {
    list.push(element.Id);
});

Or am I missing something that prevents you from doing it this way?

Docker "ERROR: could not find an available, non-overlapping IPv4 address pool among the defaults to assign to the network"

I fixed this issue by steps :

  1. turn off your network (wireless or wired...).

  2. reboot your system.

  3. before turning on your network on PC, execute command docker-compose up, it's going to create new network.

  4. then you can turn network on and go on ...

Using import fs from 'fs'

For default exports you should use:

import * as fs from 'fs';

Or in case the module has named exports:

import {fs} from 'fs';

Example:

//module1.js

export function function1() {
  console.log('f1')
}

export function function2() {
  console.log('f2')
}

export default function1;

And then:

import defaultExport, { function1, function2 } from './module1'

defaultExport();  // This calls function1
function1();
function2();

Additionally, you should use Webpack or something similar to be able to use ES6 import

I am getting an "Invalid Host header" message when connecting to webpack-dev-server remotely

Rather than editing the webpack config file, the easier way to disable the host check is by adding a .env file to your root folder and putting this:

DANGEROUSLY_DISABLE_HOST_CHECK=true

As the variable name implies, disabling it is insecure and is only advisable to use only in dev environment.

How to import functions from different js file in a Vue+webpack+vue-loader project

I was trying to organize my vue app code, and came across this question , since I have a lot of logic in my component and can not use other sub-coponents , it makes sense to use many functions in a separate js file and call them in the vue file, so here is my attempt

1)The Component (.vue file)

//MyComponent.vue file
<template>
  <div>
  <div>Hello {{name}}</div>
  <button @click="function_A">Read Name</button>
  <button @click="function_B">Write Name</button>
  <button @click="function_C">Reset</button>
  <div>{{message}}</div>
  </div>
 </template>


<script>
import Mylib from "./Mylib"; // <-- import
export default {
  name: "MyComponent",
  data() {
    return {
      name: "Bob",
      message: "click on the buttons"
    };
  },
  methods: {
    function_A() {
      Mylib.myfuncA(this); // <---read data
    },
    function_B() {
      Mylib.myfuncB(this); // <---write data
    },
    function_C() {
      Mylib.myfuncC(this); // <---write data
    }
  }
};
</script>

2)The External js file

//Mylib.js
let exports = {};

// this (vue instance) is passed as that , so we
// can read and write data from and to it as we please :)
exports.myfuncA = (that) => {
  that.message =
  "you hit ''myfuncA'' function that is located in Mylib.js  and data.name = " +
    that.name;
};

exports.myfuncB = (that) => {
  that.message =
  "you hit ''myfuncB'' function that is located in Mylib.js and now I will change the name to Nassim";
  that.name = "Nassim"; // <-- change name to Nassim
};

exports.myfuncC = (that) => {
  that.message =
  "you hit ''myfuncC'' function that is located in Mylib.js and now I will change the name back to Bob";
  that.name = "Bob"; // <-- change name to Bob
};

export default exports;

enter image description here 3)see it in action : https://codesandbox.io/s/distracted-pare-vuw7i?file=/src/components/MyComponent.vue


edit

after getting more experience with Vue , I found out that you could use mixins too to split your code into different files and make it easier to code and maintain see https://vuejs.org/v2/guide/mixins.html

Module AppRegistry is not registered callable module (calling runApplication)

Worked for me for below version and on iOS

 "react": "16.9.0",
 "react-native": "0.61.5",

Step to resolve Close the current running Metro Bundler Try Re-run your Metro Bundler and check if this issue persists

Hope this will help !

Component is part of the declaration of 2 modules

This module is added automatically when you run ionic command. However it's not necessery. So an alternative solution is to remove add-event.module.ts from the project.

Visual Studio Code pylint: Unable to import 'protorpc'

Changing the library path worked for me. Hitting Ctrl + Shift + P and typing python interpreter and choosing one of the available shown. One was familiar (as pointed to a virtualenv that was working fine earlier) and it worked. Take note of the version of python you are working with, either 2.7 or 3.x and choose accordingly

How to put a component inside another component in Angular2?

I think in your Angular-2 version directives are not supported in Component decorator, hence you have to register directive same as other component in @NgModule and then import in component as below and also remove directives: [ChildComponent] from decorator.

import {myDirective} from './myDirective';

How to predict input image using trained model in Keras?

If someone is still struggling to make predictions on images, here is the optimized code to load the saved model and make predictions:

# Modify 'test1.jpg' and 'test2.jpg' to the images you want to predict on

from keras.models import load_model
from keras.preprocessing import image
import numpy as np

# dimensions of our images
img_width, img_height = 320, 240

# load the model we saved
model = load_model('model.h5')
model.compile(loss='binary_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy'])

# predicting images
img = image.load_img('test1.jpg', target_size=(img_width, img_height))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)

images = np.vstack([x])
classes = model.predict_classes(images, batch_size=10)
print classes

# predicting multiple images at once
img = image.load_img('test2.jpg', target_size=(img_width, img_height))
y = image.img_to_array(img)
y = np.expand_dims(y, axis=0)

# pass the list of multiple images np.vstack()
images = np.vstack([x, y])
classes = model.predict_classes(images, batch_size=10)

# print the classes, the images belong to
print classes
print classes[0]
print classes[0][0]

How to overcome the CORS issue in ReactJS

Temporary solve this issue by a chrome plugin called CORS. Btw backend server have to send proper header to front end requests.

Angular 2 Cannot find control with unspecified name attribute on formArrays

Instead of

formGroupName="i"

You must use:

[formGroupName]="i"

Tips:

Since you're looping over the controls, you've already the variable area, so you can replace this:

*ngIf="areasForm.get('areas').controls[i].name.hasError('required')"

by:

*ngIf="area.hasError('required', 'name')"

Stuck at ".android/repositories.cfg could not be loaded."

I used mkdir -p /root/.android && touch /root/.android/repositories.cfg to make it works

Typescript : Property does not exist on type 'object'

You probably have allProviders typed as object[] as well. And property country does not exist on object. If you don't care about typing, you can declare both allProviders and countryProviders as Array<any>:

let countryProviders: Array<any>;
let allProviders: Array<any>;

If you do want static type checking. You can create an interface for the structure and use it:

interface Provider {
    region: string,
    country: string,
    locale: string,
    company: string
}

let countryProviders: Array<Provider>;
let allProviders: Array<Provider>;

Export result set on Dbeaver to CSV

Is there a reason you couldn't select your results and right click and choose Advanced Copy -> Advanced Copy? I'm on a Mac and this is how I always copy results to the clipboard for pasting.

vue.js 2 how to watch store values from vuex

If you simply want to watch a state property and then act within the component accordingly to the changes of that property then see the example below.

In store.js:

export const state = () => ({
 isClosed: false
})
export const mutations = {
 closeWindow(state, payload) {
  state.isClosed = payload
 }
}

In this scenario, I am creating a boolean state property that I am going to change in different places in the application like so:

this.$store.commit('closeWindow', true)

Now, if I need to watch that state property in some other component and then change the local property I would write the following in the mounted hook:

mounted() {
 this.$store.watch(
  state => state.isClosed,
  (value) => {
   if (value) { this.localProperty = 'edit' }
  }
 )
}

Firstly, I am setting a watcher on the state property and then in the callback function I use the value of that property to change the localProperty.

I hope it helps!

Angular2 : Can't bind to 'formGroup' since it isn't a known property of 'form'

I have solved it by importing FormModule in a shared.module and importing the shared.module in all other modules. My case is the FormModule is used in multiple modules.

How to use Redirect in the new react-router-dom of Reactjs

To navigate to another component you can use this.props.history.push('/main');

import React, { Component, Fragment } from 'react'

class Example extends Component {

  redirect() {
    this.props.history.push('/main')
  }

  render() {
    return (
      <Fragment>
        {this.redirect()}
      </Fragment>
    );
   }
 }

 export default Example

Can't bind to 'formControl' since it isn't a known property of 'input' - Angular2 Material Autocomplete issue

Start by adding a regular matInput to your template. Let's assume you're using the formControl directive from ReactiveFormsModule to track the value of the input.

Reactive forms provide a model-driven approach to handling form inputs whose values change over time. This guide shows you how to create and update a simple form control, progress to using multiple controls in a group, validate form values, and implement more advanced forms.

import { FormsModule, ReactiveFormsModule } from "@angular/forms"; //this to use ngModule

...

imports: [
    BrowserModule,
    AppRoutingModule,
    HttpModule,
    FormsModule,
    RouterModule,
    ReactiveFormsModule,
    BrowserAnimationsModule,
    MaterialModule],

How do I format currencies in a Vue component?

Try this:

methods: {
    formatPrice(value) {
        var formatter = new Intl.NumberFormat('en-US', {
            style: 'currency',
            currency: 'PHP',
            minimumFractionDigits: 2
        });
        return formatter.format(value);
    },
}

Then you can just call this like:

{{ formatPrice(item.total) }}

App.settings - the Angular way?

If you are using , there is yet another option:

Angular CLI provides environment files in src/environments (default ones are environment.ts (dev) and environment.prod.ts (production)).

Note that you need to provide the config parameters in all environment.* files, e.g.,

environment.ts:

export const environment = {
  production: false,
  apiEndpoint: 'http://localhost:8000/api/v1'
};

environment.prod.ts:

export const environment = {
  production: true,
  apiEndpoint: '__your_production_server__'
};

and use them in your service (the correct environment file is chosen automatically):

api.service.ts

// ... other imports
import { environment } from '../../environments/environment';

@Injectable()
export class ApiService {     

  public apiRequest(): Observable<MyObject[]> {
    const path = environment.apiEndpoint + `/objects`;
    // ...
  }

// ...
}

Read more on application environments on Github (Angular CLI version 6) or in the official Angular guide (version 7).

How to implement authenticated routes in React Router 4?

I was also looking for some answer. Here all answers are quite good, but none of them give answers how we can use it if user starts application after opening it back. (I meant to say using cookie together).

No need to create even different privateRoute Component. Below is my code

    import React, { Component }  from 'react';
    import { Route, Switch, BrowserRouter, Redirect } from 'react-router-dom';
    import { Provider } from 'react-redux';
    import store from './stores';
    import requireAuth from './components/authentication/authComponent'
    import SearchComponent from './components/search/searchComponent'
    import LoginComponent from './components/login/loginComponent'
    import ExampleContainer from './containers/ExampleContainer'
    class App extends Component {
    state = {
     auth: true
    }


   componentDidMount() {
     if ( ! Cookies.get('auth')) {
       this.setState({auth:false });
     }
    }
    render() {
     return (
      <Provider store={store}>
       <BrowserRouter>
        <Switch>
         <Route exact path="/searchComponent" component={requireAuth(SearchComponent)} />
         <Route exact path="/login" component={LoginComponent} />
         <Route exact path="/" component={requireAuth(ExampleContainer)} />
         {!this.state.auth &&  <Redirect push to="/login"/> }
        </Switch>
       </BrowserRouter>
      </Provider>);
      }
     }
    }
    export default App;

And here is authComponent

import React  from 'react';
import { withRouter } from 'react-router';
import * as Cookie from "js-cookie";
export default function requireAuth(Component) {
class AuthenticatedComponent extends React.Component {
 constructor(props) {
  super(props);
  this.state = {
   auth: Cookie.get('auth')
  }
 }
 componentDidMount() {
  this.checkAuth();
 }
 checkAuth() {
  const location = this.props.location;
  const redirect = location.pathname + location.search;
  if ( ! Cookie.get('auth')) {
   this.props.history.push(`/login?redirect=${redirect}`);
  }
 }
render() {
  return Cookie.get('auth')
   ? <Component { ...this.props } />
   : null;
  }
 }
 return  withRouter(AuthenticatedComponent)
}

Below I have written blog, you can get more depth explanation there as well.

Create Protected routes in ReactJS

Cannot find name 'require' after upgrading to Angular4

The problem (as outlined in typescript getting error TS2304: cannot find name ' require') is that the type definitions for node are not installed.

With a projected genned with @angular/cli 1.x, the specific steps should be:

Step 1:

Install @types/node with either of the following:

- npm install --save @types/node
- yarn add @types/node -D

Step 2: Edit your src/tsconfig.app.json file and add the following in place of the empty "types": [], which should already be there:

...
"types": [ "node" ],
"typeRoots": [ "../node_modules/@types" ]
...

If I've missed anything, jot a comment and I'll edit my answer.

TypeScript enum to object array

There is a simple solution, So when you run Object.keys(Enum) that gonna give you a Array of Values and Keys, in first slice Values and in the second one keys, so why we don't just return the second slice, this code below works for me.

enum Enum {
   ONE,
   TWO,
   THREE,
   FOUR,
   FIVE,
   SIX,
   SEVEN
}
const keys = Object.keys(Enum); 
console.log(keys.slice(keys.length / 2));

Typescript: TS7006: Parameter 'xxx' implicitly has an 'any' type

Minimal error reproduction

export const users = require('../data'); // presumes @types/node are installed
const foundUser = users.find(user => user.id === 42); 
// error: Parameter 'user' implicitly has an 'any' type.ts(7006)

Recommended solution: --resolveJsonModule

The simplest way for your case is to use --resolveJsonModule compiler option:
import users from "./data.json" // `import` instead of `require`
const foundUser = users.find(user => user.id === 42); // user is strongly typed, no `any`!

There are some alternatives for other cases than static JSON import.

Option 1: Explicit user type (simple, no checks)

type User = { id: number; name: string /* and others */ }
const foundUser = users.find((user: User) => user.id === 42)

Option 2: Type guards (middleground)

Type guards are a good middleground between simplicity and strong types:
function isUserArray(maybeUserArr: any): maybeUserArr is Array<User> {
  return Array.isArray(maybeUserArr) && maybeUserArr.every(isUser)
}

function isUser(user: any): user is User {
  return "id" in user && "name" in user
}

if (isUserArray(users)) {
  const foundUser = users.find((user) => user.id === 42)
}
You can even switch to assertion functions (TS 3.7+) to get rid of if and throw an error instead.
function assertIsUserArray(maybeUserArr: any): asserts maybeUserArr is Array<User> {
  if(!isUserArray(maybeUserArr)) throw Error("wrong json type")
}

assertIsUserArray(users)
const foundUser = users.find((user) => user.id === 42) // works

Option 3: Runtime type system library (sophisticated)

A runtime type check library like io-ts or ts-runtime can be integrated for more complex cases.


Not recommended solutions

noImplicitAny: false undermines many useful checks of the type system:
function add(s1, s2) { // s1,s2 implicitely get `any` type
  return s1 * s2 // `any` type allows string multiplication and all sorts of types :(
}
add("foo", 42)

Also better provide an explicit User type for user. This will avoid propagating any to inner layer types. Instead typing and validating is kept in the JSON processing code of the outer API layer.

Attach Authorization header for all axios requests

Try to make new instance like i did below

var common_axios = axios.create({
    baseURL: 'https://sample.com'
});

// Set default headers to common_axios ( as Instance )
common_axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// Check your Header
console.log(common_axios.defaults.headers);

How to Use it

common_axios.get(url).......
common_axios.post(url).......

Typescript ReferenceError: exports is not defined

This is fixed by setting the module compiler option to es6:

{
  "compilerOptions": {     
    "module": "es6",
    "target": "es5",    
  }
}

Field 'browser' doesn't contain a valid alias configuration

Add this to your package.json:

"browser": {
  "[module-name]": false   
},

NVIDIA NVML Driver/library version mismatch

I experienced this problem after a normal kernel update on a CentOS machine. Since all CUDA and nVidia drivers and libraries have been installed via YUM repositories, I managed to solve the issues using the following steps:

sudo yum remove nvidia-driver-*
sudo reboot
sudo yum install nvidia-driver-cuda nvidia-modprobe
sudo modprobe nvidia # or just reboot

It made sure my kernel and my nVidia driver are consistent. I reckon that just rebooting may result in wrong version of kernel module being loaded.

In Angular, What is 'pathmatch: full' and what effect does it have?

While technically correct, the other answers would benefit from an explanation of Angular's URL-to-route matching. I don't think you can fully (pardon the pun) understand what pathMatch: full does if you don't know how the router works in the first place.


Let's first define a few basic things. We'll use this URL as an example: /users/james/articles?from=134#section.

  1. It may be obvious but let's first point out that query parameters (?from=134) and fragments (#section) do not play any role in path matching. Only the base url (/users/james/articles) matters.

  2. Angular splits URLs into segments. The segments of /users/james/articles are, of course, users, james and articles.

  3. The router configuration is a tree structure with a single root node. Each Route object is a node, which may have children nodes, which may in turn have other children or be leaf nodes.

The goal of the router is to find a router configuration branch, starting at the root node, which would match exactly all (!!!) segments of the URL. This is crucial! If Angular does not find a route configuration branch which could match the whole URL - no more and no less - it will not render anything.

E.g. if your target URL is /a/b/c but the router is only able to match either /a/b or /a/b/c/d, then there is no match and the application will not render anything.

Finally, routes with redirectTo behave slightly differently than regular routes, and it seems to me that they would be the only place where anyone would really ever want to use pathMatch: full. But we will get to this later.

Default (prefix) path matching

The reasoning behind the name prefix is that such a route configuration will check if the configured path is a prefix of the remaining URL segments. However, the router is only able to match full segments, which makes this naming slightly confusing.

Anyway, let's say this is our root-level router configuration:

const routes: Routes = [
  {
    path: 'products',
    children: [
      {
        path: ':productID',
        component: ProductComponent,
      },
    ],
  },
  {
    path: ':other',
    children: [
      {
        path: 'tricks',
        component: TricksComponent,
      },
    ],
  },
  {
    path: 'user',
    component: UsersonComponent,
  },
  {
    path: 'users',
    children: [
      {
        path: 'permissions',
        component: UsersPermissionsComponent,
      },
      {
        path: ':userID',
        children: [
          {
            path: 'comments',
            component: UserCommentsComponent,
          },
          {
            path: 'articles',
            component: UserArticlesComponent,
          },
        ],
      },
    ],
  },
];

Note that every single Route object here uses the default matching strategy, which is prefix. This strategy means that the router iterates over the whole configuration tree and tries to match it against the target URL segment by segment until the URL is fully matched. Here's how it would be done for this example:

  1. Iterate over the root array looking for a an exact match for the first URL segment - users.
  2. 'products' !== 'users', so skip that branch. Note that we are using an equality check rather than a .startsWith() or .includes() - only full segment matches count!
  3. :other matches any value, so it's a match. However, the target URL is not yet fully matched (we still need to match james and articles), thus the router looks for children.
  • The only child of :other is tricks, which is !== 'james', hence not a match.
  1. Angular then retraces back to the root array and continues from there.
  2. 'user' !== 'users, skip branch.
  3. 'users' === 'users - the segment matches. However, this is not a full match yet, thus we need to look for children (same as in step 3).
  • 'permissions' !== 'james', skip it.
  • :userID matches anything, thus we have a match for the james segment. However this is still not a full match, thus we need to look for a child which would match articles.
    1. We can see that :userID has a child route articles, which gives us a full match! Thus the application renders UserArticlesComponent.

Full URL (full) matching

Example 1

Imagine now that the users route configuration object looked like this:

{
  path: 'users',
  component: UsersComponent,
  pathMatch: 'full',
  children: [
    {
      path: 'permissions',
      component: UsersPermissionsComponent,
    },
    {
      path: ':userID',
      component: UserComponent,
      children: [
        {
          path: 'comments',
          component: UserCommentsComponent,
        },
        {
          path: 'articles',
          component: UserArticlesComponent,
        },
      ],
    },
  ],
}

Note the usage of pathMatch: full. If this were the case, steps 1-5 would be the same, however step 6 would be different:

  1. 'users' !== 'users/james/articles - the segment does not match because the path configuration users with pathMatch: full does not match the full URL, which is users/james/articles.
  2. Since there is no match, we are skipping this branch.
  3. At this point we reached the end of the router configuration without having found a match. The application renders nothing.

Example 2

What if we had this instead:

{
  path: 'users/:userID',
  component: UsersComponent,
  pathMatch: 'full',
  children: [
    {
      path: 'comments',
      component: UserCommentsComponent,
    },
    {
      path: 'articles',
      component: UserArticlesComponent,
    },
  ],
}

users/:userID with pathMatch: full matches only users/james thus it's a no-match once again, and the application renders nothing.

Example 3

Let's consider this:

{
  path: 'users',
  children: [
    {
      path: 'permissions',
      component: UsersPermissionsComponent,
    },
    {
      path: ':userID',
      component: UserComponent,
      pathMatch: 'full',
      children: [
        {
          path: 'comments',
          component: UserCommentsComponent,
        },
        {
          path: 'articles',
          component: UserArticlesComponent,
        },
      ],
    },
  ],
}

In this case:

  1. 'users' === 'users - the segment matches, but james/articles still remains unmatched. Let's look for children.
  • 'permissions' !== 'james' - skip.
  • :userID' can only match a single segment, which would be james. However, it's a pathMatch: full route, and it must match james/articles (the whole remaining URL). It's not able to do that and thus it's not a match (so we skip this branch)!
  1. Again, we failed to find any match for the URL and the application renders nothing.

As you may have noticed, a pathMatch: full configuration is basically saying this:

Ignore my children and only match me. If I am not able to match all of the remaining URL segments myself, then move on.

Redirects

Any Route which has defined a redirectTo will be matched against the target URL according to the same principles. The only difference here is that the redirect is applied as soon as a segment matches. This means that if a redirecting route is using the default prefix strategy, a partial match is enough to cause a redirect. Here's a good example:

const routes: Routes = [
  {
    path: 'not-found',
    component: NotFoundComponent,
  },
  {
    path: 'users',
    redirectTo: 'not-found',
  },
  {
    path: 'users/:userID',
    children: [
      {
        path: 'comments',
        component: UserCommentsComponent,
      },
      {
        path: 'articles',
        component: UserArticlesComponent,
      },
    ],
  },
];

For our initial URL (/users/james/articles), here's what would happen:

  1. 'not-found' !== 'users' - skip it.
  2. 'users' === 'users' - we have a match.
  3. This match has a redirectTo: 'not-found', which is applied immediately.
  4. The target URL changes to not-found.
  5. The router begins matching again and finds a match for not-found right away. The application renders NotFoundComponent.

Now consider what would happen if the users route also had pathMatch: full:

const routes: Routes = [
  {
    path: 'not-found',
    component: NotFoundComponent,
  },
  {
    path: 'users',
    pathMatch: 'full',
    redirectTo: 'not-found',
  },
  {
    path: 'users/:userID',
    children: [
      {
        path: 'comments',
        component: UserCommentsComponent,
      },
      {
        path: 'articles',
        component: UserArticlesComponent,
      },
    ],
  },
];
  1. 'not-found' !== 'users' - skip it.
  2. users would match the first segment of the URL, but the route configuration requires a full match, thus skip it.
  3. 'users/:userID' matches users/james. articles is still not matched but this route has children.
  • We find a match for articles in the children. The whole URL is now matched and the application renders UserArticlesComponent.

Empty path (path: '')

The empty path is a bit of a special case because it can match any segment without "consuming" it (so it's children would have to match that segment again). Consider this example:

const routes: Routes = [
  {
    path: '',
    children: [
      {
        path: 'users',
        component: BadUsersComponent,
      }
    ]
  },
  {
    path: 'users',
    component: GoodUsersComponent,
  },
];

Let's say we are trying to access /users:

  • path: '' will always match, thus the route matches. However, the whole URL has not been matched - we still need to match users!
  • We can see that there is a child users, which matches the remaining (and only!) segment and we have a full match. The application renders BadUsersComponent.

Now back to the original question

The OP used this router configuration:

const routes: Routes = [
  {
    path: 'welcome',
    component: WelcomeComponent,
  },
  {
    path: '',
    redirectTo: 'welcome',
    pathMatch: 'full',
  },
  {
    path: '**',
    redirectTo: 'welcome',
    pathMatch: 'full',
  },
];

If we are navigating to the root URL (/), here's how the router would resolve that:

  1. welcome does not match an empty segment, so skip it.
  2. path: '' matches the empty segment. It has a pathMatch: 'full', which is also satisfied as we have matched the whole URL (it had a single empty segment).
  3. A redirect to welcome happens and the application renders WelcomeComponent.

What if there was no pathMatch: 'full'?

Actually, one would expect the whole thing to behave exactly the same. However, Angular explicitly prevents such a configuration ({ path: '', redirectTo: 'welcome' }) because if you put this Route above welcome, it would theoretically create an endless loop of redirects. So Angular just throws an error, which is why the application would not work at all! (https://angular.io/api/router/Route#pathMatch)

Actually, this does not make too much sense to me because Angular also has implemented a protection against such endless redirects - it only runs a single redirect per routing level! This would stop all further redirects (as you'll see in the example below).

What about path: '**'?

path: '**' will match absolutely anything (af/frewf/321532152/fsa is a match) with or without a pathMatch: 'full'.

Also, since it matches everything, the root path is also included, which makes { path: '', redirectTo: 'welcome' } completely redundant in this setup.

Funnily enough, it is perfectly fine to have this configuration:

const routes: Routes = [
  {
    path: '**',
    redirectTo: 'welcome'
  },
  {
    path: 'welcome',
    component: WelcomeComponent,
  },
];

If we navigate to /welcome, path: '**' will be a match and a redirect to welcome will happen. Theoretically this should kick off an endless loop of redirects but Angular stops that immediately (because of the protection I mentioned earlier) and the whole thing works just fine.

react router v^4.0.0 Uncaught TypeError: Cannot read property 'location' of undefined

You're doing a few things wrong.

  1. First, browserHistory isn't a thing in V4, so you can remove that.

  2. Second, you're importing everything from react-router, it should be react-router-dom.

  3. Third, react-router-dom doesn't export a Router, instead, it exports a BrowserRouter so you need to import { BrowserRouter as Router } from 'react-router-dom.

Looks like you just took your V3 app and expected it to work with v4, which isn't a great idea.

No provider for Router?

I had the error of

No provider for Router

It happens when you try to navigate in any service.ts

this.router.navigate(['/home']); like codes in services cause that error.

You should handle navigating in your components. for example: at login.component

login().subscribe(
        (res) => this.router.navigate(['/home']),
        (error: any) => this.handleError(error));

Annoying errors happens when we are newbie :)

React.createElement: type is invalid -- expected a string

In my case, the order in which you create the component and render, mattered. I was rendering the component before creating it. The best way is to create the child component and then the parent components and then render the parent component. Changing the order fixed the issue for me.

Why plt.imshow() doesn't display the image?

If you want to print the picture using imshow() you also execute plt.show()

Enabling CORS in Cloud Functions for Firebase

If You are not using Express or simply want to use CORS. The following code will help resolve

const cors = require('cors')({ origin: true, });   
exports.yourfunction = functions.https.onRequest((request, response) => {  
   return cors(request, response, () => {  
        // *Your code*
    });
});

How to set environment variables in PyCharm?

I was able to figure out this using a PyCharm plugin called EnvFile. This plugin, basically allows setting environment variables to run configurations from one or multiple files.

The installation is pretty simple:

Preferences > Plugins > Browse repositories... > Search for "Env File" > Install Plugin.

Then, I created a file, in my project root, called environment.env which contains:

DATABASE_URL=postgres://127.0.0.1:5432/my_db_name
DEBUG=1

Then I went to Run->Edit Configurations, and I followed the steps in the next image:

Set Environment Variables

In 3, I chose the file environment.env, and then I could just click the play button in PyCharm, and everything worked like a charm.

How to push to History in React Router v4?

Simplest way in React Router 4 is to use

this.props.history.push('/new/url');

But to use this method, your existing component should have access to history object. We can get access by

  1. If your component is linked to Route directly, then your component already has access to history object.

    eg:

    <Route path="/profile" component={ViewProfile}/>
    

    Here ViewProfile has access to history.

  2. If not connected to Route directly.

    eg:

    <Route path="/users" render={() => <ViewUsers/>}
    

    Then we have to use withRouter, a heigher order fuction to warp the existing component.

    Inside ViewUsers component

    • import { withRouter } from 'react-router-dom';

    • export default withRouter(ViewUsers);

    That's it now, your ViewUsers component has access to history object.

UPDATE

2- in this scenario, pass all route props to your component, and then we can access this.props.history from the component even without a HOC

eg:

<Route path="/users" render={props => <ViewUsers {...props} />}

Node.js ES6 classes with require

Yes, your example would work fine.

As for exposing your classes, you can export a class just like anything else:

class Animal {...}
module.exports = Animal;

Or the shorter:

module.exports = class Animal {

};

Once imported into another module, then you can treat it as if it were defined in that file:

var Animal = require('./Animal');

class Cat extends Animal {
    ...
}

'React' must be in scope when using JSX react/react-in-jsx-scope?

import React, { Component } from 'react';

This is a spelling error, you need to type React instead of react.

Error: Could not find gradle wrapper within Android SDK. Might need to update your Android SDK - Android

For anyone who is still having this issue, this worked for me:

    cordova platform update android@latest

then build and it will automatically download the newest gradle version and should work

Model summary in pytorch

AFAK there is no model.summary() like equivalent in pytorch

Meanwhile you can refer script by szagoruyko, which gives a nice visualizaton like in resnet18-example

Cheers

How does the "view" method work in PyTorch?

Let's do some examples, from simpler to more difficult.

  1. The view method returns a tensor with the same data as the self tensor (which means that the returned tensor has the same number of elements), but with a different shape. For example:

    a = torch.arange(1, 17)  # a's shape is (16,)
    
    a.view(4, 4) # output below
      1   2   3   4
      5   6   7   8
      9  10  11  12
     13  14  15  16
    [torch.FloatTensor of size 4x4]
    
    a.view(2, 2, 4) # output below
    (0 ,.,.) = 
    1   2   3   4
    5   6   7   8
    
    (1 ,.,.) = 
     9  10  11  12
    13  14  15  16
    [torch.FloatTensor of size 2x2x4]
    
  2. Assuming that -1 is not one of the parameters, when you multiply them together, the result must be equal to the number of elements in the tensor. If you do: a.view(3, 3), it will raise a RuntimeError because shape (3 x 3) is invalid for input with 16 elements. In other words: 3 x 3 does not equal 16 but 9.

  3. You can use -1 as one of the parameters that you pass to the function, but only once. All that happens is that the method will do the math for you on how to fill that dimension. For example a.view(2, -1, 4) is equivalent to a.view(2, 2, 4). [16 / (2 x 4) = 2]

  4. Notice that the returned tensor shares the same data. If you make a change in the "view" you are changing the original tensor's data:

    b = a.view(4, 4)
    b[0, 2] = 2
    a[2] == 3.0
    False
    
  5. Now, for a more complex use case. The documentation says that each new view dimension must either be a subspace of an original dimension, or only span d, d + 1, ..., d + k that satisfy the following contiguity-like condition that for all i = 0, ..., k - 1, stride[i] = stride[i + 1] x size[i + 1]. Otherwise, contiguous() needs to be called before the tensor can be viewed. For example:

    a = torch.rand(5, 4, 3, 2) # size (5, 4, 3, 2)
    a_t = a.permute(0, 2, 3, 1) # size (5, 3, 2, 4)
    
    # The commented line below will raise a RuntimeError, because one dimension
    # spans across two contiguous subspaces
    # a_t.view(-1, 4)
    
    # instead do:
    a_t.contiguous().view(-1, 4)
    
    # To see why the first one does not work and the second does,
    # compare a.stride() and a_t.stride()
    a.stride() # (24, 6, 2, 1)
    a_t.stride() # (24, 2, 1, 6)
    

    Notice that for a_t, stride[0] != stride[1] x size[1] since 24 != 2 x 3

take(1) vs first()

Tip: Only use first() if:

  • You consider zero items emitted to be an error condition (eg. completing before emitting) AND if there’s a greater than 0% chance of error you handling it gracefully
  • OR You know 100% that the source observable will emit 1+ items (so can never throw).

If there are zero emissions and you are not explicitly handling it (with catchError) then that error will get propagated up, possibly cause an unexpected problem somewhere else and can be quite tricky to track down - especially if it's coming from an end user.

You're safer off using take(1) for the most part provided that:

  • You're OK with take(1) not emitting anything if the source completes without an emission.
  • You don't need to use an inline predicate (eg. first(x => x > 10) )

Note: You can use a predicate with take(1) like this: .pipe( filter(x => x > 10), take(1) ). There is no error with this if nothing is ever greater than 10.

What about single()

If you want to be even stricter, and disallow two emissions you can use single() which errors if there are zero or 2+ emissions. Again you'd need to handle errors in that case.

Tip: Single can occasionally be useful if you want to ensure your observable chain isn't doing extra work like calling an http service twice and emitting two observables. Adding single to the end of the pipe will let you know if you made such a mistake. I'm using it in a 'task runner' where you pass in a task observable that should only emit one value, so I pass the response through single(), catchError() to guarantee good behavior.


Why not always use first() instead of take(1) ?

aka. How can first potentially cause more errors?

If you have an observable that takes something from a service and then pipes it through first() you should be fine most of the time. But if someone comes along to disable the service for whatever reason - and changes it to emit of(null) or NEVER then any downstream first() operators would start throwing errors.

Now I realize that might be exactly what you want - hence why this is just a tip. The operator first appealed to me because it sounded slightly less 'clumsy' than take(1) but you need to be careful about handling errors if there's ever a chance of the source not emitting. Will entirely depend on what you're doing though.


If you have a default value (constant):

Consider also .pipe(defaultIfEmpty(42), first()) if you have a default value that should be used if nothing is emitted. This would of course not raise an error because first would always receive a value.

Note that defaultIfEmpty is only triggered if the stream is empty, not if the value of what is emitted is null.

How to specify Memory & CPU limit in docker compose version 3

I know the topic is a bit old and seems stale, but anyway I was able to use these options:

    deploy:
      resources:
        limits:
          cpus: '0.001'
          memory: 50M

when using 3.7 version of docker-compose

What helped in my case, was using this command:

docker-compose --compatibility up

--compatibility flag stands for (taken from the documentation):

If set, Compose will attempt to convert deploy keys in v3 files to their non-Swarm equivalent

Think it's great, that I don't have to revert my docker-compose file back to v2.

TypeScript hashmap/dictionary interface

The most simple and the correct way is to use Record type Record<string, string>

const myVar : Record<string, string> = {
   key1: 'val1',
   key2: 'val2',
}

ReactJs: What should the PropTypes be for this.props.children?

If you want to match exactly a component type, check this

MenuPrimary.propTypes = {
  children: PropTypes.oneOfType([
    PropTypes.arrayOf(MenuPrimaryItem),
    PropTypes.objectOf(MenuPrimaryItem)
  ])
}

If you want to match exactly some component types, check this

const HeaderTypes = [
  PropTypes.objectOf(MenuPrimary),
  PropTypes.objectOf(UserInfo)
]

Header.propTypes = {
  children: PropTypes.oneOfType([
    PropTypes.arrayOf(PropTypes.oneOfType([...HeaderTypes])),
    ...HeaderTypes
  ])
}

How to Pass data from child to parent component Angular

Register the EventEmitter in your child component as the @Output:

@Output() onDatePicked = new EventEmitter<any>();

Emit value on click:

public pickDate(date: any): void {
    this.onDatePicked.emit(date);
}

Listen for the events in your parent component's template:

<div>
    <calendar (onDatePicked)="doSomething($event)"></calendar>
</div>

and in the parent component:

public doSomething(date: any):void {
    console.log('Picked date: ', date);
}

It's also well explained in the official docs: Component interaction.

Typescript: React event types

The SyntheticEvent interface is generic:

interface SyntheticEvent<T> {
    ...
    currentTarget: EventTarget & T;
    ...
}

(Technically the currentTarget property is on the parent BaseSyntheticEvent type.)

And the currentTarget is an intersection of the generic constraint and EventTarget.
Also, since your events are caused by an input element you should use the ChangeEvent (in definition file, the react docs).

Should be:

update = (e: React.ChangeEvent<HTMLInputElement>): void => {
    this.props.login[e.currentTarget.name] = e.currentTarget.value
}

(Note: This answer originally suggested using React.FormEvent. The discussion in the comments is related to this suggestion, but React.ChangeEvent should be used as shown above.)

Why binary_crossentropy and categorical_crossentropy give different performances for the same problem?

As it is a multi-class problem, you have to use the categorical_crossentropy, the binary cross entropy will produce bogus results, most likely will only evaluate the first two classes only.

50% for a multi-class problem can be quite good, depending on the number of classes. If you have n classes, then 100/n is the minimum performance you can get by outputting a random class.

Property 'value' does not exist on type 'EventTarget'

Angular 10+

Open tsconfig.json and disable strictDomEventTypes.

  "angularCompilerOptions": {
    ....
    ........
    "strictDomEventTypes": false
  }

Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema

I had the same issue and I resolved this by making some changes in my web.config.js file. FYI I am using the latest version of webpack and webpack-cli. This trick just saved my day. I have attached the example of mine web.config.js file before and after version.

Before:

module.exports = {
    resolve: {
        extensions: ['.js', '.jsx']
    },
    entry: './index.js',
    output: {
         filename: 'bundle.js'
    },
    module: {
        loaders : [
           { test: /\.js?/, loader: 'bable-loader', exclude: /node_modules/ }
        ]
    }
}

After: I Just replaced loaders to rules in module object as you can see in my code snippet.

module.exports = {
    resolve: {
        extensions: ['.js', '.jsx']
    },
    entry: './index.js',
    output: {
        filename: 'bundle.js'
    },
    module: {
        rules : [
            { test: /\.js?/, loader: 'bable-loader', exclude: /node_modules/ }
        ]
    }
}

Hopefully, This will help someone to get rid out of this issue.

Getting Error "Form submission canceled because the form is not connected"

You can also solve it, by applying a single patch in the jquery-x.x.x.js just add after " try { rp; } catch (m) {}" line 1833 this code:

if (r instanceof HTMLFormElement &&! r.parentNode) { r.style.display = "none"; document.body.append (r); r [p] (); }

This validates when a form is not part of the body and adds it.

Uncaught TypeError: (intermediate value)(...) is not a function

The error is a result of the missing semicolon on the third line:

window.Glog = function(msg) {
  console.log(msg);
}; // <--- Add this semicolon

(function(win) {
  // ...
})(window);

The ECMAScript specification has specific rules for automatic semicolon insertion, however in this case a semicolon isn't automatically inserted because the parenthesised expression that begins on the next line can be interpreted as an argument list for a function call.

This means that without that semicolon, the anonymous window.Glog function was being invoked with a function as the msg parameter, followed by (window) which was subsequently attempting to invoke whatever was returned.

This is how the code was being interpreted:

window.Glog = function(msg) {
  console.log(msg);
}(function(win) {
  // ...
})(window);

Can't bind to 'routerLink' since it isn't a known property

In my case I just need to import my newly created component to RouterModule

{path: 'newPath', component: newComponent}

Then in your app.module import the router and configure the routes:

import { RouterModule } from '@angular/router';

imports: [
        RouterModule.forRoot([
            {path: '', component: DashboardComponent},
            {path: 'dashboard', component: DashboardComponent},
            {path: 'newPath', component: newComponent}
        ])
    ],

Hope this helps to some one !!!

Invalid shorthand property initializer

Use : instead of =

see the example below that gives an error

app.post('/mews', (req, res) => {
if (isValidMew(req.body)) {
    // insert into db
    const mew = {
        name = filter.clean(req.body.name.toString()),
        content = filter.clean(req.body.content.toString()),
        created: new Date()
    };

That gives Syntex Error: invalid shorthand proprty initializer.

Then i replace = with : that's solve this error.

app.post('/mews', (req, res) => {
if (isValidMew(req.body)) {
    // insert into db
    const mew = {
        name: filter.clean(req.body.name.toString()),
        content: filter.clean(req.body.content.toString()),
        created: new Date()
    };

How to create multiple page app using react

(Make sure to install react-router using npm!)

To use react-router, you do the following:

  1. Create a file with routes defined using Route, IndexRoute components

  2. Inject the Router (with 'r'!) component as the top-level component for your app, passing the routes defined in the routes file and a type of history (hashHistory, browserHistory)

  3. Add {this.props.children} to make sure new pages will be rendered there
  4. Use the Link component to change pages

Step 1 routes.js

import React from 'react';
import { Route, IndexRoute } from 'react-router';

/**
 * Import all page components here
 */
import App from './components/App';
import MainPage from './components/MainPage';
import SomePage from './components/SomePage';
import SomeOtherPage from './components/SomeOtherPage';

/**
 * All routes go here.
 * Don't forget to import the components above after adding new route.
 */
export default (
  <Route path="/" component={App}>
    <IndexRoute component={MainPage} />
    <Route path="/some/where" component={SomePage} />
    <Route path="/some/otherpage" component={SomeOtherPage} />
  </Route>
);

Step 2 entry point (where you do your DOM injection)

// You can choose your kind of history here (e.g. browserHistory)
import { Router, hashHistory as history } from 'react-router';
// Your routes.js file
import routes from './routes';

ReactDOM.render(
  <Router routes={routes} history={history} />,
  document.getElementById('your-app')
);

Step 3 The App component (props.children)

In the render for your App component, add {this.props.children}:

render() {
  return (
    <div>
      <header>
        This is my website!
      </header>

      <main>
        {this.props.children}
      </main>

      <footer>
        Your copyright message
      </footer>
    </div>
  );
}

Step 4 Use Link for navigation

Anywhere in your component render function's return JSX value, use the Link component:

import { Link } from 'react-router';
(...)
<Link to="/some/where">Click me</Link>

Understanding "VOLUME" instruction in DockerFile

In short: No, your VOLUME instruction is not correct.

Dockerfile's VOLUME specify one or more volumes given container-side paths. But it does not allow the image author to specify a host path. On the host-side, the volumes are created with a very long ID-like name inside the Docker root. On my machine this is /var/lib/docker/volumes.

Note: Because the autogenerated name is extremely long and makes no sense from a human's perspective, these volumes are often referred to as "unnamed" or "anonymous".

Your example that uses a '.' character will not even run on my machine, no matter if I make the dot the first or second argument. I get this error message:

docker: Error response from daemon: oci runtime error: container_linux.go:265: starting container process caused "process_linux.go:368: container init caused "open /dev/ptmx: no such file or directory"".

I know that what has been said to this point is probably not very valuable to someone trying to understand VOLUME and -v and it certainly does not provide a solution for what you try to accomplish. So, hopefully, the following examples will shed some more light on these issues.

Minitutorial: Specifying volumes

Given this Dockerfile:

FROM openjdk:8u131-jdk-alpine
VOLUME vol1 vol2

(For the outcome of this minitutorial, it makes no difference if we specify vol1 vol2 or /vol1 /vol2 — this is because the default working directory within a Dockerfile is /)

Build it:

docker build -t my-openjdk

Run:

docker run --rm -it my-openjdk

Inside the container, run ls in the command line and you'll notice two directories exist; /vol1 and /vol2.

Running the container also creates two directories, or "volumes", on the host-side.

While having the container running, execute docker volume ls on the host machine and you'll see something like this (I have replaced the middle part of the name with three dots for brevity):

DRIVER    VOLUME NAME
local     c984...e4fc
local     f670...49f0

Back in the container, execute touch /vol1/weird-ass-file (creates a blank file at said location).

This file is now available on the host machine, in one of the unnamed volumes lol. It took me two tries because I first tried the first listed volume, but eventually I did find my file in the second listed volume, using this command on the host machine:

sudo ls /var/lib/docker/volumes/f670...49f0/_data

Similarly, you can try to delete this file on the host and it will be deleted in the container as well.

Note: The _data folder is also referred to as a "mount point".

Exit out from the container and list the volumes on the host. They are gone. We used the --rm flag when running the container and this option effectively wipes out not just the container on exit, but also the volumes.

Run a new container, but specify a volume using -v:

docker run --rm -it -v /vol3 my-openjdk

This adds a third volume and the whole system ends up having three unnamed volumes. The command would have crashed had we specified only -v vol3. The argument must be an absolute path inside the container. On the host-side, the new third volume is anonymous and resides together with the other two volumes in /var/lib/docker/volumes/.

It was stated earlier that the Dockerfile can not map to a host path which sort of pose a problem for us when trying to bring files in from the host to the container during runtime. A different -v syntax solves this problem.

Imagine I have a subfolder in my project directory ./src that I wish to sync to /src inside the container. This command does the trick:

docker run -it -v $(pwd)/src:/src my-openjdk

Both sides of the : character expects an absolute path. Left side being an absolute path on the host machine, right side being an absolute path inside the container. pwd is a command that "print current/working directory". Putting the command in $() takes the command within parenthesis, runs it in a subshell and yields back the absolute path to our project directory.

Putting it all together, assume we have ./src/Hello.java in our project folder on the host machine with the following contents:

public class Hello {
    public static void main(String... ignored) {
        System.out.println("Hello, World!");
    }
}

We build this Dockerfile:

FROM openjdk:8u131-jdk-alpine
WORKDIR /src
ENTRYPOINT javac Hello.java && java Hello

We run this command:

docker run -v $(pwd)/src:/src my-openjdk

This prints "Hello, World!".

The best part is that we're completely free to modify the .java file with a new message for another output on a second run - without having to rebuild the image =)

Final remarks

I am quite new to Docker, and the aforementioned "tutorial" reflects information I gathered from a 3-day command line hackathon. I am almost ashamed I haven't been able to provide links to clear English-like documentation backing up my statements, but I honestly think this is due to a lack of documentation and not personal effort. I do know the examples work as advertised using my current setup which is "Windows 10 -> Vagrant 2.0.0 -> Docker 17.09.0-ce".

The tutorial does not solve the problem "how do we specify the container's path in the Dockerfile and let the run command only specify the host path". There might be a way, I just haven't found it.

Finally, I have a gut feeling that specifying VOLUME in the Dockerfile is not just uncommon, but it's probably a best practice to never use VOLUME. For two reasons. The first reason we have already identified: We can not specify the host path - which is a good thing because Dockerfiles should be very agnostic to the specifics of a host machine. But the second reason is people might forget to use the --rm option when running the container. One might remember to remove the container but forget to remove the volume. Plus, even with the best of human memory, it might be a daunting task to figure out which of all anonymous volumes are safe to remove.

ARG or ENV, which one to use in this case?

So if want to set the value of an environment variable to something different for every build then we can pass these values during build time and we don't need to change our docker file every time.

While ENV, once set cannot be overwritten through command line values. So, if we want to have our environment variable to have different values for different builds then we could use ARG and set default values in our docker file. And when we want to overwrite these values then we can do so using --build-args at every build without changing our docker file.

For more details, you can refer this.

ES6 modules in the browser: Uncaught SyntaxError: Unexpected token import

Unfortunately, modules aren't supported by many browsers right now.

This feature is only just beginning to be implemented in browsers natively at this time. It is implemented in many transpilers, such as TypeScript and Babel, and bundlers such as Rollup and Webpack.

Found on MDN

Keras, How to get the output of each layer?

Wanted to add this as a comment (but don't have high enough rep.) to @indraforyou's answer to correct for the issue mentioned in @mathtick's comment. To avoid the InvalidArgumentError: input_X:Y is both fed and fetched. exception, simply replace the line outputs = [layer.output for layer in model.layers] with outputs = [layer.output for layer in model.layers][1:], i.e.

adapting indraforyou's minimal working example:

from keras import backend as K 
inp = model.input                                           # input placeholder
outputs = [layer.output for layer in model.layers][1:]        # all layer outputs except first (input) layer
functor = K.function([inp, K.learning_phase()], outputs )   # evaluation function

# Testing
test = np.random.random(input_shape)[np.newaxis,...]
layer_outs = functor([test, 1.])
print layer_outs

p.s. my attempts trying things such as outputs = [layer.output for layer in model.layers[1:]] did not work.

Why is "npm install" really slow?

One of the simple solution to speed up your npm install is to spin up a high powered machine on AWS and use that to compile your project and ship the code back to you.

I was experimenting with it and I found that there was a very high decrease in the time to run npm install. I found a tool to execute the above command easily https://stormyapp.com

Angular2 material dialog has issues - Did you add it to @NgModule.entryComponents?

While integrating material dialog is possible, I found that the complexity for such a trivial feature is pretty high. The code gets more complex if you are trying to achieve a non-trivial features.

For that reason, I ended up using PrimeNG Dialog, which I found pretty straightforward to use:

m-dialog.component.html:

<p-dialog header="Title">
  Content
</p-dialog>

m-dialog.component.ts:

@Component({
  selector: 'm-dialog',
  templateUrl: 'm-dialog.component.html',
  styleUrls: ['./m-dialog.component.css']
})
export class MDialogComponent {
  // dialog logic here
}

m-dialog.module.ts:

import { NgModule } from "@angular/core";
import { CommonModule } from "@angular/common";
import { DialogModule } from "primeng/primeng";
import { FormsModule } from "@angular/forms";

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    DialogModule
  ], 
  exports: [
    MDialogComponent,
  ], 
  declarations: [
    MDialogComponent
  ]
})
export class MDialogModule {}

Simply add your dialog into your component's html:

<m-dialog [isVisible]="true"> </m-dialog>

PrimeNG PrimeFaces documentation is easy to follow and very precise.

Clearing input in vuejs form

I use this

this.$refs['refFormName'].resetFields();

this work fine for me.

What's the difference between ClusterIP, NodePort and LoadBalancer service types in Kubernetes?

A ClusterIP exposes the following:

  • spec.clusterIp:spec.ports[*].port

You can only access this service while inside the cluster. It is accessible from its spec.clusterIp port. If a spec.ports[*].targetPort is set it will route from the port to the targetPort. The CLUSTER-IP you get when calling kubectl get services is the IP assigned to this service within the cluster internally.

A NodePort exposes the following:

  • <NodeIP>:spec.ports[*].nodePort
  • spec.clusterIp:spec.ports[*].port

If you access this service on a nodePort from the node's external IP, it will route the request to spec.clusterIp:spec.ports[*].port, which will in turn route it to your spec.ports[*].targetPort, if set. This service can also be accessed in the same way as ClusterIP.

Your NodeIPs are the external IP addresses of the nodes. You cannot access your service from spec.clusterIp:spec.ports[*].nodePort.

A LoadBalancer exposes the following:

  • spec.loadBalancerIp:spec.ports[*].port
  • <NodeIP>:spec.ports[*].nodePort
  • spec.clusterIp:spec.ports[*].port

You can access this service from your load balancer's IP address, which routes your request to a nodePort, which in turn routes the request to the clusterIP port. You can access this service as you would a NodePort or a ClusterIP service as well.

How to disable button in React.js

You shouldn't be setting the value of the input through refs.

Take a look at the documentation for controlled form components here - https://facebook.github.io/react/docs/forms.html#controlled-components

In a nutshell

<input value={this.state.value} onChange={(e) => this.setState({value: e.target.value})} />

Then you will be able to control the disabled state by using disabled={!this.state.value}

Clearing an input text field in Angular2

1. First Method

you have to assign null or empty string here

this.searchValue = null;
//or
this.searchValue = ' ';

Working Plunker

because no event is being fired from angular change detection. so you have to assign some value either null or string with space

2. Second Method

  • use of [(ngModel)] it should work with ngModel.

why ?

because as you did binding with value attribute which is only property binding not event binding. so angular doesn't run change detection because no event relevant to Angular is fired. If you bind to an event then Angular runs change detection and the binding works and value should be changes.

see working example of same with ngModel

Working Example with ngModel

Vue v-on:click does not work on component

From the documentation:

Due to limitations in JavaScript, Vue cannot detect the following changes to an array:

  1. When you directly set an item with the index, e.g. vm.items[indexOfItem] = newValue
  2. When you modify the length of the array, e.g. vm.items.length = newLength

In my case i stumbled on this problem when migrating from Angular to VUE. Fix was quite easy, but really difficult to find:

setValue(index) {
    Vue.set(this.arr, index, !this.arr[index]);
    this.$forceUpdate(); // Needed to force view rerendering
}

Nested routes with react router v4 / v5

A complete answer for React Router v6 or version 6 just in case needed.

import Dashboard from "./dashboard/Dashboard";
import DashboardDefaultContent from "./dashboard/dashboard-default-content";
import { Route, Routes } from "react-router";
import { useRoutes } from "react-router-dom";

/*Routes is used to be Switch*/
const Router = () => {

  return (
    <Routes>
      <Route path="/" element={<LandingPage />} />
      <Route path="games" element={<Games />} />
      <Route path="game-details/:id" element={<GameDetails />} />
      <Route path="dashboard" element={<Dashboard />}>
        <Route path="/" element={<DashboardDefaultContent />} />
        <Route path="inbox" element={<Inbox />} />
        <Route path="settings-and-privacy" element={<SettingsAndPrivacy />} />
        <Route path="*" element={<NotFound />} />
      </Route>
      <Route path="*" element={<NotFound />} />
    </Routes>
  );
};
export default Router;
import DashboardSidebarNavigation from "./dashboard-sidebar-navigation";
import { Grid } from "@material-ui/core";
import { Outlet } from "react-router";

const Dashboard = () => {
  return (
    <Grid
      container
      direction="row"
      justify="flex-start"
      alignItems="flex-start"
    >
      <DashboardSidebarNavigation />
      <Outlet />
    </Grid>
  );
};

export default Dashboard;

Github repo is here. https://github.com/webmasterdevlin/react-router-6-demo

Passing data into "router-outlet" child components

Yes, you can set inputs of components displayed via router outlets. Sadly, you have to do it programmatically, as mentioned in other answers. There's a big caveat to that when observables are involved (described below).

Here's how:

(1) Hook up to the router-outlet's activate event in the parent template:

<router-outlet (activate)="onOutletLoaded($event)"></router-outlet>

(2) Switch to the parent's typescript file and set the child component's inputs programmatically each time they are activated:

onOutletLoaded(component) {
    component.node = 'someValue';
} 

Done.

However, the above version of onOutletLoaded is simplified for clarity. It only works if you can guarantee all child components have the exact same inputs you are assigning. If you have components with different inputs, use type guards:

onChildLoaded(component: MyComponent1 | MyComponent2) {
  if (component instanceof MyComponent1) {
    component.someInput = 123;
  } else if (component instanceof MyComponent2) {
    component.anotherInput = 456;
  }
}

Why may this method be preferred over the service method?

Neither this method nor the service method are "the right way" to communicate with child components (both methods step away from pure template binding), so you just have to decide which way feels more appropriate for the project.

This method, however, avoids the tight coupling associated with the "create a service for communication" approach (i.e., the parent needs the service, and the children all need the service, making the children unusable elsewhere). Decoupling is usually preferred.

In many cases this method also feels closer to the "angular way" because you can continue passing data to your child components through @Inputs (thats the decoupling part - this enables re-use elsewhere). It's also a good fit for already existing or third-party components that you don't want to or can't tightly couple with your service.

On the other hand, it may feel less like the angular way when...

Caveat

The caveat with this method is that since you are passing data in the typescript file, you no longer have the option of using the pipe-async pattern used in templates (e.g. {{ myObservable$ | async }}) to automagically use and pass on your observable data to child components.

Instead, you'll need to set up something to get the current observable values whenever the onChildLoaded function is called. This will likely also require some teardown in the parent component's onDestroy function. This is nothing too unusual, there are often cases where this needs to be done, such as when using an observable that doesn't even get to the template.

css display table cell requires percentage width

You just need to add 'table-layout: fixed;'

.table {
   display: table;
   height: 100px;
   width: 100%;
   table-layout: fixed;
}

http://www.w3schools.com/cssref/pr_tab_table-layout.asp

How to fix java.lang.UnsupportedClassVersionError: Unsupported major.minor version

You have used a higher version of the JDK to compile and trying to run from a lower version of JDK/JRE.

To check this, see the version information:

javac -version

java -version

They will be different and javac will have a higher version number.

To get around this, run using java from the JDK version or if you have a newer JRE/JDK that will work as well.

which javac will tell you the location, for example, /usr/bin/javac. Just run directly using /usr/bin/java <program>.

OR you can set the environment variable as a permanent solution.

Locking a file in Python

I found a simple and worked(!) implementation from grizzled-python.

Simple use os.open(..., O_EXCL) + os.close() didn't work on windows.

Unix shell script find out which directory the script file resides?

Assuming you're using bash

#!/bin/bash

current_dir=$(pwd)
script_dir=$(dirname "$0")

echo $current_dir
echo $script_dir

This script should print the directory that you're in, and then the directory the script is in. For example, when calling it from / with the script in /home/mez/, it outputs

/
/home/mez

Remember, when assigning variables from the output of a command, wrap the command in $( and ) - or you won't get the desired output.

Recursive mkdir() system call on Unix

Apparently not, my two suggestions are:

char dirpath[80] = "/path/to/some/directory";
sprintf(mkcmd, "mkdir -p %s", dirpath);
system(mkcmd);

Or if you don't want to use system() try looking at the coreutils mkdir source code and see how they implemented the -p option.

How to cast int to enum in C++?

int i = 1;
Test val = static_cast<Test>(i);

Select first occurring element after another element

#many .more.selectors h4 + p { ... }

This is called the adjacent sibling selector.

Escape text for HTML

.NET 4.0 and above:

using System.Web.Security.AntiXss;
//...
var encoded = AntiXssEncoder.HtmlEncode("input", useNamedEntities: true);

Where does Android app package gets installed on phone

An application when installed on a device or on an emulator will install at:

/data/data/APP_PACKAGE_NAME

The APK itself is placed in the /data/app/ folder.

These paths, however, are in the System Partition and to access them, you will need to have root. This is for a device. On the emulator, you can see it in your logcat (DDMS) in the File Explorer tab

By the way, it only shows the package name that is defined in your Manifest.XML under the package="APP_PACKAGE_NAME" attribute. Any other packages you may have created in your project in Eclipse do not show up here.

What is the difference between bindParam and bindValue?

From the manual entry for PDOStatement::bindParam:

[With bindParam] Unlike PDOStatement::bindValue(), the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called.

So, for example:

$sex = 'male';
$s = $dbh->prepare('SELECT name FROM students WHERE sex = :sex');
$s->bindParam(':sex', $sex); // use bindParam to bind the variable
$sex = 'female';
$s->execute(); // executed with WHERE sex = 'female'

or

$sex = 'male';
$s = $dbh->prepare('SELECT name FROM students WHERE sex = :sex');
$s->bindValue(':sex', $sex); // use bindValue to bind the variable's value
$sex = 'female';
$s->execute(); // executed with WHERE sex = 'male'

Keyword not supported: "data source" initializing Entity Framework Context

This appears to be missing the providerName="System.Data.EntityClient" bit. Sure you got the whole thing?

How to start an Intent by passing some parameters to it?

In order to pass the parameters you create new intent and put a parameter map:

Intent myIntent = new Intent(this, NewActivityClassName.class);
myIntent.putExtra("firstKeyName","FirstKeyValue");
myIntent.putExtra("secondKeyName","SecondKeyValue");
startActivity(myIntent);

In order to get the parameters values inside the started activity, you must call the get[type]Extra() on the same intent:

// getIntent() is a method from the started activity
Intent myIntent = getIntent(); // gets the previously created intent
String firstKeyName = myIntent.getStringExtra("firstKeyName"); // will return "FirstKeyValue"
String secondKeyName= myIntent.getStringExtra("secondKeyName"); // will return "SecondKeyValue"

If your parameters are ints you would use getIntExtra() instead etc. Now you can use your parameters like you normally would.

How to convert a Java String to an ASCII byte array?

In my string I have Thai characters (TIS620 encoded) and German umlauts. The answer from agiles put me on the right path. Instead of .getBytes() I use now

  int len = mString.length(); // Length of the string
  byte[] dataset = new byte[len];
  for (int i = 0; i < len; ++i) {
     char c = mString.charAt(i);
     dataset[i]= (byte) c;
  }

adding css class to multiple elements

try this:

.button input, .button a {
//css here
}

That will apply the style to all a tags nested inside of <p class="button"></p>

Is it a bad practice to use an if-statement without curly braces?

I prefer using braces. Adding braces makes it easier to read and modify.

Here are some links for the use of braces:

submitting a GET form with query string params and hidden params disappear

I usually write something like this:

foreach($_GET as $key=>$content){
        echo "<input type='hidden' name='$key' value='$content'/>";
}

This is working, but don't forget to sanitize your inputs against XSS attacks!

JavaScript set object key by variable

You need to make the object first, then use [] to set it.

var key = "happyCount";
var obj = {};
obj[key] = someValueArray;
myArray.push(obj);

UPDATE 2018:

If you're able to use ES6 and Babel, you can use this new feature:

{
    [yourKeyVariable]: someValueArray,
}  

How to view the stored procedure code in SQL Server Management Studio

In case you don't have permission to 'Modify', you can install a free tool called "SQL Search" (by Redgate). I use it to search for keywords that I know will be in the SP and it returns a preview of the SP code with the keywords highlighted.

Ingenious! I then copy this code into my own SP.

Oracle: SQL query to find all the triggers belonging to the tables?

Another table that is useful is:

SELECT * FROM user_objects WHERE object_type='TRIGGER';

You can also use this to query views, indexes etc etc

How to load Spring Application Context

I am using in the way and it is working for me.

public static void main(String[] args) {
    new CarpoolDBAppTest();

}

public CarpoolDBAppTest(){
    ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
    Student stud = (Student) context.getBean("yourBeanId");
}

Here Student is my classm you will get the class matching yourBeanId.

Now work on that object with whatever operation you want to do.

How to create a custom exception type in Java?

You can create you own exception by inheriting from java.lang.Exception Here is an example that can help you do that.

How to keep two folders automatically synchronized?

You can use inotifywait (with the modify,create,delete,move flags enabled) and rsync.

while inotifywait -r -e modify,create,delete,move /directory; do
    rsync -avz /directory /target
done

If you don't have inotifywait on your system, run sudo apt-get install inotify-tools

Make anchor link go some pixels above where it's linked to

This is also a good solution. Make a div above the destination div like this and link the a to this div;

<div class="destination" id="link"></div> /**Needs to be above the destination**/

.destination {
    position:absolute;
    z-index:-1;
    left:0;
    margin-top:-100px;/* height of nav*/
}

What is the significance of url-pattern in web.xml and how to configure servlet?

url-pattern is used in web.xml to map your servlet to specific URL. Please see below xml code, similar code you may find in your web.xml configuration file.

<servlet>
    <servlet-name>AddPhotoServlet</servlet-name>  //servlet name
    <servlet-class>upload.AddPhotoServlet</servlet-class>  //servlet class
</servlet>
 <servlet-mapping>
    <servlet-name>AddPhotoServlet</servlet-name>   //servlet name
    <url-pattern>/AddPhotoServlet</url-pattern>  //how it should appear
</servlet-mapping>

If you change url-pattern of AddPhotoServlet from /AddPhotoServlet to /MyUrl. Then, AddPhotoServlet servlet can be accessible by using /MyUrl. Good for the security reason, where you want to hide your actual page URL.

Java Servlet url-pattern Specification:

  1. A string beginning with a '/' character and ending with a '/*' suffix is used for path mapping.
  2. A string beginning with a '*.' prefix is used as an extension mapping.
  3. A string containing only the '/' character indicates the "default" servlet of the application. In this case the servlet path is the request URI minus the context path and the path info is null.
  4. All other strings are used for exact matches only.

Reference : Java Servlet Specification

You may also read this Basics of Java Servlet

Amazon S3 boto - how to create a folder?

S3 doesn't have a folder structure, But there is something called as keys.

We can create /2013/11/xyz.xls and will be shown as folder's in the console. But the storage part of S3 will take that as the file name.

Even when retrieving we observe that we can see files in particular folder (or keys) by using the ListObjects method and using the Prefix parameter.

How to prevent downloading images and video files from my website?

No, it's not possible.

If you can see it, you can get it.

How to determine previous page URL in Angular?

You can subscribe to route changes and store the current event so you can use it when the next happens

previousUrl: string;
constructor(router: Router) {
  router.events
  .pipe(filter(event => event instanceof NavigationEnd))
  .subscribe((event: NavigationEnd) => {
    console.log('prev:', event.url);
    this.previousUrl = event.url;
  });
}

See also How to detect a route change in Angular?

How to write a simple Html.DropDownListFor()?

See this MSDN article and an example usage here on Stack Overflow.

Let's say that you have the following Linq/POCO class:

public class Color
{
    public int ColorId { get; set; }
    public string Name { get; set; }
}

And let's say that you have the following model:

public class PageModel 
{
   public int MyColorId { get; set; }
}

And, finally, let's say that you have the following list of colors. They could come from a Linq query, from a static list, etc.:

public static IEnumerable<Color> Colors = new List<Color> { 
    new Color {
        ColorId = 1,
        Name = "Red"
    },
    new Color {
        ColorId = 2,
        Name = "Blue"
    }
};

In your view, you can create a drop down list like so:

<%= Html.DropDownListFor(n => n.MyColorId, 
                         new SelectList(Colors, "ColorId", "Name")) %>

Two values from one input in python?

This is a sample code to take two inputs seperated by split command and delimiter as ","


>>> var1, var2 = input("enter two numbers:").split(',')
>>>enter two numbers:2,3
>>> var1
'2'
>>> var2
'3'


Other variations of delimiters that can be used are as below :
var1, var2 = input("enter two numbers:").split(',')
var1, var2 = input("enter two numbers:").split(';')
var1, var2 = input("enter two numbers:").split('/')
var1, var2 = input("enter two numbers:").split(' ')
var1, var2 = input("enter two numbers:").split('~')

Return HTTP status code 201 in flask

As lacks suggested send status code in return statement and if you are storing it in some variable like

notfound = 404
invalid = 403
ok = 200

and using

return xyz, notfound

than time make sure its type is int not str. as I faced this small issue also here is list of status code followed globally http://www.w3.org/Protocols/HTTP/HTRESP.html

Hope it helps.

Select rows of a matrix that meet a condition

m <- matrix(1:20, ncol = 4) 
colnames(m) <- letters[1:4]

The following command will select the first row of the matrix above.

subset(m, m[,4] == 16)

And this will select the last three.

subset(m, m[,4] > 17)

The result will be a matrix in both cases. If you want to use column names to select columns then you would be best off converting it to a dataframe with

mf <- data.frame(m)

Then you can select with

mf[ mf$a == 16, ]

Or, you could use the subset command.

How to fix getImageData() error The canvas has been tainted by cross-origin data?

I was seeing this error on Chrome while I was testing my code locally. I switched to Firefox and I am not seeing the error any more. Maybe switching to another browser is a quick fix.

If you are using the solution given in first answer, then make sure you add img.crossOrigin = "Anonymous"; just after you declare the img variable (for eg. var img = new Image();).

How to return a html page from a restful controller in spring boot?

I'm not using Thymeleaf and the only way it worked for me was with @Controller in the class and

@RequestMapping(method = RequestMethod.GET, value = "/")
public String index() {
    return "index.html";
}

How to check if a file exists before creating a new file

C++17, cross-platform: Using std::filesystem::exists and std::filesystem::is_regular_file.

#include <filesystem> // C++17
#include <fstream>
#include <iostream>
namespace fs = std::filesystem;

bool CreateFile(const fs::path& filePath, const std::string& content)
{
    try
    {
        if (fs::exists(filePath))
        {
            std::cout << filePath << " already exists.";
            return false;
        }
        if (!fs::is_regular_file(filePath))
        {
            std::cout << filePath << " is not a regular file.";
            return false;
        }
    }
    catch (std::exception& e)
    {
        std::cerr << __func__ << ": An error occurred: " << e.what();
        return false;
    }
    std::ofstream file(filePath);
    file << content;
    return true;
}
int main()
{
    if (CreateFile("path/to/the/file.ext", "Content of the file"))
    {
        // Your business logic.
    }
}

TSQL: How to convert local time to UTC? (SQL Server 2008)

I tend to lean towards using DateTimeOffset for all date-time storage that isn't related to a local event (ie: meeting/party, etc, 12pm-3pm at the museum).

To get the current DTO as UTC:

DECLARE @utcNow DATETIMEOFFSET = CONVERT(DATETIMEOFFSET, SYSUTCDATETIME())
DECLARE @utcToday DATE = CONVERT(DATE, @utcNow);
DECLARE @utcTomorrow DATE = DATEADD(D, 1, @utcNow);
SELECT  @utcToday [today]
        ,@utcTomorrow [tomorrow]
        ,@utcNow [utcNow]

NOTE: I will always use UTC when sending over the wire... client-side JS can easily get to/from local UTC. See: new Date().toJSON() ...

The following JS will handle parsing a UTC/GMT date in ISO8601 format to a local datetime.

if (typeof Date.fromISOString != 'function') {
  //method to handle conversion from an ISO-8601 style string to a Date object
  //  Date.fromISOString("2009-07-03T16:09:45Z")
  //    Fri Jul 03 2009 09:09:45 GMT-0700
  Date.fromISOString = function(input) {
    var date = new Date(input); //EcmaScript5 includes ISO-8601 style parsing
    if (!isNaN(date)) return date;

    //early shorting of invalid input
    if (typeof input !== "string" || input.length < 10 || input.length > 40) return null;

    var iso8601Format = /^(\d{4})-(\d{2})-(\d{2})((([T ](\d{2}):(\d{2})(:(\d{2})(\.(\d{1,12}))?)?)?)?)?([Zz]|([-+])(\d{2})\:?(\d{2}))?$/;

    //normalize input
    var input = input.toString().replace(/^\s+/,'').replace(/\s+$/,'');

    if (!iso8601Format.test(input))
      return null; //invalid format

    var d = input.match(iso8601Format);
    var offset = 0;

    date = new Date(+d[1], +d[2]-1, +d[3], +d[7] || 0, +d[8] || 0, +d[10] || 0, Math.round(+("0." + (d[12] || 0)) * 1000));

    //use specified offset
    if (d[13] == 'Z') offset = 0-date.getTimezoneOffset();
    else if (d[13]) offset = ((parseInt(d[15],10) * 60) + (parseInt(d[16],10)) * ((d[14] == '-') ? 1 : -1)) - date.getTimezoneOffset();

    date.setTime(date.getTime() + (offset * 60000));

    if (date.getTime() <= new Date(-62135571600000).getTime()) // CLR DateTime.MinValue
      return null;

    return date;
  };
}

Best practice for REST token-based authentication with JAX-RS and Jersey

How token-based authentication works

In token-based authentication, the client exchanges hard credentials (such as username and password) for a piece of data called token. For each request, instead of sending the hard credentials, the client will send the token to the server to perform authentication and then authorization.

In a few words, an authentication scheme based on tokens follow these steps:

  1. The client sends their credentials (username and password) to the server.
  2. The server authenticates the credentials and, if they are valid, generate a token for the user.
  3. The server stores the previously generated token in some storage along with the user identifier and an expiration date.
  4. The server sends the generated token to the client.
  5. The client sends the token to the server in each request.
  6. The server, in each request, extracts the token from the incoming request. With the token, the server looks up the user details to perform authentication.
    • If the token is valid, the server accepts the request.
    • If the token is invalid, the server refuses the request.
  7. Once the authentication has been performed, the server performs authorization.
  8. The server can provide an endpoint to refresh tokens.

Note: The step 3 is not required if the server has issued a signed token (such as JWT, which allows you to perform stateless authentication).

What you can do with JAX-RS 2.0 (Jersey, RESTEasy and Apache CXF)

This solution uses only the JAX-RS 2.0 API, avoiding any vendor specific solution. So, it should work with JAX-RS 2.0 implementations, such as Jersey, RESTEasy and Apache CXF.

It is worthwhile to mention that if you are using token-based authentication, you are not relying on the standard Java EE web application security mechanisms offered by the servlet container and configurable via application's web.xml descriptor. It's a custom authentication.

Authenticating a user with their username and password and issuing a token

Create a JAX-RS resource method which receives and validates the credentials (username and password) and issue a token for the user:

@Path("/authentication")
public class AuthenticationEndpoint {

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public Response authenticateUser(@FormParam("username") String username, 
                                     @FormParam("password") String password) {

        try {

            // Authenticate the user using the credentials provided
            authenticate(username, password);

            // Issue a token for the user
            String token = issueToken(username);

            // Return the token on the response
            return Response.ok(token).build();

        } catch (Exception e) {
            return Response.status(Response.Status.FORBIDDEN).build();
        }      
    }

    private void authenticate(String username, String password) throws Exception {
        // Authenticate against a database, LDAP, file or whatever
        // Throw an Exception if the credentials are invalid
    }

    private String issueToken(String username) {
        // Issue a token (can be a random String persisted to a database or a JWT token)
        // The issued token must be associated to a user
        // Return the issued token
    }
}

If any exceptions are thrown when validating the credentials, a response with the status 403 (Forbidden) will be returned.

If the credentials are successfully validated, a response with the status 200 (OK) will be returned and the issued token will be sent to the client in the response payload. The client must send the token to the server in every request.

When consuming application/x-www-form-urlencoded, the client must to send the credentials in the following format in the request payload:

username=admin&password=123456

Instead of form params, it's possible to wrap the username and the password into a class:

public class Credentials implements Serializable {

    private String username;
    private String password;

    // Getters and setters omitted
}

And then consume it as JSON:

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response authenticateUser(Credentials credentials) {

    String username = credentials.getUsername();
    String password = credentials.getPassword();

    // Authenticate the user, issue a token and return a response
}

Using this approach, the client must to send the credentials in the following format in the payload of the request:

{
  "username": "admin",
  "password": "123456"
}

Extracting the token from the request and validating it

The client should send the token in the standard HTTP Authorization header of the request. For example:

Authorization: Bearer <token-goes-here>

The name of the standard HTTP header is unfortunate because it carries authentication information, not authorization. However, it's the standard HTTP header for sending credentials to the server.

JAX-RS provides @NameBinding, a meta-annotation used to create other annotations to bind filters and interceptors to resource classes and methods. Define a @Secured annotation as following:

@NameBinding
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface Secured { }

The above defined name-binding annotation will be used to decorate a filter class, which implements ContainerRequestFilter, allowing you to intercept the request before it be handled by a resource method. The ContainerRequestContext can be used to access the HTTP request headers and then extract the token:

@Secured
@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {

    private static final String REALM = "example";
    private static final String AUTHENTICATION_SCHEME = "Bearer";

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        // Get the Authorization header from the request
        String authorizationHeader =
                requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);

        // Validate the Authorization header
        if (!isTokenBasedAuthentication(authorizationHeader)) {
            abortWithUnauthorized(requestContext);
            return;
        }

        // Extract the token from the Authorization header
        String token = authorizationHeader
                            .substring(AUTHENTICATION_SCHEME.length()).trim();

        try {

            // Validate the token
            validateToken(token);

        } catch (Exception e) {
            abortWithUnauthorized(requestContext);
        }
    }

    private boolean isTokenBasedAuthentication(String authorizationHeader) {

        // Check if the Authorization header is valid
        // It must not be null and must be prefixed with "Bearer" plus a whitespace
        // The authentication scheme comparison must be case-insensitive
        return authorizationHeader != null && authorizationHeader.toLowerCase()
                    .startsWith(AUTHENTICATION_SCHEME.toLowerCase() + " ");
    }

    private void abortWithUnauthorized(ContainerRequestContext requestContext) {

        // Abort the filter chain with a 401 status code response
        // The WWW-Authenticate header is sent along with the response
        requestContext.abortWith(
                Response.status(Response.Status.UNAUTHORIZED)
                        .header(HttpHeaders.WWW_AUTHENTICATE, 
                                AUTHENTICATION_SCHEME + " realm=\"" + REALM + "\"")
                        .build());
    }

    private void validateToken(String token) throws Exception {
        // Check if the token was issued by the server and if it's not expired
        // Throw an Exception if the token is invalid
    }
}

If any problems happen during the token validation, a response with the status 401 (Unauthorized) will be returned. Otherwise the request will proceed to a resource method.

Securing your REST endpoints

To bind the authentication filter to resource methods or resource classes, annotate them with the @Secured annotation created above. For the methods and/or classes that are annotated, the filter will be executed. It means that such endpoints will only be reached if the request is performed with a valid token.

If some methods or classes do not need authentication, simply do not annotate them:

@Path("/example")
public class ExampleResource {

    @GET
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response myUnsecuredMethod(@PathParam("id") Long id) {
        // This method is not annotated with @Secured
        // The authentication filter won't be executed before invoking this method
        ...
    }

    @DELETE
    @Secured
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response mySecuredMethod(@PathParam("id") Long id) {
        // This method is annotated with @Secured
        // The authentication filter will be executed before invoking this method
        // The HTTP request must be performed with a valid token
        ...
    }
}

In the example shown above, the filter will be executed only for the mySecuredMethod(Long) method because it's annotated with @Secured.

Identifying the current user

It's very likely that you will need to know the user who is performing the request agains your REST API. The following approaches can be used to achieve it:

Overriding the security context of the current request

Within your ContainerRequestFilter.filter(ContainerRequestContext) method, a new SecurityContext instance can be set for the current request. Then override the SecurityContext.getUserPrincipal(), returning a Principal instance:

final SecurityContext currentSecurityContext = requestContext.getSecurityContext();
requestContext.setSecurityContext(new SecurityContext() {

        @Override
        public Principal getUserPrincipal() {
            return () -> username;
        }

    @Override
    public boolean isUserInRole(String role) {
        return true;
    }

    @Override
    public boolean isSecure() {
        return currentSecurityContext.isSecure();
    }

    @Override
    public String getAuthenticationScheme() {
        return AUTHENTICATION_SCHEME;
    }
});

Use the token to look up the user identifier (username), which will be the Principal's name.

Inject the SecurityContext in any JAX-RS resource class:

@Context
SecurityContext securityContext;

The same can be done in a JAX-RS resource method:

@GET
@Secured
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response myMethod(@PathParam("id") Long id, 
                         @Context SecurityContext securityContext) {
    ...
}

And then get the Principal:

Principal principal = securityContext.getUserPrincipal();
String username = principal.getName();

Using CDI (Context and Dependency Injection)

If, for some reason, you don't want to override the SecurityContext, you can use CDI (Context and Dependency Injection), which provides useful features such as events and producers.

Create a CDI qualifier:

@Qualifier
@Retention(RUNTIME)
@Target({ METHOD, FIELD, PARAMETER })
public @interface AuthenticatedUser { }

In your AuthenticationFilter created above, inject an Event annotated with @AuthenticatedUser:

@Inject
@AuthenticatedUser
Event<String> userAuthenticatedEvent;

If the authentication succeeds, fire the event passing the username as parameter (remember, the token is issued for a user and the token will be used to look up the user identifier):

userAuthenticatedEvent.fire(username);

It's very likely that there's a class that represents a user in your application. Let's call this class User.

Create a CDI bean to handle the authentication event, find a User instance with the correspondent username and assign it to the authenticatedUser producer field:

@RequestScoped
public class AuthenticatedUserProducer {

    @Produces
    @RequestScoped
    @AuthenticatedUser
    private User authenticatedUser;

    public void handleAuthenticationEvent(@Observes @AuthenticatedUser String username) {
        this.authenticatedUser = findUser(username);
    }

    private User findUser(String username) {
        // Hit the the database or a service to find a user by its username and return it
        // Return the User instance
    }
}

The authenticatedUser field produces a User instance that can be injected into container managed beans, such as JAX-RS services, CDI beans, servlets and EJBs. Use the following piece of code to inject a User instance (in fact, it's a CDI proxy):

@Inject
@AuthenticatedUser
User authenticatedUser;

Note that the CDI @Produces annotation is different from the JAX-RS @Produces annotation:

Be sure you use the CDI @Produces annotation in your AuthenticatedUserProducer bean.

The key here is the bean annotated with @RequestScoped, allowing you to share data between filters and your beans. If you don't wan't to use events, you can modify the filter to store the authenticated user in a request scoped bean and then read it from your JAX-RS resource classes.

Compared to the approach that overrides the SecurityContext, the CDI approach allows you to get the authenticated user from beans other than JAX-RS resources and providers.

Supporting role-based authorization

Please refer to my other answer for details on how to support role-based authorization.

Issuing tokens

A token can be:

  • Opaque: Reveals no details other than the value itself (like a random string)
  • Self-contained: Contains details about the token itself (like JWT).

See details below:

Random string as token

A token can be issued by generating a random string and persisting it to a database along with the user identifier and an expiration date. A good example of how to generate a random string in Java can be seen here. You also could use:

Random random = new SecureRandom();
String token = new BigInteger(130, random).toString(32);

JWT (JSON Web Token)

JWT (JSON Web Token) is a standard method for representing claims securely between two parties and is defined by the RFC 7519.

It's a self-contained token and it enables you to store details in claims. These claims are stored in the token payload which is a JSON encoded as Base64. Here are some claims registered in the RFC 7519 and what they mean (read the full RFC for further details):

  • iss: Principal that issued the token.
  • sub: Principal that is the subject of the JWT.
  • exp: Expiration date for the token.
  • nbf: Time on which the token will start to be accepted for processing.
  • iat: Time on which the token was issued.
  • jti: Unique identifier for the token.

Be aware that you must not store sensitive data, such as passwords, in the token.

The payload can be read by the client and the integrity of the token can be easily checked by verifying its signature on the server. The signature is what prevents the token from being tampered with.

You won't need to persist JWT tokens if you don't need to track them. Althought, by persisting the tokens, you will have the possibility of invalidating and revoking the access of them. To keep the track of JWT tokens, instead of persisting the whole token on the server, you could persist the token identifier (jti claim) along with some other details such as the user you issued the token for, the expiration date, etc.

When persisting tokens, always consider removing the old ones in order to prevent your database from growing indefinitely.

Using JWT

There are a few Java libraries to issue and validate JWT tokens such as:

To find some other great resources to work with JWT, have a look at http://jwt.io.

Handling token revocation with JWT

If you want to revoke tokens, you must keep the track of them. You don't need to store the whole token on server side, store only the token identifier (that must be unique) and some metadata if you need. For the token identifier you could use UUID.

The jti claim should be used to store the token identifier on the token. When validating the token, ensure that it has not been revoked by checking the value of the jti claim against the token identifiers you have on server side.

For security purposes, revoke all the tokens for a user when they change their password.

Additional information

  • It doesn't matter which type of authentication you decide to use. Always do it on the top of a HTTPS connection to prevent the man-in-the-middle attack.
  • Take a look at this question from Information Security for more information about tokens.
  • In this article you will find some useful information about token-based authentication.

How to make a SIMPLE C++ Makefile

I suggest (note that the indent is a TAB):

tool: tool.o file1.o file2.o
    $(CXX) $(LDFLAGS) $^ $(LDLIBS) -o $@

or

LINK.o = $(CXX) $(LDFLAGS) $(TARGET_ARCH)
tool: tool.o file1.o file2.o

The latter suggestion is slightly better since it reuses GNU Make implicit rules. However, in order to work, a source file must have the same name as the final executable (i.e.: tool.c and tool).

Notice, it is not necessary to declare sources. Intermediate object files are generated using implicit rule. Consequently, this Makefile work for C and C++ (and also for Fortran, etc...).

Also notice, by default, Makefile use $(CC) as the linker. $(CC) does not work for linking C++ object files. We modify LINK.o only because of that. If you want to compile C code, you don't have to force the LINK.o value.

Sure, you can also add your compilation flags with variable CFLAGS and add your libraries in LDLIBS. For example:

CFLAGS = -Wall
LDLIBS = -lm

One side note: if you have to use external libraries, I suggest to use pkg-config in order to correctly set CFLAGS and LDLIBS:

CFLAGS += $(shell pkg-config --cflags libssl)
LDLIBS += $(shell pkg-config --libs libssl)

The attentive reader will notice that this Makefile does not rebuild properly if one header is changed. Add these lines to fix the problem:

override CPPFLAGS += -MMD
include $(wildcard *.d)

-MMD allows to build .d files that contains Makefile fragments about headers dependencies. The second line just uses them.

For sure, a well written Makefile should also include clean and distclean rules:

clean:
    $(RM) *.o *.d

distclean: clean
    $(RM) tool

Notice, $(RM) is the equivalent of rm -f, but it is a good practice to not call rm directly.

The all rule is also appreciated. In order to work, it should be the first rule of your file:

all: tool

You may also add an install rule:

PREFIX = /usr/local
install:
    install -m 755 tool $(DESTDIR)$(PREFIX)/bin

DESTDIR is empty by default. The user can set it to install your program at an alternative system (mandatory for cross-compilation process). Package maintainers for multiple distribution may also change PREFIX in order to install your package in /usr.

One final word: Do not place source files in sub-directories. If you really want to do that, keep this Makefile in the root directory and use full paths to identify your files (i.e. subdir/file.o).

So to summarise, your full Makefile should look like:

LINK.o = $(CXX) $(LDFLAGS) $(TARGET_ARCH)
PREFIX = /usr/local
override CPPFLAGS += -MMD
include $(wildcard *.d)

all: tool
tool: tool.o file1.o file2.o
clean:
    $(RM) *.o *.d
distclean: clean
    $(RM) tool
install:
    install -m 755 tool $(DESTDIR)$(PREFIX)/bin

jQuery’s .bind() vs. .on()

From the jQuery documentation:

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. For more flexible event binding, see the discussion of event delegation in .on() or .delegate().

http://api.jquery.com/bind/

JPA & Criteria API - Select only specific columns

One of the JPA ways for getting only particular columns is to ask for a Tuple object.

In your case you would need to write something like this:

CriteriaQuery<Tuple> cq = builder.createTupleQuery();
// write the Root, Path elements as usual
Root<EntityClazz> root = cq.from(EntityClazz.class);
cq.multiselect(root.get(EntityClazz_.ID), root.get(EntityClazz_.VERSION));  //using metamodel
List<Tuple> tupleResult = em.createQuery(cq).getResultList();
for (Tuple t : tupleResult) {
    Long id = (Long) t.get(0);
    Long version = (Long) t.get(1);
}

Another approach is possible if you have a class representing the result, like T in your case. T doesn't need to be an Entity class. If T has a constructor like:

public T(Long id, Long version)

then you can use T directly in your CriteriaQuery constructor:

CriteriaQuery<T> cq = builder.createQuery(T.class);
// write the Root, Path elements as usual
Root<EntityClazz> root = cq.from(EntityClazz.class);
cq.multiselect(root.get(EntityClazz_.ID), root.get(EntityClazz_.VERSION));  //using metamodel
List<T> result = em.createQuery(cq).getResultList();

See this link for further reference.

IntelliJ IDEA "The selected directory is not a valid home for JDK"

I had \bin as part of the path. Up one level of the selected directory worked for me.

Convert pandas DataFrame into list of lists

There is a built in method which would be the fastest method also, calling tolist on the .values np array:

df.values.tolist()

[[0.0, 3.61, 380.0, 3.0],
 [1.0, 3.67, 660.0, 3.0],
 [1.0, 3.19, 640.0, 4.0],
 [0.0, 2.93, 520.0, 4.0]]

How can I load Partial view inside the view?

If you want to load the partial view directly inside the main view you could use the Html.Action helper:

@Html.Action("Load", "Home")

or if you don't want to go through the Load action use the HtmlPartialAsync helper:

@await Html.PartialAsync("_LoadView")

If you want to use Ajax.ActionLink, replace your Html.ActionLink with:

@Ajax.ActionLink(
    "load partial view", 
    "Load", 
    "Home", 
    new AjaxOptions { UpdateTargetId = "result" }
)

and of course you need to include a holder in your page where the partial will be displayed:

<div id="result"></div>

Also don't forget to include:

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

in your main view in order to enable Ajax.* helpers. And make sure that unobtrusive javascript is enabled in your web.config (it should be by default):

<add key="UnobtrusiveJavaScriptEnabled" value="true" />

this in equals method

this is the current Object instance. Whenever you have a non-static method, it can only be called on an instance of your object.

Force “landscape” orientation mode

I use some css like this (based on css tricks):

@media screen and (min-width: 320px) and (max-width: 767px) and (orientation: portrait) {
  html {
    transform: rotate(-90deg);
    transform-origin: left top;
    width: 100vh;
    height: 100vw;
    overflow-x: hidden;
    position: absolute;
    top: 100%;
    left: 0;
  }
}

Role/Purpose of ContextLoaderListener in Spring?

It will give you point of hook to put some code that you wish to be executed on web application deploy time

How to 'foreach' a column in a DataTable using C#?

You can do it like this:

DataTable dt = new DataTable("MyTable");

foreach (DataRow row in dt.Rows)
{
    foreach (DataColumn column in dt.Columns)
    {
        if (row[column] != null) // This will check the null values also (if you want to check).
        {
               // Do whatever you want.
        }
     }
}

Setting Inheritance and Propagation flags with set-acl and powershell

Here's the MSDN page describing the flags and what is the result of their various combinations.

Flag combinations => Propagation results
=========================================
No Flags => Target folder.
ObjectInherit => Target folder, child object (file), grandchild object (file).
ObjectInherit and NoPropagateInherit => Target folder, child object (file).
ObjectInherit and InheritOnly => Child object (file), grandchild object (file).
ObjectInherit, InheritOnly, and NoPropagateInherit => Child object (file).
ContainerInherit => Target folder, child folder, grandchild folder.
ContainerInherit, and NoPropagateInherit => Target folder, child folder.
ContainerInherit, and InheritOnly => Child folder, grandchild folder.
ContainerInherit, InheritOnly, and NoPropagateInherit => Child folder.
ContainerInherit, and ObjectInherit => Target folder, child folder, child object (file), grandchild folder, grandchild object (file).
ContainerInherit, ObjectInherit, and NoPropagateInherit => Target folder, child folder, child object (file).
ContainerInherit, ObjectInherit, and InheritOnly => Child folder, child object (file), grandchild folder, grandchild object (file).
ContainerInherit, ObjectInherit, NoPropagateInherit, InheritOnly => Child folder, child object (file).

To have it apply the permissions to the directory, as well as all child directories and files recursively, you'll want to use these flags:

InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit 
PropagationFlags.None

So the specific code change you need to make for your example is:

$PropagationFlag = [System.Security.AccessControl.PropagationFlags]::None

Using "If cell contains" in VBA excel

This does the same, enhanced with CONTAINS:

Function SingleCellExtract(LookupValue As String, LookupRange As Range, ColumnNumber As Integer, Char As String)
Dim I As Long
Dim xRet As String
For I = 1 To LookupRange.Columns(1).Cells.Count
     If InStr(1, LookupRange.Cells(I, 1), LookupValue) > 0 Then
        If xRet = "" Then
            xRet = LookupRange.Cells(I, ColumnNumber) & Char
        Else
            xRet = xRet & "" & LookupRange.Cells(I, ColumnNumber) & Char
        End If
    End If
Next
SingleCellExtract = Left(xRet, Len(xRet) - 1)
End Function

curl.h no such file or directory

To those who use centos and have stumbled upon this post :

 $ yum install curl-devel

and when compiling your program example.cpp, link to the curl library:

 $ g++ example.cpp -lcurl -o example

"-o example" creates the executable example instead of the default a.out.

The next line runs example:

 $ ./example

Checking out Git tag leads to "detached HEAD state"

Yes, it is normal. This is because you checkout a single commit, that doesnt have a head. Especially it is (sooner or later) not a head of any branch.

But there is usually no problem with that state. You may create a new branch from the tag, if this makes you feel safer :)

What exactly is an instance in Java?

When you use the keyword new for example JFrame j = new JFrame(); you are creating an instance of the class JFrame.

The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory.
Note: The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you are creating an "instance" of a class, therefore "instantiating" a class.

Take a look here
Creating Objects


The types of the Java programming language are divided into two categories: primitive types and reference types.
The reference types are class types, interface types, and array types.
There is also a special null type.
An object is a dynamically created instance of a class type or a dynamically created array.
The values of a reference type are references to objects.

Refer Types, Values, and Variables for more information

Oracle Error ORA-06512

The variable pCv is of type VARCHAR2 so when you concat the insert you aren't putting it inside single quotes:

 EXECUTE IMMEDIATE  'INSERT INTO M'||pNum||'GR (CV, SUP, IDM'||pNum||') VALUES('''||pCv||''', '||pSup||', '||pIdM||')';

Additionally the error ORA-06512 raise when you are trying to insert a value too large in a column. Check the definiton of the table M_pNum_GR and the parameters that you are sending. Just for clarify if you try to insert the value 100 on a NUMERIC(2) field the error will raise.

Output first 100 characters in a string

From python tutorial:

Degenerate slice indices are handled gracefully: an index that is too large is replaced by the string size, an upper bound smaller than the lower bound returns an empty string.

So it is safe to use x[:100].

Reading Space separated input in python

For python 3 use this

inp = list(map(int,input().split()))
#input => java is a programming language
#return as => ("java","is","a","programming","language")

input() accepts a string from STDIN.

split() splits the string about whitespace character and returns a list of strings.

map() passes each element of the 2nd argument to the first argument and returns a map object

Finally list() converts the map to a list

What is ViewModel in MVC?

View model a is simple class which can contain more than one class property. We use it to inherit all the required properties, e.g. I have two classes Student and Subject

Public class Student
{
public int Id {get; set;}
public string Name {get; set;}
}  
Public class Subject
{
public int SubjectID {get; set;}
public string SubjectName {get; set;}
}

Now we want to display records student's Name and Subject's Name in View (In MVC), but it's not possible to add more than one classes like:

 @model ProjectName.Model.Student  
 @model ProjectName.Model.Subject

the code above will throw an error...

Now we create one class and can give it any name, but this format "XyzViewModel" will make it easier to understand. It is inheritance concept. Now we create a third class with the following name:

public class StudentViewModel:Subject
{
public int ID {get; set;}
public string Name {get; set;}
}

Now we use this ViewModel in View

@model ProjectName.Model.StudentViewModel

Now we are able to access all the properties of StudentViewModel and inherited class in View.

MySql difference between two timestamps in days?

If you want to return in full TIMESTAMP format than try it: -

 SELECT TIMEDIFF(`call_end_time`, `call_start_time`) as diff from tablename;

return like

     diff
     - - -
    00:05:15

What does "request for member '*******' in something not a structure or union" mean?

It may also happen in the following case:

eg. if we consider the push function of a stack:

typedef struct stack
{
    int a[20];
    int head;
}stack;

void push(stack **s)
{
    int data;
    printf("Enter data:");
    scanf("%d",&(*s->a[++*s->head])); /* this is where the error is*/
}

main()
{
    stack *s;
    s=(stack *)calloc(1,sizeof(stack));
    s->head=-1;
    push(&s);
    return 0;
}

The error is in the push function and in the commented line. The pointer s has to be included within the parentheses. The correct code:

scanf("%d",&( (*s)->a[++(*s)->head]));

How to listen state changes in react.js?

It's been a while but for future reference: the method shouldComponentUpdate() can be used.

An update can be caused by changes to props or state. These methods are called in the following order when a component is being re-rendered:

static getDerivedStateFromProps() 
shouldComponentUpdate() 
render()
getSnapshotBeforeUpdate() 
componentDidUpdate()

ref: https://reactjs.org/docs/react-component.html

Stored Procedure error ORA-06550

create or replace procedure point_triangle
AS
BEGIN
FOR thisteam in (select FIRSTNAME,LASTNAME,SUM(PTS)  from PLAYERREGULARSEASON  where TEAM    = 'IND' group by FIRSTNAME, LASTNAME order by SUM(PTS) DESC)

LOOP
dbms_output.put_line(thisteam.FIRSTNAME|| ' ' || thisteam.LASTNAME || ':' || thisteam.PTS);
END LOOP;

END;
/

jQuery checkbox onChange

There is no need to use :checkbox, also replace #activelist with #inactivelist:

$('#inactivelist').change(function () {
    alert('changed');
 });

How to fix "unable to open stdio.h in Turbo C" error?

Go to OPTIONS tab then select directories option then enter the particular path where your turbo c folder exists.

Enter the path in all the four message boxes and it would start working like it did in my case. I have TurboC3 and all the files were together in one common root folder.

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing

Instead of passing reference object passed the saved object, below is explanation which solve my issue:

//wrong
entityManager.persist(role);
user.setRole(role);
entityManager.persist(user)

//right
Role savedEntity= entityManager.persist(role);
user.setRole(savedEntity);
entityManager.persist(user)

Android Canvas.drawText

It should be noted that the documentation recommends using a Layout rather than Canvas.drawText directly. My full answer about using a StaticLayout is here, but I will provide a summary below.

String text = "This is some text.";

TextPaint textPaint = new TextPaint();
textPaint.setAntiAlias(true);
textPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
textPaint.setColor(0xFF000000);

int width = (int) textPaint.measureText(text);
StaticLayout staticLayout = new StaticLayout(text, textPaint, (int) width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
staticLayout.draw(canvas);

Here is a fuller example in the context of a custom view:

enter image description here

public class MyView extends View {

    String mText = "This is some text.";
    TextPaint mTextPaint;
    StaticLayout mStaticLayout;

    // use this constructor if creating MyView programmatically
    public MyView(Context context) {
        super(context);
        initLabelView();
    }

    // this constructor is used when created from xml
    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initLabelView();
    }

    private void initLabelView() {
        mTextPaint = new TextPaint();
        mTextPaint.setAntiAlias(true);
        mTextPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
        mTextPaint.setColor(0xFF000000);

        // default to a single line of text
        int width = (int) mTextPaint.measureText(mText);
        mStaticLayout = new StaticLayout(mText, mTextPaint, (int) width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);

        // New API alternate
        //
        // StaticLayout.Builder builder = StaticLayout.Builder.obtain(mText, 0, mText.length(), mTextPaint, width)
        //        .setAlignment(Layout.Alignment.ALIGN_NORMAL)
        //        .setLineSpacing(1, 0) // multiplier, add
        //        .setIncludePad(false);
        // mStaticLayout = builder.build();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // Tell the parent layout how big this view would like to be
        // but still respect any requirements (measure specs) that are passed down.

        // determine the width
        int width;
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthRequirement = MeasureSpec.getSize(widthMeasureSpec);
        if (widthMode == MeasureSpec.EXACTLY) {
            width = widthRequirement;
        } else {
            width = mStaticLayout.getWidth() + getPaddingLeft() + getPaddingRight();
            if (widthMode == MeasureSpec.AT_MOST) {
                if (width > widthRequirement) {
                    width = widthRequirement;
                    // too long for a single line so relayout as multiline
                    mStaticLayout = new StaticLayout(mText, mTextPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
                }
            }
        }

        // determine the height
        int height;
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightRequirement = MeasureSpec.getSize(heightMeasureSpec);
        if (heightMode == MeasureSpec.EXACTLY) {
            height = heightRequirement;
        } else {
            height = mStaticLayout.getHeight() + getPaddingTop() + getPaddingBottom();
            if (heightMode == MeasureSpec.AT_MOST) {
                height = Math.min(height, heightRequirement);
            }
        }

        // Required call: set width and height
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // do as little as possible inside onDraw to improve performance

        // draw the text on the canvas after adjusting for padding
        canvas.save();
        canvas.translate(getPaddingLeft(), getPaddingTop());
        mStaticLayout.draw(canvas);
        canvas.restore();
    }
}

String comparison - Android

In Java we don't compare string as you are doing above... Here is String comparison...

    if (gender.equalsIgnoreCase("Male")) {
        salutation = "Mr.";
    } else if (gender.equalsIgnoreCase("Female")) {
        salutation = "Ms.";
    }

ORA-00979 not a group by expression

Same error also come when UPPER or LOWER keyword not used in both place in select expression and group by expression .

Wrong :-

select a , count(*) from my_table group by UPPER(a) .

Right :-

select UPPER(a) , count(*) from my_table group by UPPER(a) .

Using Rsync include and exclude options to include directory and file by pattern

rsync include exclude pattern examples:

"*"         means everything
"dir1"      transfers empty directory [dir1]
"dir*"      transfers empty directories like: "dir1", "dir2", "dir3", etc...
"file*"     transfers files whose names start with [file]
"dir**"     transfers every path that starts with [dir] like "dir1/file.txt", "dir2/bar/ffaa.html", etc...
"dir***"    same as above
"dir1/*"    does nothing
"dir1/**"   does nothing
"dir1/***"  transfers [dir1] directory and all its contents like "dir1/file.txt", "dir1/fooo.sh", "dir1/fold/baar.py", etc...

And final note is that simply dont rely on asterisks that are used in the beginning for evaluating paths; like "**dir" (its ok to use them for single folders or files but not paths) and note that more than two asterisks dont work for file names.

How to disable HTML button using JavaScript?

<button disabled=true>text here</button>

You can still use an attribute. Just use the 'disabled' attribute instead of 'value'.

What's the difference between @JoinColumn and mappedBy when using a JPA @OneToMany association

I disagree with the accepted answer here by Óscar López. That answer is inaccurate!

It is NOT @JoinColumn which indicates that this entity is the owner of the relationship. Instead, it is the @ManyToOne annotation which does this (in his example).

The relationship annotations such as @ManyToOne, @OneToMany and @ManyToMany tell JPA/Hibernate to create a mapping. By default, this is done through a seperate Join Table.


@JoinColumn

The purpose of @JoinColumn is to create a join column if one does not already exist. If it does, then this annotation can be used to name the join column.


MappedBy

The purpose of the MappedBy parameter is to instruct JPA: Do NOT create another join table as the relationship is already being mapped by the opposite entity of this relationship.



Remember: MappedBy is a property of the relationship annotations whose purpose is to generate a mechanism to relate two entities which by default they do by creating a join table. MappedBy halts that process in one direction.

The entity not using MappedBy is said to be the owner of the relationship because the mechanics of the mapping are dictated within its class through the use of one of the three mapping annotations against the foreign key field. This not only specifies the nature of the mapping but also instructs the creation of a join table. Furthermore, the option to suppress the join table also exists by applying @JoinColumn annotation over the foreign key which keeps it inside the table of the owner entity instead.

So in summary: @JoinColumn either creates a new join column or renames an existing one; whilst the MappedBy parameter works collaboratively with the relationship annotations of the other (child) class in order to create a mapping either through a join table or by creating a foreign key column in the associated table of the owner entity.

To illustrate how MapppedBy works, consider the code below. If MappedBy parameter were to be deleted, then Hibernate would actually create TWO join tables! Why? Because there is a symmetry in many-to-many relationships and Hibernate has no rationale for selecting one direction over the other.

We therefore use MappedBy to tell Hibernate, we have chosen the other entity to dictate the mapping of the relationship between the two entities.

@Entity
public class Driver {
    @ManyToMany(mappedBy = "drivers")
    private List<Cars> cars;
}

@Entity
public class Cars {
    @ManyToMany
    private List<Drivers> drivers;
}

Adding @JoinColumn(name = "driverID") in the owner class (see below), will prevent the creation of a join table and instead, create a driverID foreign key column in the Cars table to construct a mapping:

@Entity
public class Driver {
    @ManyToMany(mappedBy = "drivers")
    private List<Cars> cars;
}

@Entity
public class Cars {
    @ManyToMany
    @JoinColumn(name = "driverID")
    private List<Drivers> drivers;
}

add scroll bar to table body

These solutions often have issues with the header columns aligning with the body columns, and may not work properly when resizing. I know you didn't want to use an additional library, but if you happen to be using jQuery, this one is really small. It supports fixed header, footer, column spanning (colspan), horizontal scrolling, resizing, and an optional number of rows to display before scrolling starts.

jQuery.scrollTableBody (GitHub)

As long as you have a table with proper <thead>, <tbody>, and (optional) <tfoot>, all you need to do is this:

$('table').scrollTableBody();

MySQL Select Multiple VALUES

Try or:

WHERE id = 3 or id = 4

Or the equivalent in:

WHERE id in (3,4)

Hide html horizontal but not vertical scrollbar

<div style="width:100px;height:100px;overflow-x:hidden;overflow-y:auto;background-color:#000000">

Use Excel pivot table as data source for another Pivot Table

Personally, I got around this in a slightly different way - I had a pivot table querying an SQL server source and I was using the timeline slicer to restrict the results to a date range - I then wanted to summarise the pivot results in another table.

I selected the 'source' pivot table and created a named range called 'SourcePivotData'.

Create your summary pivot tables using the named range as a source.

In the worksheet events for the source pivot table, I put the following code:

Private Sub Worksheet_PivotTableUpdate(ByVal Target As PivotTable)

'Update the address of the named range
ThisWorkbook.Names("SourcePivotData").RefersTo = "='" & Target.TableRange1.Worksheet.Name & "'!" & Target.TableRange1.AddressLocal

'Refresh any pivot tables that use this as a source
Dim pt As PivotTable
Application.DisplayAlerts = False
For Each pt In Sheet2.PivotTables
    pt.PivotCache.Refresh
Next pt
Application.DisplayAlerts = True

End Sub

Works nicely for me! :)

Convert character to Date in R

library(lubridate) if your date format is like this '04/24/2017 05:35:00'then change it like below prods.all$Date2<-gsub("/","-",prods.all$Date2) then change the date format parse_date_time(prods.all$Date2, orders="mdy hms")

Convert an image to grayscale in HTML/CSS

A new way to do this has been available for some time now on modern browsers.

background-blend-mode allows you to get some interesting effects, and one of them is grayscale conversion

The value luminosity , set on a white background, allows it. (hover to see it in gray)

_x000D_
_x000D_
.test {_x000D_
  width: 300px;_x000D_
  height: 200px;_x000D_
    background: url("http://placekitten.com/1000/750"), white; _x000D_
    background-size: cover;_x000D_
}_x000D_
_x000D_
.test:hover {_x000D_
    background-blend-mode: luminosity;_x000D_
}
_x000D_
<div class="test"></div>
_x000D_
_x000D_
_x000D_

The luminosity is taken from the image, the color is taken from the background. Since it is always white, there is no color.

But it allows much more.

You can animate the effect setting 3 layers. The first one will be the image, and the second will be a white-black gradient. If you apply a multiply blend mode on this, you will get a white result as before on the white part, but the original image on the black part (multiply by white gives white, multiplying by black has no effect.)

On the white part of the gradient, you get the same effect as before. On the black part of the gradient, you are blending the image over itself, and the result is the unmodified image.

Now, all that is needed is to move the gradient to get this effect dynamic: (hover to see it in color)

_x000D_
_x000D_
div {_x000D_
    width: 600px;_x000D_
    height: 400px;_x000D_
}_x000D_
_x000D_
.test {_x000D_
    background: url("http://placekitten.com/1000/750"), _x000D_
linear-gradient(0deg, white 33%, black 66%), url("http://placekitten.com/1000/750"); _x000D_
    background-position: 0px 0px, 0px 0%, 0px 0px;_x000D_
    background-size: cover, 100% 300%, cover;_x000D_
    background-blend-mode: luminosity, multiply;_x000D_
    transition: all 2s;_x000D_
}_x000D_
_x000D_
.test:hover {_x000D_
    background-position: 0px 0px, 0px 66%, 0px 0px;_x000D_
}
_x000D_
<div class="test"></div>
_x000D_
_x000D_
_x000D_

reference

compatibility matrix

C#: New line and tab characters in strings

sb.AppendLine();

or

sb.Append( "\n" );

And

sb.Append( "\t" );

How to display and hide a div with CSS?

You need

.abc,.ab {
    display: none;
}

#f:hover ~ .ab {
    display: block;
}

#s:hover ~ .abc {
    display: block;
}

#s:hover ~ .a,
#f:hover ~ .a{
    display: none;
}

Updated demo at http://jsfiddle.net/gaby/n5fzB/2/


The problem in your original CSS was that the , in css selectors starts a completely new selector. it is not combined.. so #f:hover ~ .abc,.a means #f:hover ~ .abc and .a. You set that to display:none so it was always set to be hidden for all .a elements.

How can query string parameters be forwarded through a proxy_pass with nginx?

you have to use rewrite to pass params using proxy_pass here is example I did for angularjs app deployment to s3

S3 Static Website Hosting Route All Paths to Index.html

adopted to your needs would be something like

location /service/ {
    rewrite ^\/service\/(.*) /$1 break;
    proxy_pass http://apache;
}

if you want to end up in http://127.0.0.1:8080/query/params/

if you want to end up in http://127.0.0.1:8080/service/query/params/ you'll need something like

location /service/ {
    rewrite ^\/(.*) /$1 break;
    proxy_pass http://apache;
}

Custom thread pool in Java 8 parallel stream

I tried the custom ForkJoinPool as follows to adjust the pool size:

private static Set<String> ThreadNameSet = new HashSet<>();
private static Callable<Long> getSum() {
    List<Long> aList = LongStream.rangeClosed(0, 10_000_000).boxed().collect(Collectors.toList());
    return () -> aList.parallelStream()
            .peek((i) -> {
                String threadName = Thread.currentThread().getName();
                ThreadNameSet.add(threadName);
            })
            .reduce(0L, Long::sum);
}

private static void testForkJoinPool() {
    final int parallelism = 10;

    ForkJoinPool forkJoinPool = null;
    Long result = 0L;
    try {
        forkJoinPool = new ForkJoinPool(parallelism);
        result = forkJoinPool.submit(getSum()).get(); //this makes it an overall blocking call

    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    } finally {
        if (forkJoinPool != null) {
            forkJoinPool.shutdown(); //always remember to shutdown the pool
        }
    }
    out.println(result);
    out.println(ThreadNameSet);
}

Here is the output saying the pool is using more threads than the default 4.

50000005000000
[ForkJoinPool-1-worker-8, ForkJoinPool-1-worker-9, ForkJoinPool-1-worker-6, ForkJoinPool-1-worker-11, ForkJoinPool-1-worker-10, ForkJoinPool-1-worker-1, ForkJoinPool-1-worker-15, ForkJoinPool-1-worker-13, ForkJoinPool-1-worker-4, ForkJoinPool-1-worker-2]

But actually there is a weirdo, when I tried to achieve the same result using ThreadPoolExecutor as follows:

BlockingDeque blockingDeque = new LinkedBlockingDeque(1000);
ThreadPoolExecutor fixedSizePool = new ThreadPoolExecutor(10, 20, 60, TimeUnit.SECONDS, blockingDeque, new MyThreadFactory("my-thread"));

but I failed.

It will only start the parallelStream in a new thread and then everything else is just the same, which again proves that the parallelStream will use the ForkJoinPool to start its child threads.

Loop through checkboxes and count each one checked or unchecked

To build a result string exactly in the format you show, you can use this:

var sList = "";
$('input[type=checkbox]').each(function () {
    sList += "(" + $(this).val() + "-" + (this.checked ? "checked" : "not checked") + ")";
});
console.log (sList);

However, I would agree with @SLaks, I think you should re-consider the structure into which you will store this in your database.

EDIT: Sorry, I mis-read the output format you were looking for. Here is an update:

var sList = "";
$('input[type=checkbox]').each(function () {
    var sThisVal = (this.checked ? "1" : "0");
    sList += (sList=="" ? sThisVal : "," + sThisVal);
});
console.log (sList);

HTTP Error 500.19 and error code : 0x80070021

I solved this by doing the following:

WebServer(ISS)->WebServer->Application Development
add .NET Extensibility 3.5
add .NET Extensibility 4.5
add ASP.NET 4.5
add ISAPI Extensions
add ISAPI Filters

enter image description here

How can I detect browser type using jQuery?

$.browser.chrome = /chrom(e|ium)/.test(navigator.userAgent.toLowerCase()); 

if($.browser.chrome){
  alert(1);      
}

UPDATE:(10x to @Mr. Bacciagalupe)

jQuery has removed $.browser from 1.9 and their latest release.

But you can still use $.browser as a standalone plugin, found here

How to check internet access on Android? InetAddress never times out

Just create the following class which checks for an internet connection:

public class ConnectionStatus {

    private Context _context;

    public ConnectionStatus(Context context) {
        this._context = context;
    }

    public boolean isConnectionAvailable() {
        ConnectivityManager connectivity = (ConnectivityManager) _context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
                for (int i = 0; i < info.length; i++)
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
        }
        return false;
    }
}

This class simply contains a method which returns the boolean value of the connection status. Therefore in simple terms, if the method finds a valid connection to the Internet, the return value is true, otherwise false if no valid connection is found.

The following method in the MainActivity then calls the result from the method previously described, and prompts the user to act accordingly:

public void addListenerOnWifiButton() {
        Button btnWifi = (Button)findViewById(R.id.btnWifi);

        iia = new ConnectionStatus(getApplicationContext());

        isConnected = iia.isConnectionAvailable();
        if (!isConnected) {
            btnWifi.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
                    Toast.makeText(getBaseContext(), "Please connect to a hotspot",
                            Toast.LENGTH_SHORT).show();
                }
            });
        }
        else {
            btnWifi.setVisibility(4);
            warning.setText("This app may use your mobile data to update events and get their details.");
        }
    }

In the above code, if the result is false, (therefore there is no internet connection, the user is taken to the Android wi-fi panel, where he is prompted to connect to a wi-fi hotspot.

Tell Ruby Program to Wait some amount of time

Implementation of seconds/minutes/hours, which are rails methods. Note that implicit returns aren't needed, but they look cleaner, so I prefer them. I'm not sure Rails even has .days or if it goes further, but these are the ones I need.

class Integer
   def seconds
      return self
   end
   def minutes
      return self * 60
   end
   def hours
      return self * 3600
   end
   def days
      return self * 86400
   end
end

After this, you can do: sleep 5.seconds to sleep for 5 seconds. You can do sleep 5.minutes to sleep for 5 min. You can do sleep 5.hours to sleep for 5 hours. And finally, you can do sleep 5.days to sleep for 5 days... You can add any method that return the value of self * (amount of seconds in that timeframe). As an exercise, try implementing it for months!

Difference between [routerLink] and routerLink

ROUTER LINK DIRECTIVE:

[routerLink]="link"                  //when u pass URL value from COMPONENT file
[routerLink]="['link','parameter']" //when you want to pass some parameters along with route

 routerLink="link"                  //when you directly pass some URL 
[routerLink]="['link']"              //when you directly pass some URL

whitespaces in the path of windows filepath

(WINDOWS - AWS solution)
Solved for windows by putting tripple quotes around files and paths.
Benefits:
1) Prevents excludes that quietly were getting ignored.
2) Files/folders with spaces in them, will no longer kick errors.

    aws_command = 'aws s3 sync """D:/""" """s3://mybucket/my folder/"  --exclude """*RECYCLE.BIN/*""" --exclude """*.cab""" --exclude """System Volume Information/*""" '

    r = subprocess.run(f"powershell.exe {aws_command}", shell=True, capture_output=True, text=True)

Get class labels from Keras functional model

It is possible to save a "list" of labels in keras model directly. This way the user who uses the model for predictions and does not have any other sources of information can perform the lookup himself. Here is a dummy example of how one can perform an "injection" of labels

# assume we get labels as list
labels = ["cat","dog","horse","tomato"]
# here we start building our model with input image 299x299 and one output layer
xx = Input(shape=(299,299,3))
flat = Flatten()(xx)
output = Dense(shape=(4))(flat)
# here we perform injection of labels
tf_labels = tf.constant([labels],dtype="string")
tf_labels = tf.tile(labels,[tf.shape(xx)[0],1])
output_labels = Lambda(lambda x: tf_labels,name="label_injection")(xx)
#and finaly creating a model
model=tf.keras.Model(xx,[output,output_labels])

When used for prediction, this model returns tensor of scores and tensot of string labels. Model like this can be saved to h5. In this case the file contains the labels. This model can also be exported to saved_model and used for serving in the cloud.

AttributeError: 'str' object has no attribute

The problem is in your playerMovement method. You are creating the string name of your room variables (ID1, ID2, ID3):

letsago = "ID" + str(self.dirDesc.values())

However, what you create is just a str. It is not the variable. Plus, I do not think it is doing what you think its doing:

>>>str({'a':1}.values())
'dict_values([1])'

If you REALLY needed to find the variable this way, you could use the eval function:

>>>foo = 'Hello World!'
>>>eval('foo')
'Hello World!'

or the globals function:

class Foo(object):
    def __init__(self):
        super(Foo, self).__init__()
    def test(self, name):
        print(globals()[name])

foo = Foo()
bar = 'Hello World!'
foo.text('bar')

However, instead I would strongly recommend you rethink you class(es). Your userInterface class is essentially a Room. It shouldn't handle player movement. This should be within another class, maybe GameManager or something like that.

Undefined symbols for architecture arm64

This worked for me:

ios sdk 9.3

into your build setting of app.xcodeproj valid architecture: armv7 armv7s Build Active architecture : No

Clean and build , worked for me.

ld.exe: cannot open output file ... : Permission denied

It may be your Antivirus Software.

In my case Malwarebytes was holding a handle on my program's executable:

enter image description here

Using Process Explorer to close the handle, or just disabling antivirus for a bit work just fine.

Permission denied error on Github Push

Another way to get this error, is if you have duplicate or conflicting ~/.ssh/* entries. First check what is on your ssh key-chain with:

$ ssh-add -l
2048 SHA256:<hash1> [email protected] (RSA)
2048 SHA256:<hash2> [email protected] (RSA)
2048 SHA256:<hash3> [email protected] (RSA)

As you can see there are two emails which are the same, and easy for you to get confused. Then check your config file:

$ cat ~/.ssh/config

# GitHub: [email protected]
Host github_ex
 HostName github.com
 PreferredAuthentications publickey
 IdentityFile ~/.ssh/github_ex

# GitHub: [email protected]
Host github
 HostName github.com
 PreferredAuthentications publickey
 IdentityFile ~/.ssh/github

# Bitbucket: [email protected]
Host bitbucket
 HostName bitbucket.org
 PreferredAuthentications publickey
 IdentityFile ~/.ssh/bitbuc

Here you see that you have two different email accounts to github but same HostName. Someone is bound to get confused, including your git.

To resolve, manually remove (after copying) the (default) files:

cd ~/.ssh
rm id_rsa
rm id_rsa.pub

Now copy back the one you want to use, for example Host github:

cp -a github id_rsa
cp -a github.pub id_rsa.pub

Then try again.

For some reason, removing keys with ssh-add -d id_rsa didn't work as expected, as it seem that key-chain is cached.

Is there a TRY CATCH command in Bash

There are so many similar solutions which probably work. Below is a simple and working way to accomplish try/catch, with explanation in the comments.

#!/bin/bash

function a() {
  # do some stuff here
}
function b() {
  # do more stuff here
}

# this subshell is a scope of try
# try
(
  # this flag will make to exit from current subshell on any error
  # inside it (all functions run inside will also break on any error)
  set -e
  a
  b
  # do more stuff here
)
# and here we catch errors
# catch
errorCode=$?
if [ $errorCode -ne 0 ]; then
  echo "We have an error"
  # We exit the all script with the same error, if you don't want to
  # exit it and continue, just delete this line.
  exit $errorCode
fi

how to make window.open pop up Modal?

You can't make window.open modal and I strongly recommend you not to go that way. Instead you can use something like jQuery UI's dialog widget.

UPDATE:

You can use load() method:

$("#dialog").load("resource.php").dialog({options});

This way it would be faster but the markup will merge into your main document so any submit will be applied on the main window.

And you can use an IFRAME:

$("#dialog").append($("<iframe></iframe>").attr("src", "resource.php")).dialog({options});

This is slower, but will submit independently.

$(document).ready(function() is not working

Did you load jQuery in head section? Did you load it correctly?

<head>
   <script src="scripts/jquery.js"></script>
   ...
</head>

This code assumes jquery.js is in scripts directory. (You can change file name if you like)

You can also use jQuery as hosted by Google:

<head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
   ...
</head>

As per your comment:

Apparently, your web server is not configured to return jQuery-1.6.1.js on requesting /webProject/jquery-1.6.1.js. There may be numerous reasons for this, such as wrong file name, folder name, routing settings, etc. You need to create another question and describe your 404 in greater details (such as local file name, operation system, webserver name and settings).

Again, you can use jQuery as provided by Google (see above), however you still might want to find out why some local files don't get served on request.

Remove accents/diacritics in a string in JavaScript

In NPM there is a package for this: latinize

It's a very good package to solve this issue.

How do I check in JavaScript if a value exists at a certain array index?

With Lodash, you can do:

if(_.has(req,'documents')){
      if (req.documents.length)
      _.forEach(req.documents, function(document){
        records.push(document);
      });
} else {
}

if(_.has(req,'documents')) is to check whether our request object has a property named documents and if it has that prop, the next if (req.documents.length) is to validate if it is not an empty array, so the other stuffs like forEach can be proceeded.

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-jar-plugin:2.3.2 or one of its dependencies could not be resolved

Whenever if you get this error please delete .m2 repository from local drive C:\Users\user and delete .m2 from there. The reason is this is existing repository used by different workspace so not allowing new application to create

How can I get input radio elements to horizontally align?

To get your radio button to list horizontally , just add

RepeatDirection="Horizontal"

to your .aspx file where the asp:radiobuttonlist is being declared.

jquery $(window).width() and $(window).height() return different values when viewport has not been resized

Note that if the problem is being caused by appearing scrollbars, putting

body {
  overflow: hidden;
}

in your CSS might be an easy fix (if you don't need the page to scroll).

Search and get a line in Python

If you prefer a one-liner:

matched_lines = [line for line in my_string.split('\n') if "substring" in line]

Creating the Singleton design pattern in PHP5

Unfortunately Inwdr's answer breaks when there are multiple subclasses.

Here is a correct inheritable Singleton base class.

class Singleton
{
    private static $instances = array();
    protected function __construct() {}
    protected function __clone() {}
    public function __wakeup()
    {
        throw new Exception("Cannot unserialize singleton");
    }

    public static function getInstance()
    {
        $cls = get_called_class(); // late-static-bound class name
        if (!isset(self::$instances[$cls])) {
            self::$instances[$cls] = new static;
        }
        return self::$instances[$cls];
    }
}

Test code:

class Foo extends Singleton {}
class Bar extends Singleton {}

echo get_class(Foo::getInstance()) . "\n";
echo get_class(Bar::getInstance()) . "\n";

Postgresql: error "must be owner of relation" when changing a owner object

This solved my problem : Sample alter table statement to change the ownership.

ALTER TABLE databasechangelog OWNER TO arwin_ash;
ALTER TABLE databasechangeloglock OWNER TO arwin_ash;

Angular.js programmatically setting a form field to dirty

Made a jsFiddle just for you that solves this issue. simply set $dirty to true, but with a $timeout 0 so it runs after DOM was loaded.

Find it here: JsFiddle

$timeout(function () {
  $scope.form.uName.$dirty = true;
}, 0);

Is it possible to create static classes in PHP (like in C#)?

You can have static classes in PHP but they don't call the constructor automatically (if you try and call self::__construct() you'll get an error).

Therefore you'd have to create an initialize() function and call it in each method:

<?php

class Hello
{
    private static $greeting = 'Hello';
    private static $initialized = false;

    private static function initialize()
    {
        if (self::$initialized)
            return;

        self::$greeting .= ' There!';
        self::$initialized = true;
    }

    public static function greet()
    {
        self::initialize();
        echo self::$greeting;
    }
}

Hello::greet(); // Hello There!


?>

C linked list inserting node at the end

This works fine:

struct node *addNode(node *head, int value) {
    node *newNode = (node *) malloc(sizeof(node));
    newNode->value = value;
    newNode->next = NULL;

    if (head == NULL) {
        // Add at the beginning
        head = newNode;
    } else {
        node *current = head;

        while (current->next != NULL) {
            current = current->next;
        };

        // Add at the end
        current->next = newNode;
    }

    return head;
}

Example usage:

struct node *head = NULL;

for (int currentIndex = 1; currentIndex < 10; currentIndex++) {
    head = addNode(head, currentIndex);
}

How to append in a json file in Python?

json_obj=json.dumps(a_dict, ensure_ascii=False)

Read files from a Folder present in project

Use this Code for read all files in folder and sub-folders also

class Program
{
    static void Main(string[] args)
    {

        getfiles get = new getfiles();
        List<string> files =  get.GetAllFiles(@"D:\Document");

        foreach(string f in files)
        {
            Console.WriteLine(f);
        }


        Console.Read();
    }


}

class getfiles
{
    public List<string> GetAllFiles(string sDirt)
    {
        List<string> files = new List<string>();

        try
        {
            foreach (string file in Directory.GetFiles(sDirt))
            {
                files.Add(file);
            }
            foreach (string fl in Directory.GetDirectories(sDirt))
            {
                files.AddRange(GetAllFiles(fl));
            }
        }
        catch (Exception ex)
        {

            Console.WriteLine(ex.Message);
        }



        return files;
    }
}

Check if a file exists with wildcard in shell script

Update: For bash scripts, the most direct and performant approach is:

if compgen -G "${PROJECT_DIR}/*.png" > /dev/null; then
    echo "pattern exists!"
fi

This will work very speedily even in directories with millions of files and does not involve a new subshell.

Source


The simplest should be to rely on ls return value (it returns non-zero when the files do not exist):

if ls /path/to/your/files* 1> /dev/null 2>&1; then
    echo "files do exist"
else
    echo "files do not exist"
fi

I redirected the ls output to make it completely silent.


EDIT: Since this answer has got a bit of attention (and very useful critic remarks as comments), here is an optimization that also relies on glob expansion, but avoids the use of ls:

for f in /path/to/your/files*; do

    ## Check if the glob gets expanded to existing files.
    ## If not, f here will be exactly the pattern above
    ## and the exists test will evaluate to false.
    [ -e "$f" ] && echo "files do exist" || echo "files do not exist"

    ## This is all we needed to know, so we can break after the first iteration
    break
done

This is very similar to @grok12's answer, but it avoids the unnecessary iteration through the whole list.

How to print without newline or space?

It should be as simple as described at this link by Guido Van Rossum:

Re: How does one print without a c/r ?

http://legacy.python.org/search/hypermail/python-1992/0115.html

Is it possible to print something but not automatically have a carriage return appended to it ?

Yes, append a comma after the last argument to print. For instance, this loop prints the numbers 0..9 on a line separated by spaces. Note the parameterless "print" that adds the final newline:

>>> for i in range(10):
...     print i,
... else:
...     print
...
0 1 2 3 4 5 6 7 8 9
>>> 

Variably modified array at file scope

It is also possible to use enumeration.

typedef enum {
    typeNo1 = 1,
    typeNo2,
    typeNo3,
    typeNo4,
    NumOfTypes = typeNo4
}  TypeOfSomething;

do-while loop in R

Pretty self explanatory.

repeat{
  statements...
  if(condition){
    break
  }
}

Or something like that I would think. To get the effect of the do while loop, simply check for your condition at the end of the group of statements.

How do I sort an observable collection?

This is what I do with OC extensions:

    /// <summary>
    /// Synches the collection items to the target collection items.
    /// This does not observe sort order.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="source">The items.</param>
    /// <param name="updatedCollection">The updated collection.</param>
    public static void SynchCollection<T>(this IList<T> source, IEnumerable<T> updatedCollection)
    {
        // Evaluate
        if (updatedCollection == null) return;

        // Make a list
        var collectionArray = updatedCollection.ToArray();

        // Remove items from FilteredViewItems not in list
        source.RemoveRange(source.Except(collectionArray));

        // Add items not in FilteredViewItems that are in list
        source.AddRange(collectionArray.Except(source));
    }

    /// <summary>
    /// Synches the collection items to the target collection items.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="source">The source.</param>
    /// <param name="updatedCollection">The updated collection.</param>
    /// <param name="canSort">if set to <c>true</c> [can sort].</param>
    public static void SynchCollection<T>(this ObservableCollection<T> source,
        IList<T> updatedCollection, bool canSort = false)
    {
        // Synch collection
        SynchCollection(source, updatedCollection.AsEnumerable());

        // Sort collection
        if (!canSort) return;

        // Update indexes as needed
        for (var i = 0; i < updatedCollection.Count; i++)
        {
            // Index of new location
            var index = source.IndexOf(updatedCollection[i]);
            if (index == i) continue;

            // Move item to new index if it has changed.
            source.Move(index, i);
        }
    }

Remove all html tags from php string

Use PHP's strip_tags() function.

For example:

$businessDesc = strip_tags($row_get_Business['business_description']);
$businessDesc = substr($businessDesc, 0, 110);


print($businessDesc);

How to use responsive background image in css3 in bootstrap

Check this out,

body {
    background-color: black;
    background: url(img/bg.jpg) no-repeat center center fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

Get index of a key in json

Try this

var json = '{ "key1" : "watevr1", "key2" : "watevr2", "key3" : "watevr3" }';
json = $.parseJSON(json);

var i = 0, req_index = "";
$.each(json, function(index, value){
    if(index == 'key2'){
        req_index = i;
    }
    i++;
});
alert(req_index);

Why is my Spring @Autowired field null?

If you are not coding a web application, make sure your class in which @Autowiring is done is a spring bean. Typically, spring container won't be aware of the class which we might think of as a spring bean. We have to tell the Spring container about our spring classes.

This can be achieved by configuring in appln-contxt or the better way is to annotate class as @Component and please do not create the annotated class using new operator. Make sure you get it from Appln-context as below.

@Component
public class MyDemo {


    @Autowired
    private MyService  myService; 

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
            System.out.println("test");
            ApplicationContext ctx=new ClassPathXmlApplicationContext("spring.xml");
            System.out.println("ctx>>"+ctx);

            Customer c1=null;
            MyDemo myDemo=ctx.getBean(MyDemo.class);
            System.out.println(myDemo);
            myDemo.callService(ctx);


    }

    public void callService(ApplicationContext ctx) {
        // TODO Auto-generated method stub
        System.out.println("---callService---");
        System.out.println(myService);
        myService.callMydao();

    }

}

Html/PHP - Form - Input as array

in addition: for those who have a empty POST variable, don't use this:

name="[levels][level][]"

rather use this (as it is already here in this example):

name="levels[level][]"

Python regex to match dates

I built my solution on top of @aditya Prakash appraoch:

 print(re.search("^([1-9]|0[1-9]|1[0-9]|2[0-9]|3[0-1])(\.|-|/)([1-9]|0[1-9]|1[0-2])(\.|-|/)([0-9][0-9]|19[0-9][0-9]|20[0-9][0-9])$|^([0-9][0-9]|19[0-9][0-9]|20[0-9][0-9])(\.|-|/)([1-9]|0[1-9]|1[0-2])(\.|-|/)([1-9]|0[1-9]|1[0-9]|2[0-9]|3[0-1])$",'01/01/2018'))

The first part (^([1-9]|0[1-9]|1[0-9]|2[0-9]|3[0-1])(\.|-|/)([1-9]|0[1-9]|1[0-2])(\.|-|/)([0-9][0-9]|19[0-9][0-9]|20[0-9][0-9])$) can handle the following formats:

  • 01.10.2019
  • 1.1.2019
  • 1.1.19
  • 12/03/2020
  • 01.05.1950

The second part (^([0-9][0-9]|19[0-9][0-9]|20[0-9][0-9])(\.|-|/)([1-9]|0[1-9]|1[0-2])(\.|-|/)([1-9]|0[1-9]|1[0-9]|2[0-9]|3[0-1])$) can basically do the same, but in inverse order, where the year comes first, followed by month, and then day.

  • 2020/02/12

As delimiters it allows ., /, -. As years it allows everything from 1900-2099, also giving only two numbers is fine.

If you have suggestions for improvement please let me know in the comments, so I can update the answer.

java.io.StreamCorruptedException: invalid stream header: 7371007E

This exception may also occur if you are using Sockets on one side and SSLSockets on the other. Consistency is important.

How to right align widget in horizontal linear layout Android?

In case with TextView:

<TextView 
    android:text="TextView" 
    android:id="@+id/textView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"   
    android:gravity="right"
    android:textAlignment="gravity">    
</TextView>

How do you use subprocess.check_output() in Python?

The right answer (using Python 2.7 and later, since check_output() was introduced then) is:

py2output = subprocess.check_output(['python','py2.py','-i', 'test.txt'])

To demonstrate, here are my two programs:

py2.py:

import sys
print sys.argv

py3.py:

import subprocess
py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'])
print('py2 said:', py2output)

Running it:

$ python3 py3.py
py2 said: b"['py2.py', '-i', 'test.txt']\n"

Here's what's wrong with each of your versions:

py2output = subprocess.check_output([str('python py2.py '),'-i', 'test.txt'])

First, str('python py2.py') is exactly the same thing as 'python py2.py'—you're taking a str, and calling str to convert it to an str. This makes the code harder to read, longer, and even slower, without adding any benefit.

More seriously, python py2.py can't be a single argument, unless you're actually trying to run a program named, say, /usr/bin/python\ py2.py. Which you're not; you're trying to run, say, /usr/bin/python with first argument py2.py. So, you need to make them separate elements in the list.

Your second version fixes that, but you're missing the ' before test.txt'. This should give you a SyntaxError, probably saying EOL while scanning string literal.

Meanwhile, I'm not sure how you found documentation but couldn't find any examples with arguments. The very first example is:

>>> subprocess.check_output(["echo", "Hello World!"])
b'Hello World!\n'

That calls the "echo" command with an additional argument, "Hello World!".

Also:

-i is a positional argument for argparse, test.txt is what the -i is

I'm pretty sure -i is not a positional argument, but an optional argument. Otherwise, the second half of the sentence makes no sense.

VBA check if object is set

If obj Is Nothing Then
    ' need to initialize obj: '
    Set obj = ...
Else
    ' obj already set / initialized. '
End If

Or, if you prefer it the other way around:

If Not obj Is Nothing Then
    ' obj already set / initialized. '
Else
    ' need to initialize obj: '
    Set obj = ...
End If

List all employee's names and their managers by manager name using an inner join

You have an incorrect ON clause at the join, this works:

inner join Employees m on e.mgr = m.EmpId;

The mgr column references the EmpId column.

DEMO

CSS @font-face not working in ie

If you're still having troubles with this, here's your solution:

http://www.fontsquirrel.com/fontface/generator

It works far better/faster than any other font-generator and also gives an example for you to use.

How to create a directive with a dynamic template in AngularJS?

I managed to deal with this problem. Below is the link :

https://github.com/nakosung/ng-dynamic-template-example

with the specific file being:

https://github.com/nakosung/ng-dynamic-template-example/blob/master/src/main.coffee

dynamicTemplate directive hosts dynamic template which is passed within scope and hosted element acts like other native angular elements.

scope.template = '< div ng-controller="SomeUberCtrl">rocks< /div>'

From an array of objects, extract value of a property as array

Check out Lodash's _.pluck() function or Underscore's _.pluck() function. Both do exactly what you want in a single function call!

var result = _.pluck(objArray, 'foo');

Update: _.pluck() has been removed as of Lodash v4.0.0, in favour of _.map() in combination with something similar to Niet's answer. _.pluck() is still available in Underscore.

Update 2: As Mark points out in the comments, somewhere between Lodash v4 and 4.3, a new function has been added that provides this functionality again. _.property() is a shorthand function that returns a function for getting the value of a property in an object.

Additionally, _.map() now allows a string to be passed in as the second parameter, which is passed into _.property(). As a result, the following two lines are equivalent to the code sample above from pre-Lodash 4.

var result = _.map(objArray, 'foo');
var result = _.map(objArray, _.property('foo'));

_.property(), and hence _.map(), also allow you to provide a dot-separated string or array in order to access sub-properties:

var objArray = [
    {
        someProperty: { aNumber: 5 }
    },
    {
        someProperty: { aNumber: 2 }
    },
    {
        someProperty: { aNumber: 9 }
    }
];
var result = _.map(objArray, _.property('someProperty.aNumber'));
var result = _.map(objArray, _.property(['someProperty', 'aNumber']));

Both _.map() calls in the above example will return [5, 2, 9].

If you're a little more into functional programming, take a look at Ramda's R.pluck() function, which would look something like this:

var result = R.pluck('foo')(objArray);  // or just R.pluck('foo', objArray)

Quickly reading very large tables as dataframes

Often times I think it is just good practice to keep larger databases inside a database (e.g. Postgres). I don't use anything too much larger than (nrow * ncol) ncell = 10M, which is pretty small; but I often find I want R to create and hold memory intensive graphs only while I query from multiple databases. In the future of 32 GB laptops, some of these types of memory problems will disappear. But the allure of using a database to hold the data and then using R's memory for the resulting query results and graphs still may be useful. Some advantages are:

(1) The data stays loaded in your database. You simply reconnect in pgadmin to the databases you want when you turn your laptop back on.

(2) It is true R can do many more nifty statistical and graphing operations than SQL. But I think SQL is better designed to query large amounts of data than R.

# Looking at Voter/Registrant Age by Decade

library(RPostgreSQL);library(lattice)

con <- dbConnect(PostgreSQL(), user= "postgres", password="password",
                 port="2345", host="localhost", dbname="WC2014_08_01_2014")

Decade_BD_1980_42 <- dbGetQuery(con,"Select PrecinctID,Count(PrecinctID),extract(DECADE from Birthdate) from voterdb where extract(DECADE from Birthdate)::numeric > 198 and PrecinctID in (Select * from LD42) Group By PrecinctID,date_part Order by Count DESC;")

Decade_RD_1980_42 <- dbGetQuery(con,"Select PrecinctID,Count(PrecinctID),extract(DECADE from RegistrationDate) from voterdb where extract(DECADE from RegistrationDate)::numeric > 198 and PrecinctID in (Select * from LD42) Group By PrecinctID,date_part Order by Count DESC;")

with(Decade_BD_1980_42,(barchart(~count | as.factor(precinctid))));
mtext("42LD Birthdays later than 1980 by Precinct",side=1,line=0)

with(Decade_RD_1980_42,(barchart(~count | as.factor(precinctid))));
mtext("42LD Registration Dates later than 1980 by Precinct",side=1,line=0)

Predefined type 'System.ValueTuple´2´ is not defined or imported

It's part of the .NET Framework 4.7.

As long as you don't target the above framework or higher (or .NET Core 2.0 / .NET Standard 2.0), you'll need to reference ValueTuple. Do this by adding the System.ValueTuple NuGet Package

Chrome / Safari not filling 100% height of flex parent

Solution

Use nested flex containers.

Get rid of percentage heights. Get rid of table properties. Get rid of vertical-align. Avoid absolute positioning. Just stick with flexbox all the way through.

Apply display: flex to the flex item (.item), making it a flex container. This automatically sets align-items: stretch, which tells the child (.item-inner) to expand the full height of the parent.

Important: Remove specified heights from flex items for this method to work. If a child has a height specified (e.g. height: 100%), then it will ignore the align-items: stretch coming from the parent. For the stretch default to work, the child's height must compute to auto (full explanation).

Try this (no changes to HTML):

_x000D_
_x000D_
.container {_x000D_
    display: flex;_x000D_
    flex-direction: column;_x000D_
    height: 20em;_x000D_
    border: 5px solid black_x000D_
}_x000D_
_x000D_
.item {_x000D_
    display: flex;                      /* new; nested flex container */_x000D_
    flex: 1;_x000D_
    border-bottom: 1px solid white;_x000D_
}_x000D_
_x000D_
.item-inner {_x000D_
    display: flex;                      /* new; nested flex container */_x000D_
    flex: 1;                            /* new */_x000D_
_x000D_
    /* height: 100%;                    <-- remove; unnecessary */_x000D_
    /* width: 100%;                     <-- remove; unnecessary */_x000D_
    /* display: table;                  <-- remove; unnecessary */  _x000D_
}_x000D_
_x000D_
a {_x000D_
    display: flex;                      /* new; nested flex container */_x000D_
    flex: 1;                            /* new */_x000D_
    align-items: center;                /* new; vertically center text */_x000D_
    background: orange;_x000D_
_x000D_
    /* display: table-cell;             <-- remove; unnecessary */_x000D_
    /* vertical-align: middle;          <-- remove; unnecessary */_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="item">_x000D_
    <div class="item-inner">_x000D_
      <a>Button</a>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <div class="item">_x000D_
    <div class="item-inner">_x000D_
      <a>Button</a>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <div class="item">_x000D_
    <div class="item-inner">_x000D_
      <a>Button</a>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

jsFiddle demo


Explanation

My problem is that .item-inner { height: 100% } is not working in webkit (Chrome).

It's not working because you're using percentage height in a way that doesn't conform with the traditional implementation of the spec.

10.5 Content height: the height property

percentage
Specifies a percentage height. The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly and this element is not absolutely positioned, the value computes to auto.

auto
The height depends on the values of other properties.

In other words, for percentage height to work on an in-flow child, the parent must have a set height.

In your code, the top-level container has a defined height: .container { height: 20em; }

The third-level container has a defined height: .item-inner { height: 100%; }

But between them, the second-level container – .itemdoes not have a defined height. Webkit sees that as a missing link.

.item-inner is telling Chrome: give me height: 100%. Chrome looks to the parent (.item) for reference and responds: 100% of what? I don't see anything (ignoring the flex: 1 rule that is there). As a result, it applies height: auto (content height), in accordance with the spec.

Firefox, on the other hand, now accepts a parent's flex height as a reference for the child's percentage height. IE11 and Edge accept flex heights, as well.

Also, Chrome will accept flex-grow as an adequate parent reference if used in conjunction with flex-basis (any numerical value works (auto won't), including flex-basis: 0). As of this writing, however, this solution fails in Safari.

_x000D_
_x000D_
#outer {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  height: 300px;_x000D_
  background-color: white;_x000D_
  border: 1px solid red;_x000D_
}_x000D_
#middle {_x000D_
  flex-grow: 1;_x000D_
  flex-basis: 1px;_x000D_
  background-color: yellow;_x000D_
}_x000D_
#inner {_x000D_
  height: 100%;_x000D_
  background-color: lightgreen;_x000D_
}
_x000D_
<div id="outer">_x000D_
  <div id="middle">_x000D_
    <div id="inner">_x000D_
      INNER_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Four Solutions

1. Specify a height on all parent elements

A reliable cross-browser solution is to specify a height on all parent elements. This prevents missing links, which Webkit-based browsers consider a violation of the spec.

Note that min-height and max-height are not acceptable. It must be the height property.

More details here: Working with the CSS height property and percentage values

2. CSS Relative & Absolute Positioning

Apply position: relative to the parent and position: absolute to the child.

Size the child with height: 100% and width: 100%, or use the offset properties: top: 0, right: 0, bottom: 0, left: 0.

With absolute positioning, percentage height works without a specified height on the parent.

3. Remove unnecessary HTML containers (recommended)

Is there a need for two containers around button? Why not remove .item or .item-inner, or both? Although button elements sometimes fail as flex containers, they can be flex items. Consider making button a child of .container or .item, and removing gratuitous mark-up.

Here's an example:

_x000D_
_x000D_
.container {_x000D_
    height: 20em;_x000D_
    display: flex;_x000D_
    flex-direction: column;_x000D_
    border: 5px solid black_x000D_
}_x000D_
_x000D_
a {_x000D_
    flex: 1;_x000D_
    background: orange;_x000D_
    border-bottom: 1px solid white;_x000D_
    display: flex;                   /* nested flex container (for aligning text) */_x000D_
    align-items: center;             /* center text vertically */_x000D_
    justify-content: center;         /* center text horizontally */_x000D_
}
_x000D_
<div class="container">_x000D_
    <a>Button</a>_x000D_
    <a>Button</a>_x000D_
    <a>Button</a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

4. Nested Flex Containers (recommended)

Get rid of percentage heights. Get rid of table properties. Get rid of vertical-align. Avoid absolute positioning. Just stick with flexbox all the way through.

Apply display: flex to the flex item (.item), making it a flex container. This automatically sets align-items: stretch, which tells the child (.item-inner) to expand the full height of the parent.

Important: Remove specified heights from flex items for this method to work. If a child has a height specified (e.g. height: 100%), then it will ignore the align-items: stretch coming from the parent. For the stretch default to work, the child's height must compute to auto (full explanation).

Try this (no changes to HTML):

_x000D_
_x000D_
.container {_x000D_
    display: flex;_x000D_
    flex-direction: column;_x000D_
    height: 20em;_x000D_
    border: 5px solid black_x000D_
}_x000D_
_x000D_
.item {_x000D_
    display: flex;                      /* new; nested flex container */_x000D_
    flex: 1;_x000D_
    border-bottom: 1px solid white;_x000D_
}_x000D_
_x000D_
.item-inner {_x000D_
    display: flex;                      /* new; nested flex container */_x000D_
    flex: 1;                            /* new */_x000D_
_x000D_
    /* height: 100%;                    <-- remove; unnecessary */_x000D_
    /* width: 100%;                     <-- remove; unnecessary */_x000D_
    /* display: table;                  <-- remove; unnecessary */  _x000D_
}_x000D_
_x000D_
a {_x000D_
    display: flex;                      /* new; nested flex container */_x000D_
    flex: 1;                            /* new */_x000D_
    align-items: center;                /* new; vertically center text */_x000D_
    background: orange;_x000D_
_x000D_
    /* display: table-cell;             <-- remove; unnecessary */_x000D_
    /* vertical-align: middle;          <-- remove; unnecessary */_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="item">_x000D_
    <div class="item-inner">_x000D_
      <a>Button</a>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <div class="item">_x000D_
    <div class="item-inner">_x000D_
      <a>Button</a>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <div class="item">_x000D_
    <div class="item-inner">_x000D_
      <a>Button</a>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

jsFiddle

Get exit code of a background process

I would change your approach slightly. Rather than checking every few seconds if the command is still alive and reporting a message, have another process that reports every few seconds that the command is still running and then kill that process when the command finishes. For example:

#!/bin/sh

cmd() { sleep 5; exit 24; }

cmd &   # Run the long running process
pid=$!  # Record the pid

# Spawn a process that coninually reports that the command is still running
while echo "$(date): $pid is still running"; do sleep 1; done &
echoer=$!

# Set a trap to kill the reporter when the process finishes
trap 'kill $echoer' 0

# Wait for the process to finish
if wait $pid; then
    echo "cmd succeeded"
else
    echo "cmd FAILED!! (returned $?)"
fi

Python Script Uploading files via FTP

Try this:

#!/usr/bin/env python

import os
import paramiko 
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('hostname', username="username", password="password")
sftp = ssh.open_sftp()
localpath = '/home/e100075/python/ss.txt'
remotepath = '/home/developers/screenshots/ss.txt'
sftp.put(localpath, remotepath)
sftp.close()
ssh.close()

How do I check CPU and Memory Usage in Java?

JConsole is an easy way to monitor a running Java application or you can use a Profiler to get more detailed information on your application. I like using the NetBeans Profiler for this.

In Java, what does NaN mean?

It literally means "Not a Number." I suspect something is wrong with your conversion process.

Check out the Not A Number section at this reference

RSA encryption and decryption in Python

In order to make it work you need to convert key from str to tuple before decryption(ast.literal_eval function). Here is fixed code:

import Crypto
from Crypto.PublicKey import RSA
from Crypto import Random
import ast

random_generator = Random.new().read
key = RSA.generate(1024, random_generator) #generate pub and priv key

publickey = key.publickey() # pub key export for exchange

encrypted = publickey.encrypt('encrypt this message', 32)
#message to encrypt is in the above line 'encrypt this message'

print 'encrypted message:', encrypted #ciphertext
f = open ('encryption.txt', 'w')
f.write(str(encrypted)) #write ciphertext to file
f.close()

#decrypted code below

f = open('encryption.txt', 'r')
message = f.read()


decrypted = key.decrypt(ast.literal_eval(str(encrypted)))

print 'decrypted', decrypted

f = open ('encryption.txt', 'w')
f.write(str(message))
f.write(str(decrypted))
f.close()

javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"Group")

You need to put package-info.java class in package of contextPath and put below code in same class:

@javax.xml.bind.annotation.XmlSchema(namespace = "https://www.namespaceUrl.com/xml/", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package com.test.valueobject;

Comparing chars in Java

pseudocode as I haven't got a java sdk on me:

Char candidates = new Char[] { 'A', 'B', ... 'G' };

foreach(Char c in candidates)
{
    if (symbol == c) { return true; }
}
return false;

Get dates from a week number in T-SQL

The most votes answer works fine except the 1st week and last week of year. When datecol value is '2009-01-01', the result will be 01/03/2009 and 12/28/2008.

My solution:

DECLARE @Date date = '2009-03-01', @WeekNum int, @StartDate date;
SELECT @WeekNum = DATEPART(WEEK, @Date);
SELECT @StartDate = DATEADD(DAY, -(DATEPART(WEEKDAY, DATEADD(YEAR, DATEDIFF(YEAR, 0, @Date), 0)) + 6), DATEADD(YEAR, DATEDIFF(YEAR, 0, @Date), 0));
SELECT CONVERT(nvarchar, CASE WHEN @WeekNum = 1 THEN CAST(DATEADD(YEAR, DATEDIFF(YEAR, 0, @Date), 0) AS date) ELSE DATEADD(DAY, 7 * @WeekNum, @StartDate) END, 101) AS StartOfWeek
      ,CONVERT(nvarchar, CASE WHEN @WeekNum = DATEPART(WEEK, DATEADD(DAY, -1, DATEADD(YEAR, DATEDIFF(YEAR, 0, @Date) + 1, 0))) THEN DATEADD(DAY, -1, DATEADD(YEAR, DATEDIFF(YEAR, 0, @Date) + 1, 0)) ELSE DATEADD(DAY, 7 * @WeekNum + 6, @StartDate) END, 101) AS EndOfWeek;

This will display 01/01/2009 and 01/03/2009 for the 1st week, and display 03/01/2009 and 03/07/2009 for the 10th week.

I think this would be what you want exactly. You can replace the variables with their expressions as you wish.

Builder Pattern in Effective Java

Make the builder a static class. Then it will work. If it is non-static, it would require an instance of its owning class - and the point is not to have an instance of it, and even to forbid making instances without the builder.

public class NutritionFacts {
    public static class Builder {
    }
}

Reference: Nested classes

undefined offset PHP error

Undefined offset means there's an empty array key for example:

$a = array('Felix','Jon','Java');

// This will result in an "Undefined offset" because the size of the array
// is three (3), thus, 0,1,2 without 3
echo $a[3];

You can solve the problem using a loop (while):

$i = 0;
while ($row = mysqli_fetch_assoc($result)) {
    // Increase count by 1, thus, $i=1
    $i++;

    $groupname[$i] = base64_decode(base64_decode($row['groupname']));

    // Set the first position of the array to null or empty
    $groupname[0] = "";
}

Custom style to jquery ui dialogs

You can specify a custom class to the top element of the dialog via the option dialogClass

$("#success").dialog({
    ...
    dialogClass:"myClass",
    ...
});

Then you can target this class in CSS via .myClass.ui-dialog.

Changing button color programmatically

I believe you want bgcolor. Something like this:

document.getElementById("button").bgcolor="#ffffff";

Here are a couple of demos that might help:

Background Color

Background Color Changer

Getting "cannot find Symbol" in Java project in Intellij

Thanks for the help so far, turns out the fix was to compile HUD.java first (right click on the file-> Compile HUD.java). After compiling the java file the rest of the project could be compiled without any problems.

I don't really know why this fixed it, or why IntelliJ wouldn't do this automatically, but root error seems it has to do with IntelliJ not correctly handling having multiple classes in a single .java file.

How do I get rid of the b-prefix in a string in python?

****How to remove b' ' chars which is decoded string in python ****

import base64
a='cm9vdA=='
b=base64.b64decode(a).decode('utf-8')
print(b)

How To Get Selected Value From UIPickerView

You can access the selected row for a given component using the following method:

- (NSInteger)selectedRowInComponent:(NSInteger)component

Otherwise, implementing the delegate function is the only other option.

How to access model hasMany Relation with where condition?

I think this is what you're looking for (Laravel 4, see http://laravel.com/docs/eloquent#querying-relations)

$games = Game::whereHas('video', function($q)
{
    $q->where('available','=', 1);

})->get();

Java: Check if enum contains a given string?

solution to check whether value is present as well get enum value in return :

protected TradeType getEnumType(String tradeType) {
    if (tradeType != null) {
        if (EnumUtils.isValidEnum(TradeType.class, tradeType)) {
            return TradeType.valueOf(tradeType);
        }
    }
    return null;
}

How do you handle a "cannot instantiate abstract class" error in C++?

If anyone is getting this error from a function, try using a reference to the abstract class in the parameters instead.

void something(Abstract bruh){
}

to

void something(Abstract& bruh){
}

Pass Hidden parameters using response.sendRedirect()

Using session, I successfully passed a parameter (name) from servlet #1 to servlet #2, using response.sendRedirect in servlet #1. Servlet #1 code:

protected void doPost(HttpServletRequest request, HttpServletResponse response) {
    String name = request.getParameter("name");
    String password = request.getParameter("password");
    ...
    request.getSession().setAttribute("name", name);
    response.sendRedirect("/todo.do");

In Servlet #2, you don't need to get name back. It's already connected to the session. You could do String name = (String) request.getSession().getAttribute("name"); ---but you don't need this.

If Servlet #2 calls a JSP, you can show name this way on the JSP webpage:

<h1>Welcome ${name}</h1>

How to Set Opacity (Alpha) for View in Android

For API < 11 for textView color I did the following:

int textViewColor = textView.getTextColors().getDefaultColor(); 
textView.setTextColor(Color.argb(128, Color.red(textViewColor), Color.green(textViewColor), Color.blue(textViewColor))); //50% transparent

A little cumbersome, but hey, it works :-)

tsql returning a table from a function or store procedure

You need a special type of function known as a table valued function. Below is a somewhat long-winded example that builds a date dimension for a data warehouse. Note the returns clause that defines a table structure. You can insert anything into the table variable (@DateHierarchy in this case) that you want, including building a temporary table and copying the contents into it.

if object_id ('ods.uf_DateHierarchy') is not null
    drop function ods.uf_DateHierarchy
go

create function ods.uf_DateHierarchy (
       @DateFrom datetime
      ,@DateTo   datetime
) returns @DateHierarchy table (
        DateKey           datetime
       ,DisplayDate       varchar (20)
       ,SemanticDate      datetime
       ,MonthKey          int     
       ,DisplayMonth      varchar (10)
       ,FirstDayOfMonth   datetime
       ,QuarterKey        int
       ,DisplayQuarter    varchar (10)
       ,FirstDayOfQuarter datetime
       ,YearKey           int
       ,DisplayYear       varchar (10)
       ,FirstDayOfYear    datetime
) as begin
    declare @year            int
           ,@quarter         int
           ,@month           int
           ,@day             int
           ,@m1ofqtr         int
           ,@DisplayDate     varchar (20)
           ,@DisplayQuarter  varchar (10)
           ,@DisplayMonth    varchar (10)
           ,@DisplayYear     varchar (10)
           ,@today           datetime
           ,@MonthKey        int
           ,@QuarterKey      int
           ,@YearKey         int
           ,@SemanticDate    datetime
           ,@FirstOfMonth    datetime
           ,@FirstOfQuarter  datetime
           ,@FirstOfYear     datetime
           ,@MStr            varchar (2)
           ,@QStr            varchar (2)
           ,@Ystr            varchar (4)
           ,@DStr            varchar (2)
           ,@DateStr         varchar (10)


    -- === Previous ===================================================
    -- Special placeholder date of 1/1/1800 used to denote 'previous'
    -- so that naive date calculations sort and compare in a sensible
    -- order.
    --
    insert @DateHierarchy (
         DateKey
        ,DisplayDate
        ,SemanticDate
        ,MonthKey
        ,DisplayMonth
        ,FirstDayOfMonth
        ,QuarterKey
        ,DisplayQuarter
        ,FirstDayOfQuarter
        ,YearKey
        ,DisplayYear
        ,FirstDayOfYear
    ) values (
         '1800-01-01'
        ,'Previous'
        ,'1800-01-01'
        ,180001
        ,'Prev'
        ,'1800-01-01'
        ,18001
        ,'Prev'
        ,'1800-01-01'
        ,1800
        ,'Prev'
        ,'1800-01-01'
    )

    -- === Calendar Dates =============================================
    -- These are generated from the date range specified in the input
    -- parameters.
    --
    set @today = @Datefrom
    while @today <= @DateTo begin

        set @year = datepart (yyyy, @today)
        set @month = datepart (mm, @today)
        set @day = datepart (dd, @today)
        set @quarter = case when @month in (1,2,3) then 1
                            when @month in (4,5,6) then 2
                            when @month in (7,8,9) then 3
                            when @month in (10,11,12) then 4
                        end
        set @m1ofqtr = @quarter * 3 - 2 

        set @DisplayDate = left (convert (varchar, @today, 113), 11)
        set @SemanticDate = @today
        set @MonthKey = @year * 100 + @month
        set @DisplayMonth = substring (convert (varchar, @today, 113), 4, 8)
        set @Mstr = right ('0' + convert (varchar, @month), 2)
        set @Dstr = right ('0' + convert (varchar, @day), 2)
        set @Ystr = convert (varchar, @year)
        set @DateStr = @Ystr + '-' + @Mstr + '-01'
        set @FirstOfMonth = convert (datetime, @DateStr, 120)
        set @QuarterKey = @year * 10 + @quarter
        set @DisplayQuarter = 'Q' + convert (varchar, @quarter) + ' ' +
                                    convert (varchar, @year)
        set @QStr = right ('0' + convert (varchar, @m1ofqtr), 2)   
        set @DateStr = @Ystr + '-' + @Qstr + '-01' 
        set @FirstOfQuarter = convert (datetime, @DateStr, 120)
        set @YearKey = @year
        set @DisplayYear = convert (varchar, @year)
        set @DateStr = @Ystr + '-01-01'
        set @FirstOfYear = convert (datetime, @DateStr)


        insert @DateHierarchy (
             DateKey
            ,DisplayDate
            ,SemanticDate
            ,MonthKey
            ,DisplayMonth
            ,FirstDayOfMonth
            ,QuarterKey
            ,DisplayQuarter
            ,FirstDayOfQuarter
            ,YearKey
            ,DisplayYear
            ,FirstDayOfYear
        ) values (
             @today
            ,@DisplayDate
            ,@SemanticDate
            ,@Monthkey
            ,@DisplayMonth
            ,@FirstOfMonth
            ,@QuarterKey
            ,@DisplayQuarter
            ,@FirstOfQuarter
            ,@YearKey
            ,@DisplayYear
            ,@FirstOfYear
        )

        set @today = dateadd (dd, 1, @today)
    end

    -- === Specials ===================================================
    -- 'Ongoing', 'Error' and 'Not Recorded' set two years apart to
    -- avoid accidental collisions on 'Next Year' calculations.
    --
    insert @DateHierarchy (
         DateKey
        ,DisplayDate
        ,SemanticDate
        ,MonthKey
        ,DisplayMonth
        ,FirstDayOfMonth
        ,QuarterKey
        ,DisplayQuarter
        ,FirstDayOfQuarter
        ,YearKey
        ,DisplayYear
        ,FirstDayOfYear
    ) values (
         '9000-01-01'
        ,'Ongoing'
        ,'9000-01-01'
        ,900001
        ,'Ong.'
        ,'9000-01-01'
        ,90001
        ,'Ong.'
        ,'9000-01-01'
        ,9000
        ,'Ong.'
        ,'9000-01-01'
    )

    insert @DateHierarchy (
         DateKey
        ,DisplayDate
        ,SemanticDate
        ,MonthKey
        ,DisplayMonth
        ,FirstDayOfMonth
        ,QuarterKey
        ,DisplayQuarter
        ,FirstDayOfQuarter
        ,YearKey
        ,DisplayYear
        ,FirstDayOfYear
    ) values (
         '9100-01-01'
        ,'Error'
        ,null
        ,910001
        ,'Error'
        ,null
        ,91001
        ,'Error'
        ,null
        ,9100
        ,'Err'
        ,null
    )

    insert @DateHierarchy (
         DateKey
        ,DisplayDate
        ,SemanticDate
        ,MonthKey
        ,DisplayMonth
        ,FirstDayOfMonth
        ,QuarterKey
        ,DisplayQuarter
        ,FirstDayOfQuarter
        ,YearKey
        ,DisplayYear
        ,FirstDayOfYear
    ) values (
         '9200-01-01'
        ,'Not Recorded'
        ,null
        ,920001
        ,'N/R'
        ,null
        ,92001
        ,'N/R'
        ,null
        ,9200
        ,'N/R'
        ,null
    )

    return
end

go

Difference between <input type='submit' /> and <button type='submit'>text</button>

With <button>, you can use img tags, etc. where text is

<button type='submit'> text -- can be img etc.  </button>

with <input> type, you are limited to text

socket.emit() vs. socket.send()

socket.send is implemented for compatibility with vanilla WebSocket interface. socket.emit is feature of Socket.IO only. They both do the same, but socket.emit is a bit more convenient in handling messages.

Installing PIL (Python Imaging Library) in Win7 64 bits, Python 2.6.4

I was having the same problem so I decided to download the source kit and install it according to how you posted above...

  1. Downloaded Source Kit
  2. Opened command prompt on that folder and typed python setup.py build
  3. Then I typed python setup.py install

It worked perfectly!

Now, some notes: when I typed python setup.py build, I saw that Microsoft Visual Studio v9.0 C compiler was being used to build everything.

So probably it's something with your compiler not correctly configured or something...

Anyways, that worked with me so thank you!

How to read all rows from huge table?

I did it like below. Not the best way i think, but it works :)

    Connection c = DriverManager.getConnection("jdbc:postgresql://....");
    PreparedStatement s = c.prepareStatement("select * from " + tabName + " where id > ? order by id");
    s.setMaxRows(100);
    int lastId = 0;
    for (;;) {
        s.setInt(1, lastId);
        ResultSet rs = s.executeQuery();

        int lastIdBefore = lastId;
        while (rs.next()) {
            lastId = Integer.parseInt(rs.getObject(1).toString());
            // ...
        }

        if (lastIdBefore == lastId) {
            break;
        }
    }

what is the most efficient way of counting occurrences in pandas?

I think df['word'].value_counts() should serve. By skipping the groupby machinery, you'll save some time. I'm not sure why count should be much slower than max. Both take some time to avoid missing values. (Compare with size.)

In any case, value_counts has been specifically optimized to handle object type, like your words, so I doubt you'll do much better than that.

Importing Excel spreadsheet data into another Excel spreadsheet containing VBA

This should get you started: Using VBA in your own Excel workbook, have it prompt the user for the filename of their data file, then just copy that fixed range into your target workbook (that could be either the same workbook as your macro enabled one, or a third workbook). Here's a quick vba example of how that works:

' Get customer workbook...
Dim customerBook As Workbook
Dim filter As String
Dim caption As String
Dim customerFilename As String
Dim customerWorkbook As Workbook
Dim targetWorkbook As Workbook

' make weak assumption that active workbook is the target
Set targetWorkbook = Application.ActiveWorkbook

' get the customer workbook
filter = "Text files (*.xlsx),*.xlsx"
caption = "Please Select an input file "
customerFilename = Application.GetOpenFilename(filter, , caption)

Set customerWorkbook = Application.Workbooks.Open(customerFilename)

' assume range is A1 - C10 in sheet1
' copy data from customer to target workbook
Dim targetSheet As Worksheet
Set targetSheet = targetWorkbook.Worksheets(1)
Dim sourceSheet As Worksheet
Set sourceSheet = customerWorkbook.Worksheets(1)

targetSheet.Range("A1", "C10").Value = sourceSheet.Range("A1", "C10").Value

' Close customer workbook
customerWorkbook.Close

Java 8 stream map to list of keys sorted by values

You can use this as an example of your problem

    Map<Integer, String> map = new HashMap<>();
    map.put(10, "apple");
    map.put(20, "orange");
    map.put(30, "banana");
    map.put(40, "watermelon");
    map.put(50, "dragonfruit");

    // split a map into 2 List
    List<Integer> resultSortedKey = new ArrayList<>();
    List<String> resultValues = map.entrySet().stream()
            //sort a Map by key and stored in resultSortedKey
            .sorted(Map.Entry.<Integer, String>comparingByKey().reversed())
            .peek(e -> resultSortedKey.add(e.getKey()))
            .map(x -> x.getValue())
            // filter banana and return it to resultValues
            .filter(x -> !"banana".equalsIgnoreCase(x))
            .collect(Collectors.toList());

    resultSortedKey.forEach(System.out::println);
    resultValues.forEach(System.out::println);

Java Enum Methods - return opposite direction enum

For a small enum like this, I find the most readable solution to be:

public enum Direction {

    NORTH {
        @Override
        public Direction getOppositeDirection() {
            return SOUTH;
        }
    }, 
    SOUTH {
        @Override
        public Direction getOppositeDirection() {
            return NORTH;
        }
    },
    EAST {
        @Override
        public Direction getOppositeDirection() {
            return WEST;
        }
    },
    WEST {
        @Override
        public Direction getOppositeDirection() {
            return EAST;
        }
    };


    public abstract Direction getOppositeDirection();

}

Random word generator- Python

Solution for Python 3

For Python3 the following code grabs the word list from the web and returns a list. Answer based on accepted answer above by Kyle Kelley.

import urllib.request

word_url = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain"
response = urllib.request.urlopen(word_url)
long_txt = response.read().decode()
words = long_txt.splitlines()

Output:

>>> words
['a', 'AAA', 'AAAS', 'aardvark', 'Aarhus', 'Aaron', 'ABA', 'Ababa',
 'aback', 'abacus', 'abalone', 'abandon', 'abase', 'abash', 'abate',
 'abbas', 'abbe', 'abbey', 'abbot', 'Abbott', 'abbreviate', ... ]

And to generate (because it was my objective) a list of 1) upper case only words, 2) only "name like" words, and 3) a sort-of-realistic-but-fun sounding random name:

import random
upper_words = [word for word in words if word[0].isupper()]
name_words  = [word for word in upper_words if not word.isupper()]
rand_name   = ' '.join([name_words[random.randint(0, len(name_words))] for i in range(2)])

And some random names:

>>> for n in range(10):
        ' '.join([name_words[random.randint(0,len(name_words))] for i in range(2)])

    'Semiramis Sicilian'
    'Julius Genevieve'
    'Rwanda Cohn'
    'Quito Sutherland'
    'Eocene Wheller'
    'Olav Jove'
    'Weldon Pappas'
    'Vienna Leyden'
    'Io Dave'
    'Schwartz Stromberg'

Base64: java.lang.IllegalArgumentException: Illegal character

Just use the below code to resolve this:

JsonObject obj = Json.createReader(new ByteArrayInputStream(Base64.getDecoder().decode(accessToken.split("\\.")[1].
                        replace('-', '+').replace('_', '/')))).readObject();

In the above code replace('-', '+').replace('_', '/') did the job. For more details see the https://jwt.io/js/jwt.js. I understood the problem from the part of the code got from that link:

function url_base64_decode(str) {
  var output = str.replace(/-/g, '+').replace(/_/g, '/');
  switch (output.length % 4) {
    case 0:
      break;
    case 2:
      output += '==';
      break;
    case 3:
      output += '=';
      break;
    default:
      throw 'Illegal base64url string!';
  }
  var result = window.atob(output); //polifyll https://github.com/davidchambers/Base64.js
  try{
    return decodeURIComponent(escape(result));
  } catch (err) {
    return result;
  }
}

Variable declaration in a header file

If you declare it like

int x;

in a header file which is then included in multiple places, you'll end up with multiple instances of x (and potentially compile or link problems).

The correct way to approach this is to have the header file say

extern int x; /* declared in foo.c */

and then in foo.c you can say

int x; /* exported in foo.h */

THen you can include your header file in as many places as you like.

SHOW PROCESSLIST in MySQL command: sleep

Sleep meaning that thread is do nothing. Time is too large beacuse anthor thread query,but not disconnect server, default wait_timeout=28800;so you can set values smaller,eg 10. also you can kill the thread.

How do I compare if a string is not equal to?

Either != or ne will work, but you need to get the accessor syntax and nested quotes sorted out.

<c:if test="${content.contentType.name ne 'MCE'}">
    <%-- snip --%>
</c:if>

TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader

I think it has to do with your second element in storbinary. You are trying to open file, but it is already a pointer to the file you opened in line file = open(local_path,'rb'). So, try to use ftp.storbinary("STOR " + i, file).

if arguments is equal to this string, define a variable like this string

It seems that you are looking to parse commandline arguments into your bash script. I have searched for this recently myself. I came across the following which I think will assist you in parsing the arguments:

http://rsalveti.wordpress.com/2007/04/03/bash-parsing-arguments-with-getopts/

I added the snippet below as a tl;dr

#using : after a switch variable means it requires some input (ie, t: requires something after t to validate while h requires nothing.
while getopts “ht:r:p:v” OPTION
do
     case $OPTION in
         h)
             usage
             exit 1
             ;;
         t)
             TEST=$OPTARG
             ;;
         r)
             SERVER=$OPTARG
             ;;
         p)
             PASSWD=$OPTARG
             ;;
         v)
             VERBOSE=1
             ;;
         ?)
             usage
             exit
             ;;
     esac
done

if [[ -z $TEST ]] || [[ -z $SERVER ]] || [[ -z $PASSWD ]]
then
     usage
     exit 1
fi

./script.sh -t test -r server -p password -v

What is the largest possible heap size with a 64-bit JVM?

For a 64-bit JVM running in a 64-bit OS on a 64-bit machine, is there any limit besides the theoretical limit of 2^64 bytes or 16 exabytes?

You also have to take hardware limits into account. While pointers may be 64bit current CPUs can only address a less than 2^64 bytes worth of virtual memory.

With uncompressed pointers the hotspot JVM needs a continuous chunk of virtual address space for its heap. So the second hurdle after hardware is the operating system providing such a large chunk, not all OSes support this.

And the third one is practicality. Even if you can have that much virtual memory it does not mean the CPUs support that much physical memory, and without physical memory you will end up swapping, which will adversely affect the performance of the JVM because the GCs generally have to touch a large fraction of the heap.

As other answers mention compressed oops: By bumping the object alignment higher than 8 bytes the limits with compressed oops can be increased beyond 32GB

Enable remote connections for SQL Server Express 2012

I prefer way of "Rosdi Kasim" as that's doesn't require detail configuration on the IP.

I will definitely forget it again when I try to up another server again.

Keep It Simple Stupid (KISS) by simply enable the Sql Server Browser service, then add the \SQLEXPRESS behind the IP when you connect the server.

Direct using IP without "\SQLEXPRESS" was my point of failure as it doesn't use the default port.

Thanks.

Android add placeholder text to EditText

In Android Studio you can add Hint (Place holder) through GUI. First select EditText field on designer view. Then Click on Component Tree Left side of IDE (Normally it's there, but it may be there minimized) There you can see Properties of selected EditText. Find Hint field as below Image

enter image description here

There you can add Hint(Place holder) to EditText

What is the Simplest Way to Reverse an ArrayList?

Not the simplest way but if you're a fan of recursion you might be interested in the following method to reverse an ArrayList:

public ArrayList<Object> reverse(ArrayList<Object> list) {
    if(list.size() > 1) {                   
        Object value = list.remove(0);
        reverse(list);
        list.add(value);
    }
    return list;
}

Or non-recursively:

public ArrayList<Object> reverse(ArrayList<Object> list) {
    for(int i = 0, j = list.size() - 1; i < j; i++) {
        list.add(i, list.remove(j));
    }
    return list;
}

How do I detect if I am in release or debug mode?

Yes, you will have no problems using:

if (BuildConfig.DEBUG) {
   //It's not a release version.
}

Unless you are importing the wrong BuildConfig class. Make sure you are referencing your project's BuildConfig class, not from any of your dependency libraries.

enter image description here

Apache Proxy: No protocol handler was valid

For me all above-mentioned answers was enabled on xampp still not working. Enabling below module made virtual host work again

LoadModule slotmem_shm_module modules/mod_slotmem_shm.so

How to get the id of the element clicked using jQuery

update as you loading contents dynamically so you use.

$(document).on('click', 'span', function () {
    alert(this.id);
});

old code

$('span').click(function(){
    alert(this.id);
});

or you can use .on

$('span').on('click', function () {
    alert(this.id);
});

this refers to current span element clicked

this.id will give the id of the current span clicked

int to unsigned int conversion

with a little help of math

#include <math.h>
int main(){
  int a = -1;
  unsigned int b;
  b = abs(a);
}

Reordering Chart Data Series

To change the stacking order for series in charts under Excel for Mac 2011:

  1. select the chart,
  2. select the series (easiest under Ribbon>Chart Layout>Current Selection),
  3. click Chart Layout>Format Selection or Menu>Format>Data Series …,
  4. on popup menu Format Data Series click Order, then click individual series and click Move Up or Move Down buttons to adjust the stacking order on the Axis for the subject series. This changes the order for the plot and for the legend, but may not change the order number in the Series formula.

I had a three series plot on the secondary axis, and the series I wanted on top was stuck on the bottom in defiance of the Move Up and Move Down buttons. It happened to be formatted as markers only. I inserted a line, and presto(!), I could change its order in the plot. Later I could remove the line and sometimes it could still be ordered, but sometimes not.

Xcode is not currently available from the Software Update server

I solved this by going to the App Store and installing Xcode.

It was a pretty large 11GB install, so this is probably overkill. But, as a last resort, it seems to have solve my issues. In the middle of the installation (well around 10GB), Mac OS told me there was an update to Command Line Tools for Xcode. Performing this installation won't fix anything until Xcode is fully installed.

Once the install is done, it should start working (after you accept the license agreement).

How to resolve git stash conflict without commit?

According to git stash questions, after fixing the conflict, git add <file> is the right course of action.

It was after reading this comment that I understood that the changes are automatically added to the index (by design). That's why git add <file> completes the conflict resolution process.

What is token-based authentication?

I think it's well explained here -- quoting just the key sentences of the long article:

The general concept behind a token-based authentication system is simple. Allow users to enter their username and password in order to obtain a token which allows them to fetch a specific resource - without using their username and password. Once their token has been obtained, the user can offer the token - which offers access to a specific resource for a time period - to the remote site.

In other words: add one level of indirection for authentication -- instead of having to authenticate with username and password for each protected resource, the user authenticates that way once (within a session of limited duration), obtains a time-limited token in return, and uses that token for further authentication during the session.

Advantages are many -- e.g., the user could pass the token, once they've obtained it, on to some other automated system which they're willing to trust for a limited time and a limited set of resources, but would not be willing to trust with their username and password (i.e., with every resource they're allowed to access, forevermore or at least until they change their password).

If anything is still unclear, please edit your question to clarify WHAT isn't 100% clear to you, and I'm sure we can help you further.

How to export MySQL database with triggers and procedures?

May be it's obvious for expert users of MYSQL but I wasted some time while trying to figure out default value would not export functions. So I thought to mention here that --routines param needs to be set to true to make it work.

mysqldump --routines=true -u <user> my_database > my_database.sql

Error 6 (net::ERR_FILE_NOT_FOUND): The files c or directory could not be found

The below are the typical situation where we shall get ERR_FILE_NOT_FOUND even file avail in respective folder.

Code:
@font-face {
    font-family: Eau_Sans_Bold;
    src: url("/fonts/eau_sans_bold.otf") format("opentype");
}
Error:
 GET file:///C:/fonts/eau_sans_bold.otf net::ERR_FILE_NOT_FOUND

Answer or Solution.:
@font-face {
    font-family: Eau_Sans_Book;
    src: url("../fonts/eau_sans_book.otf") format("opentype");  
}

Basically browser not able to pick if we metion just /font/. We should to mention ../fonts/ This will work. So, we wont get ERR_FILE_NOT_FOUND.

jQuery & CSS - Remove/Add display:none

jQuery's .show() and .hide() functions are probably your best bet.

How to exclude subdirectories in the destination while using /mir /xd switch in robocopy

When i tried the solution with /XD i found, that the path to exclude should be the source path - not the destination.

e.g. this Works

robocopy c:\test\a c:\test\b /MIR /XD c:\test\a\leavethisdiralone\

GitHub: invalid username or password

I'm constantly running into this problem. Make sure you set git --config user.name "" and not your real name, which I've done a few times..

Python: Get the first character of the first string in a list?

Get the first character of a bare python string:

>>> mystring = "hello"
>>> print(mystring[0])
h
>>> print(mystring[:1])
h
>>> print(mystring[3])
l
>>> print(mystring[-1])
o
>>> print(mystring[2:3])
l
>>> print(mystring[2:4])
ll

Get the first character from a string in the first position of a python list:

>>> myarray = []
>>> myarray.append("blah")
>>> myarray[0][:1]
'b'
>>> myarray[0][-1]
'h'
>>> myarray[0][1:3]
'la'

Many people get tripped up here because they are mixing up operators of Python list objects and operators of Numpy ndarray objects:

Numpy operations are very different than python list operations.

Wrap your head around the two conflicting worlds of Python's "list slicing, indexing, subsetting" and then Numpy's "masking, slicing, subsetting, indexing, then numpy's enhanced fancy indexing".

These two videos cleared things up for me:

"Losing your Loops, Fast Numerical Computing with NumPy" by PyCon 2015: https://youtu.be/EEUXKG97YRw?t=22m22s

"NumPy Beginner | SciPy 2016 Tutorial" by Alexandre Chabot LeClerc: https://youtu.be/gtejJ3RCddE?t=1h24m54s

How do I find out if first character of a string is a number?

Character.isDigit(string.charAt(0))

Note that this will allow any Unicode digit, not just 0-9. You might prefer:

char c = string.charAt(0);
isDigit = (c >= '0' && c <= '9');

Or the slower regex solutions:

s.substring(0, 1).matches("\\d")
// or the equivalent
s.substring(0, 1).matches("[0-9]")

However, with any of these methods, you must first be sure that the string isn't empty. If it is, charAt(0) and substring(0, 1) will throw a StringIndexOutOfBoundsException. startsWith does not have this problem.

To make the entire condition one line and avoid length checks, you can alter the regexes to the following:

s.matches("\\d.*")
// or the equivalent
s.matches("[0-9].*")

If the condition does not appear in a tight loop in your program, the small performance hit for using regular expressions is not likely to be noticeable.

Display Adobe pdf inside a div

You cannot, and here is the simple answer.

Every media asset poured into the browser is identified by a mime type name. A browser then makes processing determinations upon that mime type name. If it is image/gif or image/jpeg the browser processes the asset as an image. If it is text/css or text/javascript it is processed as a code asset unless the asset is addressed independent of HTML. PDF is identified as application/pdf. When browsers see application/pdf they immediately switch processing to a plugin software capable of processing that media type. If you attempt to push media of type application/pdf into a div the browser will likely throw an error to the user. Typically files of type application/pdf are linked to directly so that the processing software an intercept the request and process the media independent of the browser.

Firebase FCM notifications click_action payload

there is dual method for fcm fcm messaging notification and app notification in first your app reciever only message notification with body ,title and you can add color ,vibration not working,sound default. in 2nd you can full control what happen when you recieve message example onMessageReciever(RemoteMessage rMessage){ notification.setContentTitle(rMessage.getData().get("yourKey")); } you will recieve data with(yourKey) but that not from fcm message that from fcm cloud functions reguard

Send private messages to friends

This is not possible now, but there is a work around. You can engage with the user in the public realm and ask them to send you private messages, but you can't send private messages back, only public ones. Of course, this all depends on if the user gives you the correct permissions.

If you have given permission to access a person's friends, you can then theoretically post on that users wall with references to each one of the friends, asking them to publicly interact with you and then potentially privately message you.

Get Friends

#if authenticated
https://graph.facebook.com/me/friends
http://developers.facebook.com/docs/reference/api/user/

Post in the Public Domain

http://developers.facebook.com/docs/reference/api/status/

Get Messages sent to that user (if given permission)

http://developers.facebook.com/docs/reference/api/message/

gcc: undefined reference to

However, avpicture_get_size is defined.

No, as the header (<libavcodec/avcodec.h>) just declares it.

The definition is in the library itself.

So you might like to add the linker option to link libavcodec when invoking gcc:

-lavcodec

Please also note that libraries need to be specified on the command line after the files needing them:

gcc -I$HOME/ffmpeg/include program.c -lavcodec

Not like this:

gcc -lavcodec -I$HOME/ffmpeg/include program.c

Referring to Wyzard's comment, the complete command might look like this:

gcc -I$HOME/ffmpeg/include program.c -L$HOME/ffmpeg/lib -lavcodec

For libraries not stored in the linkers standard location the option -L specifies an additional search path to lookup libraries specified using the -l option, that is libavcodec.x.y.z in this case.


For a detailed reference on GCC's linker option, please read here.

How to pass parameters to a modal?

I tried as below.

I called ng-click to angularjs controller on Encourage button,

               <tr ng-cloak
                  ng-repeat="user in result.users">
                   <td>{{user.userName}}</rd>
                   <td>
                      <a class="btn btn-primary span11" ng-click="setUsername({{user.userName}})" href="#encouragementModal" data-toggle="modal">
                            Encourage
                       </a>
                  </td>
                </tr>

I set userName of encouragementModal from angularjs controller.

    /**
     * Encouragement controller for AngularJS
     * 
     * @param $scope
     * @param $http
     * @param encouragementService
     */
    function EncouragementController($scope, $http, encouragementService) {
      /**
       * set invoice number
       */
      $scope.setUsername = function (username) {
            $scope.userName = username;
      };
     }
    EncouragementController.$inject = [ '$scope', '$http', 'encouragementService' ];

I provided a place(userName) to get value from angularjs controller on encouragementModal.

<div id="encouragementModal" class="modal hide fade">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal"
      aria-hidden="true">&times;</button>
    <h3>Confirm encouragement?</h3>
  </div>
  <div class="modal-body">
      Do you really want to encourage <b>{{userName}}</b>?
  </div>
  <div class="modal-footer">
    <button class="btn btn-info"
      ng-click="encourage('${createLink(uri: '/encourage/')}',{{userName}})">
      Confirm
    </button>
    <button class="btn" data-dismiss="modal" aria-hidden="true">Never Mind</button>
  </div>
</div>

It worked and I saluted myself.

How to delete a specific file from folder using asp.net

string sourceDir = @"c:\current";
string backupDir = @"c:\archives\2008";

try
{
    string[] picList = Directory.GetFiles(sourceDir, "*.jpg");
    string[] txtList = Directory.GetFiles(sourceDir, "*.txt");

    // Copy picture files. 
    foreach (string f in picList)
    {
        // Remove path from the file name. 
        string fName = f.Substring(sourceDir.Length + 1);

        // Use the Path.Combine method to safely append the file name to the path. 
        // Will overwrite if the destination file already exists.
        File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), true);
    }

    // Copy text files. 
    foreach (string f in txtList)
    {

        // Remove path from the file name. 
        string fName = f.Substring(sourceDir.Length + 1);

        try
        {
            // Will not overwrite if the destination file already exists.
            File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName));
        }

        // Catch exception if the file was already copied. 
        catch (IOException copyError)
        {
            Console.WriteLine(copyError.Message);
        }
    }

    // Delete source files that were copied. 
    foreach (string f in txtList)
    {
        File.Delete(f);
    }
    foreach (string f in picList)
    {
        File.Delete(f);
    }
}

catch (DirectoryNotFoundException dirNotFound)
{
    Console.WriteLine(dirNotFound.Message);
}

How do I create directory if it doesn't exist to create a file?

To Create

(new FileInfo(filePath)).Directory.Create() Before writing to the file.

....Or, If it exists, then create (else do nothing)

System.IO.FileInfo file = new System.IO.FileInfo(filePath);
file.Directory.Create(); // If the directory already exists, this method does nothing.
System.IO.File.WriteAllText(file.FullName, content);

How is the default submit button on an HTML form determined?

EDIT: Sorry, when writing this answer I was thinking about submit buttons in the general sense. The answer below is not about multiple type="submit" buttons, as it leaves only one type="submit" and change the other to type="button". I leave the answer here as reference in case helps someone that can change the type in their form:

To determine what button is pressed when hitting enter, you can mark it up with type="submit", and the other buttons mark them with type="button". For example:

<input type="button" value="Cancel" />
<input type="submit" value="Submit" />

How do I pull my project from github?

Run these commands:

cd /pathToYourLocalProjectFolder

git pull origin master

Transparent color of Bootstrap-3 Navbar

you can use this for your css , mainly use css3 rgba as your background in order to control the opacity and use a background fallback for older browser , either using a solid color or a transparent .png image.

.navbar {
   background:rgba(0,0,0,0.5);   /* for latest browsers */
   background: #000;  /* fallback for older browsers */
}

More info: http://css-tricks.com/rgba-browser-support/

SQL Server Convert Varchar to Datetime

You can have all the different styles to datetime conversion :

https://www.w3schools.com/sql/func_sqlserver_convert.asp

This has range of values :-

CONVERT(data_type(length),expression,style)

For style values,
Choose anyone you need like I needed 106.

How get an apostrophe in a string in javascript

You can try the following:

theAnchorText = "I'm home";

OR

theAnchorText = 'I\'m home';

Fill an array with random numbers

You need to add logic to assign random values to double[] array using randomFill method.

Change

 public static double[] list(){
    anArray = new double[10];   
    return anArray;
 }

To

 public static double[] list() {
    anArray = new double[10];
    for(int i=0;i<anArray.length;i++)
    {
        anArray[i] = randomFill();
    }
    return anArray;
}

Then you can call methods, including list() and print() in main method to generate random double values and print the double[] array in console.

 public static void main(String args[]) {

list();
print();
 }

One result is as follows:

-2.89783865E8 
1.605018025E9 
-1.55668528E9 
-1.589135498E9 
-6.33159518E8 
-1.038278095E9 
-4.2632203E8 
1.310182951E9 
1.350639892E9 
6.7543543E7 

PostgreSQL JOIN data from 3 tables

Something like:

select t1.name, t2.image_id, t3.path
from table1 t1 inner join table2 t2 on t1.person_id = t2.person_id
inner join table3 t3 on t2.image_id=t3.image_id