Programs & Examples On #Xact

How can I convert this one line of ActionScript to C#?

There is collection of Func<...> classes - Func that is probably what you are looking for:

 void MyMethod(Func<int> param1 = null) 

This defines method that have parameter param1 with default value null (similar to AS), and a function that returns int. Unlike AS in C# you need to specify type of the function's arguments.

So if you AS usage was

MyMethod(function(intArg, stringArg) { return true; }) 

Than in C# it would require param1 to be of type Func<int, siring, bool> and usage like

MyMethod( (intArg, stringArg) => { return true;} ); 

Difference between opening a file in binary vs text

The most important difference to be aware of is that with a stream opened in text mode you get newline translation on non-*nix systems (it's also used for network communications, but this isn't supported by the standard library). In *nix newline is just ASCII linefeed, \n, both for internal and external representation of text. In Windows the external representation often uses a carriage return + linefeed pair, "CRLF" (ASCII codes 13 and 10), which is converted to a single \n on input, and conversely on output.


From the C99 standard (the N869 draft document), §7.19.2/2,

A text stream is an ordered sequence of characters composed into lines, each line consisting of zero or more characters plus a terminating new-line character. Whether the last line requires a terminating new-line character is implementation-defined. Characters may have to be added, altered, or deleted on input and output to conform to differing conventions for representing text in the host environment. Thus, there need not be a one- to-one correspondence between the characters in a stream and those in the external representation. Data read in from a text stream will necessarily compare equal to the data that were earlier written out to that stream only if: the data consist only of printing characters and the control characters horizontal tab and new-line; no new-line character is immediately preceded by space characters; and the last character is a new-line character. Whether space characters that are written out immediately before a new-line character appear when read in is implementation-defined.

And in §7.19.3/2

Binary files are not truncated, except as defined in 7.19.5.3. Whether a write on a text stream causes the associated file to be truncated beyond that point is implementation- defined.

About use of fseek, in §7.19.9.2/4:

For a text stream, either offset shall be zero, or offset shall be a value returned by an earlier successful call to the ftell function on a stream associated with the same file and whence shall be SEEK_SET.

About use of ftell, in §17.19.9.4:

The ftell function obtains the current value of the file position indicator for the stream pointed to by stream. For a binary stream, the value is the number of characters from the beginning of the file. For a text stream, its file position indicator contains unspecified information, usable by the fseek function for returning the file position indicator for the stream to its position at the time of the ftell call; the difference between two such return values is not necessarily a meaningful measure of the number of characters written or read.

I think that’s the most important, but there are some more details.

What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

I got the same issue (asp, c# - HttpPostedFileBase) when posting a file that was larger than 1MB (even though application doesn't have any limitation for file size), for me the simplification of model class helped. If you got this issue, try to remove some parts of the model, and see if it will help in any way. Sounds strange, but worked for me.

OpenCV TypeError: Expected cv::UMat for argument 'src' - What is this?

gray = cv2.cvtColor(cv2.UMat(imgUMat), cv2.COLOR_RGB2GRAY)

UMat is a part of the Transparent API (TAPI) than help to write one code for the CPU and OpenCL implementations.

WARNING in budgets, maximum exceeded for initial

Open angular.json file and find budgets keyword.

It should look like:

    "budgets": [
       {
          "type": "initial",
          "maximumWarning": "2mb",
          "maximumError": "5mb"
       }
    ]

As you’ve probably guessed you can increase the maximumWarning value to prevent this warning, i.e.:

    "budgets": [
       {
          "type": "initial",
          "maximumWarning": "4mb", <===
          "maximumError": "5mb"
       }
    ]

What does budgets mean?

A performance budget is a group of limits to certain values that affect site performance, that may not be exceeded in the design and development of any web project.

In our case budget is the limit for bundle sizes.

See also:

Flutter - The method was called on null

Because of your initialization wrong.

Don't do like this,

MethodName _methodName;

Do like this,

MethodName _methodName = MethodName();

What is the Record type in typescript?

A Record lets you create a new type from a Union. The values in the Union are used as attributes of the new type.

For example, say I have a Union like this:

type CatNames = "miffy" | "boris" | "mordred";

Now I want to create an object that contains information about all the cats, I can create a new type using the values in the CatName Union as keys.

type CatList = Record<CatNames, {age: number}>

If I want to satisfy this CatList, I must create an object like this:

const cats:CatList = {
  miffy: { age:99 },
  boris: { age:16 },
  mordred: { age:600 }
}

You get very strong type safety:

  • If I forget a cat, I get an error.
  • If I add a cat that's not allowed, I get an error.
  • If I later change CatNames, I get an error. This is especially useful because CatNames is likely imported from another file, and likely used in many places.

Real-world React example.

I used this recently to create a Status component. The component would receive a status prop, and then render an icon. I've simplified the code quite a lot here for illustrative purposes

I had a union like this:

type Statuses = "failed" | "complete";

I used this to create an object like this:

const icons: Record<
  Statuses,
  { iconType: IconTypes; iconColor: IconColors }
> = {
  failed: {
    iconType: "warning",
    iconColor: "red"
  },
  complete: {
    iconType: "check",
    iconColor: "green"
  };

I could then render by destructuring an element from the object into props, like so:

const Status = ({status}) => <Icon {...icons[status]} />

If the Statuses union is later extended or changed, I know my Status component will fail to compile and I'll get an error that I can fix immediately. This allows me to add additional error states to the app.

Note that the actual app had dozens of error states that were referenced in multiple places, so this type safety was extremely useful.

Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0

Run the Gradle build with a command line argument --warning-mode=all to see what exactly the deprecated features are.

It will give you a detailed description of found issues with links to the Gradle docs for instructions how to fix your build.

Adding --stacktrace to that, you will also be able to pinpoint where the warning comes from, if it's triggered by outdated code in one of the plugins and not your build script.

How do I install the Nuget provider for PowerShell on a unconnected machine so I can install a nuget package from the PS command line?

Here is the script I use in a Dockerfile based on windows/servercore to achieve complete PowerShellGallery setup through Artifactory mirrors (require access to GitHub releases too)

ARG ONEGET_PACKAGEMANAGEMENT="https://artifactory/artifactory/github-releases/OneGet/oneget/releases/download/1.4/PackageManagement.zip"
ARG ONEGET_ZIPFILE="C:/PackageManagement.zip"
 
RUN $ProviderPath = 'C:/Program Files/PackageManagement/ProviderAssemblies/nuget/2.8.5.208/'; `
    Invoke-WebRequest -Uri ${Env:ONEGET_PACKAGEMANAGEMENT} -OutFile ${Env:ONEGET_ZIPFILE}; `
    Expand-Archive ${Env:ONEGET_ZIPFILE} -DestinationPath "C:/" -Force; `
    New-Item -ItemType "directory" -Path $ProviderPath -Force; `
    Move-Item -Path "C:/PackageManagement/fullclr/Microsoft.PackageManagement.NuGetProvider.dll" -Destination $ProviderPath -Force; `
    Remove-Item -Recurse -Force -Path "C:/PackageManagement",${Env:ONEGET_ZIPFILE}; `
    Install-PackageProvider -Name NuGet -RequiredVersion 2.8.5.208 -Force; `
    Register-PSRepository -Name "artifactory-powershellgallery-remote" -SourceLocation "https://artifactory/artifactory/api/nuget/powershellgallery-remote"; `
    Unregister-PSRepository -Name PSGallery;

What exactly is the 'react-scripts start' command?

create-react-app and react-scripts

react-scripts is a set of scripts from the create-react-app starter pack. create-react-app helps you kick off projects without configuring, so you do not have to setup your project by yourself.

react-scripts start sets up the development environment and starts a server, as well as hot module reloading. You can read here to see what everything it does for you.

with create-react-app you have following features out of the box.

  • React, JSX, ES6, and Flow syntax support.
  • Language extras beyond ES6 like the object spread operator.
  • Autoprefixed CSS, so you don’t need -webkit- or other prefixes.
  • A fast interactive unit test runner with built-in support for coverage reporting.
  • A live development server that warns about common mistakes.
  • A build script to bundle JS, CSS, and images for production, with hashes and sourcemaps.
  • An offline-first service worker and a web app manifest, meeting all the Progressive Web App criteria.
  • Hassle-free updates for the above tools with a single dependency.

npm scripts

npm start is a shortcut for npm run start.

npm run is used to run scripts that you define in the scripts object of your package.json

if there is no start key in the scripts object, it will default to node server.js

Sometimes you want to do more than the react scripts gives you, in this case you can do react-scripts eject. This will transform your project from a "managed" state into a not managed state, where you have full control over dependencies, build scripts and other configurations.

Set default option in mat-select

Normally you are going to do this in your template with FormGroup, Reactive Forms, etc...

    this.myForm = this.fb.group({
      title: ['', Validators.required],
      description: ['', Validators.required],
      isPublished: ['false',Validators.required]
    });

How to do a timer in Angular 5

You can simply use setInterval to create such timer in Angular, Use this Code for timer -

timeLeft: number = 60;
  interval;

startTimer() {
    this.interval = setInterval(() => {
      if(this.timeLeft > 0) {
        this.timeLeft--;
      } else {
        this.timeLeft = 60;
      }
    },1000)
  }

  pauseTimer() {
    clearInterval(this.interval);
  }

<button (click)='startTimer()'>Start Timer</button>
<button (click)='pauseTimer()'>Pause</button>

<p>{{timeLeft}} Seconds Left....</p>

Working Example

Another way using Observable timer like below -

import { timer } from 'rxjs';

observableTimer() {
    const source = timer(1000, 2000);
    const abc = source.subscribe(val => {
      console.log(val, '-');
      this.subscribeTimer = this.timeLeft - val;
    });
  }

<p (click)="observableTimer()">Start Observable timer</p> {{subscribeTimer}}

Working Example

For more information read here

Access IP Camera in Python OpenCV

To access an Ip Camera, first, I recommend you to install it like you are going to use for the standard application, without any code, using normal software.

After this, you have to know that for different cameras, we have different codes. There is a website where you can see what code you can use to access them:

https://www.ispyconnect.com/sources.aspx

But be careful, for my camera (Intelbras S3020) it does not work. The right way is to ask the company of your camera, and if they are a good company they will provide it.

When you know your code just add it like:

cap = cv2.VideoCapture("http://LOGIN:PASSWORD@IP/cgi-bin/mjpg/video.cgi?&subtype=1")

Instead LOGIN you will put your login, and instead PASSWORD you will put your password.

To find out camera's IP address there is many softwares that you can download and provide the Ip address to you. I use the software from Intelbras, but I also recommend EseeCloud because they work for almost all cameras that I've bought:

https://eseecloud.software.informer.com/1.2/

In this example, it shows the protocol http to access the Ip camera, but you can also use rstp, it depends on the camera, as I said.

If you have any further questions just let me know.

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

If we need to move from one component to another service then we have to define that service into app.module providers array.

Default interface methods are only supported starting with Android N

Update your build.gradle(Module:app) add compileOptions block and add JavaVersion.VERSION_1_8

apply plugin: 'com.android.application'

android {
    .................
    .........................
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

React : difference between <Route exact path="/" /> and <Route path="/" />

In this example, nothing really. The exact param comes into play when you have multiple paths that have similar names:

For example, imagine we had a Users component that displayed a list of users. We also have a CreateUser component that is used to create users. The url for CreateUsers should be nested under Users. So our setup could look something like this:

<Switch>
  <Route path="/users" component={Users} />
  <Route path="/users/create" component={CreateUser} />
</Switch>

Now the problem here, when we go to http://app.com/users the router will go through all of our defined routes and return the FIRST match it finds. So in this case, it would find the Users route first and then return it. All good.

But, if we went to http://app.com/users/create, it would again go through all of our defined routes and return the FIRST match it finds. React router does partial matching, so /users partially matches /users/create, so it would incorrectly return the Users route again!

The exact param disables the partial matching for a route and makes sure that it only returns the route if the path is an EXACT match to the current url.

So in this case, we should add exact to our Users route so that it will only match on /users:

<Switch>
  <Route exact path="/users" component={Users} />
  <Route path="/users/create" component={CreateUser} />
</Switch>

The docs explain exact in detail and give other examples.

ASP.NET Core - Swashbuckle not creating swagger.json file

I don't know if this is useful for someone, but in my case the problem was that the name had different casing.

V1 in the service configuration - V capital letter
v1 in Settings -- v lower case

The only thing I did was to use the same casing and it worked.

version name with capital V

What is pipe() function in Angular

Two very different types of Pipes Angular - Pipes and RxJS - Pipes

Angular-Pipe

A pipe takes in data as input and transforms it to a desired output. In this page, you'll use pipes to transform a component's birthday property into a human-friendly date.

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

@Component({
  selector: 'app-hero-birthday',
  template: `<p>The hero's birthday is {{ birthday | date }}</p>`
})
export class HeroBirthdayComponent {
  birthday = new Date(1988, 3, 15); // April 15, 1988
}

RxJS - Pipe

Observable operators are composed using a pipe method known as Pipeable Operators. Here is an example.

import {Observable, range} from 'rxjs';
import {map, filter} from 'rxjs/operators';

const source$: Observable<number> = range(0, 10);

source$.pipe(
    map(x => x * 2),
    filter(x => x % 3 === 0)
).subscribe(x => console.log(x));

The output for this in the console would be the following:

0

6

12

18

For any variable holding an observable, we can use the .pipe() method to pass in one or multiple operator functions that can work on and transform each item in the observable collection.

So this example takes each number in the range of 0 to 10, and multiplies it by 2. Then, the filter function to filter the result down to only the odd numbers.

what does numpy ndarray shape do?

Unlike it's most popular commercial competitor, numpy pretty much from the outset is about "arbitrary-dimensional" arrays, that's why the core class is called ndarray. You can check the dimensionality of a numpy array using the .ndim property. The .shape property is a tuple of length .ndim containing the length of each dimensions. Currently, numpy can handle up to 32 dimensions:

a = np.ones(32*(1,))
a
# array([[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ 1.]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]])
a.shape
# (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
a.ndim
# 32

If a numpy array happens to be 2d like your second example, then it's appropriate to think about it in terms of rows and columns. But a 1d array in numpy is truly 1d, no rows or columns.

If you want something like a row or column vector you can achieve this by creating a 2d array with one of its dimensions equal to 1.

a = np.array([[1,2,3]]) # a 'row vector'
b = np.array([[1],[2],[3]]) # a 'column vector'
# or if you don't want to type so many brackets:
b = np.array([[1,2,3]]).T

NullInjectorError: No provider for AngularFirestore

import angularFirebaseStore 

in app.module.ts and set it as a provider like service

How to update/upgrade a package using pip?

use this code in teminal :

python -m pip install --upgrade PAKAGE_NAME #instead of PAKAGE_NAME 

for example i want update pip pakage :

 python -m pip install --upgrade pip

more example :

python -m pip install --upgrade selenium
python -m pip install --upgrade requests
...

How to open local file on Jupyter?

simple way is to move your files to be read under the same folder of your python file, then you just need to use the name of the file, without calling another path.

react-router (v4) how to go back?

Try:

this.props.router.goBack()

How to VueJS router-link active style

Just add to @Bert's solution to make it more clear:

    const routes = [
  { path: '/foo', component: Foo },
  { path: '/bar', component: Bar }
]

const router = new VueRouter({
  routes,
  linkExactActiveClass: "active" // active class for *exact* links.
})

As one can see, this line should be removed:

linkActiveClass: "active", // active class for non-exact links.

this way, ONLY the current link is hi-lighted. This should apply to most of the cases.

David

React Router Pass Param to Component

try this.

<Route exact path="/details/:id" render={(props)=>{return(
    <DetailsPage id={props.match.params.id}/>)
}} />

In details page try this...

this.props.id

How to import popper.js?

I had the same problem. Tried different approches, but this one worked for me. Read the instruction from http://getbootstrap.com/.

Copy the CDN paths of Javascripts (Popper, jQuery and Bootstrap) in same manner (it is important) as given.

enter image description here

_x000D_
_x000D_
<head>_x000D_
//Path to jQuery_x000D_
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>_x000D_
_x000D_
////Path to Popper - it is for dropsdowns etc in bootstrap_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>_x000D_
_x000D_
//Path to bootsrap_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>_x000D_
</head>
_x000D_
_x000D_
_x000D_

NotificationCompat.Builder deprecated in Android O

This constructor was deprecated in API level 26.1.0. use NotificationCompat.Builder(Context, String) instead. All posted Notifications must specify a NotificationChannel Id.

Constraint Layout Vertical Align Center

Two buttons one centered one below to the left of it

Showing it graphically.

Centering on parent is done by constraining both sides to the parent. You can the constrain additional objects off of the centered object.

Note. Each arrow represents a "app:layout_constraintXXX_toYYY=" attribute. (6 in the picture)

ESLint not working in VS Code?

General issues

Open the terminal Ctrl+`

Under output ESLint dropdown, you find useful debugging data (Errors, warnings, info).

enter image description here

For example, missing .eslintrc-.json throw this error: enter image description here

Error: ENOENT: no such file or directory, realpath

Next, check if the plugin enabled: enter image description here

Last, Since v 2.0.4 - eslint.validate in normal cases not necessary anymore (old legacy setting):

eslint.probe = an array for language identifiers for which the ESLint extension should be activated and should try to validate the file. If validation fails for probed languages the extension says silent. Defaults to [javascript, javascriptreact, typescript, typescriptreact, html, vue, markdown].

Specific Issue - First-time plugin instalation

My issue was related to the ESLint plugin "currently block" status bar enter image description here on New/First instalation (v2.1.14).

Since ESLint plugin Version 2.1.10 (08/10/2020)

no modal dialog is shown when the ESLint extension tries to load an ESLint library for the first time and an approval is necessary. Instead the ESLint status bar item changes to ESLint status icon indicating that the execution is currently block.

Click on the status-bar (Right-Bottom corner): enter image description here

Opens this popup:

enter image description here

Approve ==> Allows Everywhere

enter image description here

-or- by commands:

ctrl + Shift + p -- ESLint: Manage Library Execution

enter image description here

Read more here under "Release Notes":

https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint

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

Note This answer only applies to version 2.x of Vue. Version 3 has lifted this restriction.

You have two root elements in your template.

<div class="form-group">
  ...
</div>
<div class="col-md-6">
  ...
</div>

And you need one.

<div>
    <div class="form-group">
      ...
    </div>

    <div class="col-md-6">
      ...
    </div>
</div>

Essentially in Vue you must have only one root element in your templates.

Returning JSON object as response in Spring Boot

use ResponseEntity<ResponseBean>

Here you can use ResponseBean or Any java bean as you like to return your api response and it is the best practice. I have used Enum for response. it will return status code and status message of API.

@GetMapping(path = "/login")
public ResponseEntity<ServiceStatus> restApiExample(HttpServletRequest request,
            HttpServletResponse response) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        loginService.login(username, password, request);
        return new ResponseEntity<ServiceStatus>(ServiceStatus.LOGIN_SUCCESS,
                HttpStatus.ACCEPTED);
    }

for response ServiceStatus or(ResponseBody)

    public enum ServiceStatus {

    LOGIN_SUCCESS(0, "Login success"),

    private final int id;
    private final String message;

    //Enum constructor
    ServiceStatus(int id, String message) {
        this.id = id;
        this.message = message;
    }

    public int getId() {
        return id;
    }

    public String getMessage() {
        return message;
    }
}

Spring REST API should have below key in response

  1. Status Code
  2. Message

you will get final response below

{

   "StatusCode" : "0",

   "Message":"Login success"

}

you can use ResponseBody(java POJO, ENUM,etc..) as per your requirement.

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

Don't use with Router.

handleSubmit(e){
   e.preventDefault();
   this.props.form.validateFieldsAndScroll((err,values)=>{
      if(!err){
        this.setState({
            visible:false
        });
        this.props.form.resetFields();
        console.log(values.username);
        const path = '/list/';
        this.props.history.push(path);
      }
   })
}

It works well.

VS 2017 Metadata file '.dll could not be found

I had 2 files (and 2 classes) in the same project with the same name.

Val and Var in Kotlin

var is a variable like any other language. eg.

var price: Double

On the other side, val provides you feature of referencing. eg.

val CONTINENTS = 7
// You refer this to get constant value 7. In this case, val acts as access
// specifier final in Java

and,

val Int.absolute: Int
    get() {
        return Math.abs(this)
    }
// You refer to the newly create 'method' which provides absolute value 
// of your integer

println(-5.absolute) // O.P: 5

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

I had missing application context in the Tomcat Run\Debug configuration:enter image description here

Adding it, solved the problem and I got the right response instead of "The origin server did not find..."

How do I set the background color of my main screen in Flutter?

You can set background color to All Scaffolds in application at once.

just set scaffoldBackgroundColor: in ThemeData

 MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(scaffoldBackgroundColor: const Color(0xFFEFEFEF)),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );

How to fix the error "Windows SDK version 8.1" was not found?

I realize this post is a few years old, but I just wanted to extend this to anyone still struggling through this issue.

The company I work for still uses VS2015 so in turn I still use VS2015. I recently started working on a RPC application using C++ and found the need to download the Win32 Templates. Like many others I was having this "SDK 8.1 was not found" issue. i took the following corrective actions with no luck.

  • I found the SDK through Micrsoft at the following link https://developer.microsoft.com/en-us/windows/downloads/sdk-archive/ as referenced above and downloaded it.
  • I located my VS2015 install in Apps & Features and ran the repair.
  • I completely uninstalled my VS2015 and reinstalled it.
  • I attempted to manually point my console app "Executable" and "Include" directories to the C:\Program Files (x86)\Microsoft SDKs\Windows Kits\8.1 and C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools.

None of the attempts above corrected the issue for me...

I then found this article on social MSDN https://social.msdn.microsoft.com/Forums/office/en-US/5287c51b-46d0-4a79-baad-ddde36af4885/visual-studio-cant-find-windows-81-sdk-when-trying-to-build-vs2015?forum=visualstudiogeneral

Finally what resolved the issue for me was:

  • Uninstalling and reinstalling VS2015.
  • Locating my installed "Windows Software Development Kit for Windows 8.1" and running the repair.
  • Checked my "C:\Program Files (x86)\Microsoft SDKs\Windows Kits\8.1" to verify the "DesignTime" folder was in fact there.
  • Opened VS created a Win32 Console application and comiled with no errors or issues

I hope this saves anyone else from almost 3 full days of frustration and loss of productivity.

Spark difference between reduceByKey vs groupByKey vs aggregateByKey vs combineByKey

Then apart from these 4, we have

foldByKey which is same as reduceByKey but with a user defined Zero Value.

AggregateByKey takes 3 parameters as input and uses 2 functions for merging(one for merging on same partitions and another to merge values across partition. The first parameter is ZeroValue)

whereas

ReduceBykey takes 1 parameter only which is a function for merging.

CombineByKey takes 3 parameter and all 3 are functions. Similar to aggregateBykey except it can have a function for ZeroValue.

GroupByKey takes no parameter and groups everything. Also, it is an overhead for data transfer across partitions.

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

For me, I missed this statement in @Component decorator: animations: [yourAnimation]

Once I added this statement, errors gone. (Angular 6.x)

How to implement authenticated routes in React Router 4?

Heres how I solved it with React and Typescript. Hope it helps !

_x000D_
_x000D_
import * as React from 'react';
import { FC } from 'react';
import { Route, RouteComponentProps, RouteProps, Redirect } from 'react-router';

const PrivateRoute: FC<RouteProps> = ({ component: Component, ...rest }) => {
    if (!Component) {
      return null;
    }
    const isLoggedIn = true; // Add your provider here
    return (
      <Route
        {...rest}
            render={(props: RouteComponentProps<{}>) => isLoggedIn ? (<Component {...props} />) : (<Redirect to={{ pathname: '/', state: { from: props.location } }} />)}
      />
    );
  };

export default PrivateRoute;








<PrivateRoute component={SignIn} path="/signin" />
_x000D_
_x000D_
_x000D_

Purpose of "%matplotlib inline"

If you want to add plots to your Jupyter notebook, then %matplotlib inline is a standard solution. And there are other magic commands will use matplotlib interactively within Jupyter.

%matplotlib: any plt plot command will now cause a figure window to open, and further commands can be run to update the plot. Some changes will not draw automatically, to force an update, use plt.draw()

%matplotlib notebook: will lead to interactive plots embedded within the notebook, you can zoom and resize the figure

%matplotlib inline: only draw static images in the notebook

React-Router External link

FOR V3, although it may work for V4. Going off of Eric's answer, I needed to do a little more, like handle local development where 'http' is not present on the url. I'm also redirecting to another application on the same server.

Added to router file:

import RedirectOnServer from './components/RedirectOnServer';

       <Route path="/somelocalpath"
          component={RedirectOnServer}
          target="/someexternaltargetstring like cnn.com"
        />

And the Component:

import React, { Component } from "react";

export class RedirectOnServer extends Component {

  constructor(props) {
    super();
    //if the prefix is http or https, we add nothing
    let prefix = window.location.host.startsWith("http") ? "" : "http://";
    //using host here, as I'm redirecting to another location on the same host
    this.target = prefix + window.location.host + props.route.target;
  }
  componentDidMount() {
    window.location.replace(this.target);
  }
  render(){
    return (
      <div>
        <br />
        <span>Redirecting to {this.target}</span>
      </div>
    );
  }
}

export default RedirectOnServer;

Unit Tests not discovered in Visual Studio 2017

Just had this problem with visual studio being unable to find my tests, couldn't see the button to run them besides the method, and they weren't picked up by running all tests in the project.

Turns out my test class wasn't public! Making it public allowed VS to discover the tests.

All com.android.support libraries must use the exact same version specification

Open the external library of your project you will see that some library still using previous version although you didn't mention those library so my suggestion is just use the particular library version for those it will solve your problem.

In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?

That's the non-null assertion operator. It is a way to tell the compiler "this expression cannot be null or undefined here, so don't complain about the possibility of it being null or undefined." Sometimes the type checker is unable to make that determination itself.

It is explained here:

A new ! post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact. Specifically, the operation x! produces a value of the type of x with null and undefined excluded. Similar to type assertions of the forms <T>x and x as T, the ! non-null assertion operator is simply removed in the emitted JavaScript code.

I find the use of the term "assert" a bit misleading in that explanation. It is "assert" in the sense that the developer is asserting it, not in the sense that a test is going to be performed. The last line indeed indicates that it results in no JavaScript code being emitted.

How to install PHP intl extension in Ubuntu 14.04

install it from terminal

sudo apt-get install php-intl

TypeScript hashmap/dictionary interface

Just as a normal js object:

let myhash: IHash = {};   

myhash["somestring"] = "value"; //set

let value = myhash["somestring"]; //get

There are two things you're doing with [indexer: string] : string

  • tell TypeScript that the object can have any string-based key
  • that for all key entries the value MUST be a string type.

enter image description here

You can make a general dictionary with explicitly typed fields by using [key: string]: any;

enter image description here

e.g. age must be number, while name must be a string - both are required. Any implicit field can be any type of value.

As an alternative, there is a Map class:

let map = new Map<object, string>(); 

let key = new Object();

map.set(key, "value");
map.get(key); // return "value"

This allows you have any Object instance (not just number/string) as the key.

Although its relatively new so you may have to polyfill it if you target old systems.

How does spring.jpa.hibernate.ddl-auto property exactly work in Spring?

For the record, the spring.jpa.hibernate.ddl-auto property is Spring Data JPA specific and is their way to specify a value that will eventually be passed to Hibernate under the property it knows, hibernate.hbm2ddl.auto.

The values create, create-drop, validate, and update basically influence how the schema tool management will manipulate the database schema at startup.

For example, the update operation will query the JDBC driver's API to get the database metadata and then Hibernate compares the object model it creates based on reading your annotated classes or HBM XML mappings and will attempt to adjust the schema on-the-fly.

The update operation for example will attempt to add new columns, constraints, etc but will never remove a column or constraint that may have existed previously but no longer does as part of the object model from a prior run.

Typically in test case scenarios, you'll likely use create-drop so that you create your schema, your test case adds some mock data, you run your tests, and then during the test case cleanup, the schema objects are dropped, leaving an empty database.

In development, it's often common to see developers use update to automatically modify the schema to add new additions upon restart. But again understand, this does not remove a column or constraint that may exist from previous executions that is no longer necessary.

In production, it's often highly recommended you use none or simply don't specify this property. That is because it's common practice for DBAs to review migration scripts for database changes, particularly if your database is shared across multiple services and applications.

Nested routes with react router v4 / v5

Some thing like this.

_x000D_
_x000D_
import React from 'react';_x000D_
import {_x000D_
  BrowserRouter as Router, Route, NavLink, Switch, Link_x000D_
} from 'react-router-dom';_x000D_
_x000D_
import '../assets/styles/App.css';_x000D_
_x000D_
const Home = () =>_x000D_
  <NormalNavLinks>_x000D_
    <h1>HOME</h1>_x000D_
  </NormalNavLinks>;_x000D_
const About = () =>_x000D_
  <NormalNavLinks>_x000D_
    <h1>About</h1>_x000D_
  </NormalNavLinks>;_x000D_
const Help = () =>_x000D_
  <NormalNavLinks>_x000D_
    <h1>Help</h1>_x000D_
  </NormalNavLinks>;_x000D_
_x000D_
const AdminHome = () =>_x000D_
  <AdminNavLinks>_x000D_
    <h1>root</h1>_x000D_
  </AdminNavLinks>;_x000D_
_x000D_
const AdminAbout = () =>_x000D_
  <AdminNavLinks>_x000D_
    <h1>Admin about</h1>_x000D_
  </AdminNavLinks>;_x000D_
_x000D_
const AdminHelp = () =>_x000D_
  <AdminNavLinks>_x000D_
    <h1>Admin Help</h1>_x000D_
  </AdminNavLinks>;_x000D_
_x000D_
_x000D_
const AdminNavLinks = (props) => (_x000D_
  <div>_x000D_
    <h2>Admin Menu</h2>_x000D_
    <NavLink exact to="/admin">Admin Home</NavLink>_x000D_
    <NavLink to="/admin/help">Admin Help</NavLink>_x000D_
    <NavLink to="/admin/about">Admin About</NavLink>_x000D_
    <Link to="/">Home</Link>_x000D_
    {props.children}_x000D_
  </div>_x000D_
);_x000D_
_x000D_
const NormalNavLinks = (props) => (_x000D_
  <div>_x000D_
    <h2>Normal Menu</h2>_x000D_
    <NavLink exact to="/">Home</NavLink>_x000D_
    <NavLink to="/help">Help</NavLink>_x000D_
    <NavLink to="/about">About</NavLink>_x000D_
    <Link to="/admin">Admin</Link>_x000D_
    {props.children}_x000D_
  </div>_x000D_
);_x000D_
_x000D_
const App = () => (_x000D_
  <Router>_x000D_
    <div>_x000D_
      <Switch>_x000D_
        <Route exact path="/" component={Home}/>_x000D_
        <Route path="/help" component={Help}/>_x000D_
        <Route path="/about" component={About}/>_x000D_
_x000D_
        <Route exact path="/admin" component={AdminHome}/>_x000D_
        <Route path="/admin/help" component={AdminHelp}/>_x000D_
        <Route path="/admin/about" component={AdminAbout}/>_x000D_
      </Switch>_x000D_
_x000D_
    </div>_x000D_
  </Router>_x000D_
);_x000D_
_x000D_
_x000D_
export default App;
_x000D_
_x000D_
_x000D_

Angular 1.6.0: "Possibly unhandled rejection" error

To avoid having to type additional .catch(function () {}) in your code in multiple places, you could add a decorator to the $exceptionHandler.

This is a more verbose option than the others but you only have to make the change in one place.

angular
    .module('app')
    .config(configDecorators);

configDecorators.$inject = ["$provide"];
function configDecorators($provide) {

    $provide.decorator("$exceptionHandler", exceptionHandler);

    exceptionHandler.$inject = ['$delegate', '$injector'];
    function exceptionHandler($delegate, $injector) {
        return function (exception, cause) {

            if ((exception.toString().toLowerCase()).includes("Possibly unhandled rejection".toLowerCase())) {
                console.log(exception); /* optional to log the "Possibly unhandled rejection" */
                return;
            }
            $delegate(exception, cause);
        };
    }
};

Installing TensorFlow on Windows (Python 3.6.x)

On 2/22/18, when I tried the official recommendation:

pip3 install --upgrade tensorflow

I got this error

Could not find a version that satisfies the requirement tensorflow

But instead using

pip install --upgrade tensorflow

installed it ok. (I ran it from the ps command prompt.)

I have 64-bit windows 10, 64-bit python 3.6.3, and pip3 version 9.0.1.

How to turn on/off MySQL strict mode in localhost (xampp)?

I want to know how to check whether MySQL strict mode is on or off in localhost(xampp).

SHOW VARIABLES LIKE 'sql_mode';

If result has "STRICT_TRANS_TABLES", then it's ON. Otherwise, it's OFF.

If on then for what modes and how to off.

If off then how to on.

For Windows,

  1. Go to C:\Program Files\MariaDB XX.X\data
  2. Open the my.ini file.
  3. *On the line with "sql_mode", modify the value to turn strict mode ON/OFF.
  4. Save the file
  5. **Restart the MySQL service
  6. Run SHOW VARIABLES LIKE 'sql_mode' again to see if it worked;

*3.a. To turn it ON, add STRICT_TRANS_TABLES on that line like this: sql_mode=STRICT_TRANS_TABLES. *If there are other values already, add a comma after this then join with the rest of the value.

*3.b. To turn it OFF, simply remove STRICT_TRANS_TABLES from value. *Remove the additional comma too if there is one.

**6. To restart the MySQL service on your computer,

  1. Open the Run command window (press WINDOWS + R button).
  2. Type services.msc
  3. Click OK
  4. Right click on the Name MySQL
  5. Click Restart

Disable nginx cache for JavaScript files

What you are looking for is a simple directive like:

location ~* \.(?:manifest|appcache|html?|xml|json)$ {
    expires -1;
}

The above will not cache the extensions within the (). You can configure different directives for different file types.

Support for ES6 in Internet Explorer 11

The statement from Microsoft regarding the end of Internet Explorer 11 support mentions that it will continue to receive security updates, compatibility fixes, and technical support until its end of life. The wording of this statement leads me to believe that Microsoft has no plans to continue adding features to Internet Explorer 11, and instead will be focusing on Edge.

If you require ES6 features in Internet Explorer 11, check out a transpiler such as Babel.

BehaviorSubject vs Observable?

An observable allows you to subscribe only whereas a subject allows you to both publish and subscribe.

So a subject allows your services to be used as both a publisher and a subscriber.

As of now, I'm not so good at Observable so I'll share only an example of Subject.

Let's understand better with an Angular CLI example. Run the below commands:

npm install -g @angular/cli

ng new angular2-subject

cd angular2-subject

ng serve

Replace the content of app.component.html with:

<div *ngIf="message">
  {{message}}
</div>

<app-home>
</app-home>

Run the command ng g c components/home to generate the home component. Replace the content of home.component.html with:

<input type="text" placeholder="Enter message" #message>
<button type="button" (click)="setMessage(message)" >Send message</button>

#message is the local variable here. Add a property message: string; to the app.component.ts's class.

Run this command ng g s service/message. This will generate a service at src\app\service\message.service.ts. Provide this service to the app.

Import Subject into MessageService. Add a subject too. The final code shall look like this:

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class MessageService {

  public message = new Subject<string>();

  setMessage(value: string) {
    this.message.next(value); //it is publishing this value to all the subscribers that have already subscribed to this message
  }
}

Now, inject this service in home.component.ts and pass an instance of it to the constructor. Do this for app.component.ts too. Use this service instance for passing the value of #message to the service function setMessage:

import { Component } from '@angular/core';
import { MessageService } from '../../service/message.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent {

  constructor(public messageService:MessageService) { }

  setMessage(event) {
    console.log(event.value);
    this.messageService.setMessage(event.value);
  }
}

Inside app.component.ts, subscribe and unsubscribe (to prevent memory leaks) to the Subject:

import { Component, OnDestroy } from '@angular/core';
import { MessageService } from './service/message.service';
import { Subscription } from 'rxjs/Subscription';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {

  message: string;
  subscription: Subscription;

  constructor(public messageService: MessageService) { }

  ngOnInit() {
    this.subscription = this.messageService.message.subscribe(
      (message) => {
        this.message = message;
      }
    );
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

That's it.

Now, any value entered inside #message of home.component.html shall be printed to {{message}} inside app.component.html

Updating to latest version of CocoaPods?

This is a really quick & detailed solution

Open the Terminal and execute the following to get the latest stable version:

sudo gem install cocoapods

Add --pre to get the latest pre release:

sudo gem install cocoapods --pre

Incase any error occured

Try uninstall and install again:

sudo gem uninstall cocoapods
sudo gem install cocoapods

Run after updating CocoaPods

sudo gem clean cocoapods

After updating CocoaPods, also need to update Podfile.lock file in your project.

Go to your project directory

pod install

How to add SHA-1 to android application

Just In case: while using the command line to generate the SHA1 fingerprint, be careful while specifying the folder path. If your User Name or android folder path has a space, you should add two double quotes as below:

keytool -list -v -keystore "C:\Users\User Name\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

What is the meaning of <> in mysql query?

<> is equal to != i.e, both are used to represent the NOT EQUAL operation. For instance, email <> '' and email != '' are same.

Can't bind to 'ngIf' since it isn't a known property of 'div'

If you are using RC5 then import this:

import { CommonModule } from '@angular/common';  
import { BrowserModule } from '@angular/platform-browser';

and be sure to import CommonModule from the module that is providing your component.

 @NgModule({
    imports: [CommonModule],
    declarations: [MyComponent]
  ...
})
class MyComponentModule {}

Clear an input field with Reactjs?

You can use input type="reset"

<form action="/action_page.php">
  text: <input type="text" name="email" /><br />  
  <input type="reset" defaultValue="Reset" />  
</form>

Convert a string to datetime in PowerShell

$invoice = "Jul-16"
[datetime]$newInvoice = "01-" + $invoice

$newInvoice.ToString("yyyy-MM-dd")

There you go, use a type accelerator, but also into a new var, if you want to use it elsewhere, use it like so: $newInvoice.ToString("yyyy-MM-dd")as $newInvoice will always be in the datetime format, unless you cast it as a string afterwards, but will lose the ability to perform datetime functions - adding days etc...

ImportError: No module named google.protobuf

I also have this issue and have been looking into it for a long time. It seems that there is no such problem on python 3+. The problem is actually on google.protobuf

Solution 1:

pip uninstall protobuf
pip uninstall google
pip install google
pip install protobuf
pip install google-cloud

Solution 2:

create an __init__.py in "google" folder.

cd /path/to/your/env/lib/python2.7/site-packages/google
touch __init__.py

Hopefully it will work.

Angular2 set value for formGroup

To set all FormGroup values use, setValue:

this.myFormGroup.setValue({
  formControlName1: myValue1, 
  formControlName2: myValue2
});

To set only some values, use patchValue:

this.myFormGroup.patchValue({
  formControlName1: myValue1, 
  // formControlName2: myValue2 (can be omitted)
});

With this second technique, not all values need to be supplied and fields whos values were not set will not be affected.

Check if a value is in an array or not with Excel VBA

This Question was asked here: VBA Arrays - Check strict (not approximative) match

Sub test()
    vars1 = Array("Examples")
    vars2 = Array("Example")
    If IsInArray(Range("A1").value, vars1) Then
        x = 1
    End If

    If IsInArray(Range("A1").value, vars2) Then
        x = 1
    End If
End Sub

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
    IsInArray = Not IsError(Application.Match(stringToBeFound, arr, 0))
End Function

Split / Explode a column of dictionaries into separate columns with pandas

I strongly recommend the method extract the column 'Pollutants':

df_pollutants = pd.DataFrame(df['Pollutants'].values.tolist(), index=df.index)

it's much faster than

df_pollutants = df['Pollutants'].apply(pd.Series)

when the size of df is giant.

MongoDB: How to find the exact version of installed MongoDB

To check mongodb version use the mongod command with --version option.

To check MongoDB Server version, Open the command line via your terminal program and execute the following command:

Path : C:\Program Files\MongoDB\Server\3.2\bin Open Cmd and execute the following command: mongod --version To Check MongoDB Shell version, Type:

mongo --version

FCM getting MismatchSenderId

You will have a server key something like this AIzaSyDiTEVq4Li1pj7IyraRlyRU9adc-49-KVY available in the Settings section of firebase console console.firebase.google.com/project/project-XXXXXXXXXXXXX/settings/cloudmessaging.

Specify the correct key with your code and try again.

Use of symbols '@', '&', '=' and '>' in custom directive's scope binding: AngularJS

When we create a customer directive, the scope of the directive could be in Isolated scope, It means the directive does not share a scope with the controller; both directive and controller have their own scope. However, data can be passed to the directive scope in three possible ways.

  1. Data can be passed as a string using the @ string literal, pass string value, one way binding.
  2. Data can be passed as an object using the = string literal, pass object, 2 ways binding.
  3. Data can be passed as a function the & string literal, calls external function, can pass data from directive to controller.

How to return HTTP 500 from ASP.NET Core RC2 Web Api?

From what I can see there are helper methods inside the ControllerBase class. Just use the StatusCode method:

[HttpPost]
public IActionResult Post([FromBody] string something)
{    
    //...
    try
    {
        DoSomething();
    }
    catch(Exception e)
    {
         LogException(e);
         return StatusCode(500);
    }
}

You may also use the StatusCode(int statusCode, object value) overload which also negotiates the content.

What is FCM token in Firebase?

FirebaseInstanceIdService is now deprecated. you should get the Token in the onNewToken method in the FirebaseMessagingService.

Check out the docs

How to unset (remove) a collection element after fetching it?

Or you can use reject method

$newColection = $collection->reject(function($element) {
    return $item->selected != true;
});

or pull method

$selected = []; 
foreach ($collection as $key => $item) {
      if ($item->selected == true) {
          $selected[] = $collection->pull($key);
      }
}

How to call another components function in angular2

You can access component one's method from component two..

componentOne

  ngOnInit() {}

  public testCall(){
    alert("I am here..");    
  }

componentTwo

import { oneComponent } from '../one.component';


@Component({
  providers:[oneComponent ],
  selector: 'app-two',
  templateUrl: ...
}


constructor(private comp: oneComponent ) { }

public callMe(): void {
    this.comp.testCall();
  }

componentTwo html file

<button (click)="callMe()">click</button>

Convert string to buffer Node

This is working for me, you might change your code like this

var responseData=x.toString();

to

var responseData=x.toString("binary");

and finally

response.write(new Buffer(toTransmit, "binary"));

How to Validate on Max File Size in Laravel?

According to the documentation:

$validator = Validator::make($request->all(), [
    'file' => 'max:500000',
]);

The value is in kilobytes. I.e. max:10240 = max 10 MB.

JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory

The issue is that you are not able to get a connection to MYSQL database and hence it is throwing an error saying that cannot build a session factory.

Please see the error below:

 Caused by: java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO) 

which points to username not getting populated.

Please recheck system properties

dataSource.setUsername(System.getProperty("root"));

some packages seems to be missing as well pointing to a dependency issue:

package org.gjt.mm.mysql does not exist

Please run a mvn dependency:tree command to check for dependencies

Firebase cloud messaging notification not received by device

As if you want your app to run in > 24 versions too, follow these:

1.Add this in your strings.xml

< string name="default_notification_channel_id" translatable="false"> fcm_default_channel

  1. Add this meta-data in your manifest file:

< meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="@string/default_notification_channel_id" />

3.for creating notifications (with images) use this method where you are handling notifications, if directly then add in the firebasemessaging service or if you are using some util class then add in that util class :

   @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public static void createBigNotification(Bitmap bitmap, int icon, String message, Uri alarmSound) {
        final int NOTIFY_ID = 0; // ID of notification
        NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(NOTIFICATION_SERVICE);
        String id = mContext.getString(R.string.default_notification_channel_id); // default_channel_id
        String title = mContext.getString(R.string.app_name);
        Intent intent;
        NotificationCompat.Builder builder;
        if (notificationManager == null) {
            notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        }
        PendingIntent resultPendingIntent;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = notificationManager.getNotificationChannel(id);
            if (mChannel == null) {
                mChannel = new NotificationChannel(id, title, importance);
                mChannel.enableVibration(true);
                mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
                notificationManager.createNotificationChannel(mChannel);
            }
            builder = new NotificationCompat.Builder(mContext, id);
            intent = new Intent(mContext, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            resultPendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
            NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
            bigPictureStyle.setBigContentTitle(title);
            bigPictureStyle.setSummaryText(Html.fromHtml(message).toString());
            bigPictureStyle.bigPicture(bitmap);

            builder.setContentTitle(title)        // required
                    .setSmallIcon(R.drawable.app_icon)   // required
                    .setContentText(message) // required
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setAutoCancel(true)
                    .setSound(alarmSound)
                    .setStyle(bigPictureStyle)
                    .setContentIntent(resultPendingIntent)
                    .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
                    .setTicker(title)
                    .setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
        } else {
            builder = new NotificationCompat.Builder(mContext, id);
            intent = new Intent(mContext, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            resultPendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
            NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
            bigPictureStyle.setBigContentTitle(title);
            bigPictureStyle.setSummaryText(Html.fromHtml(message).toString());
            bigPictureStyle.bigPicture(bitmap);

            builder.setContentTitle(title)     // required
                    .setSmallIcon(R.drawable.app_icon)   // required
                    .setContentText(message) // required
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setAutoCancel(true)
                    .setSound(alarmSound)
                    .setStyle(bigPictureStyle)
                    .setContentIntent(resultPendingIntent)
                    .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
                    .setTicker(title)
                    .setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
                    .setPriority(Notification.PRIORITY_HIGH);
        }
        Notification notification = builder.build();
        notificationManager.notify(NOTIFY_ID, notification);
    }

Follow these steps and your notification will come in the notification tray.

Differences between ConstraintLayout and RelativeLayout

The Conclusion I can make is

1) We can do UI design without touching the xml part of code, to be honest I feel google has copied how UI is designed in iOS apps, it will make sense if you are familiar with UI development in iOS, but in relative layout its hard to set the constraints without touching the xml design.

2) Secondly it has flat view hierarchy unlike other layouts, so does better performance than relative layout which you might have seen from other answers

3) It also have extra things apart from what relative layout has, such as circular relative positioning where we can position another view relative to this one at certain radius with certain angle which cant do in relative layout

I am saying it again, designing UI using constraint layout is same as designing UI in iOS, so in future if you work on iOS you will find it easier if you have used constraint layout

Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432?

This worked for me: run

sudo lsof -i :<port_number>

after that it will display the PID which is currently attached to the process.

After that run sudo kill -9 <PID>

if that doesn't work, try the solution offered by user8376606 it would definitely work!

Could not find method android() for arguments

guys. I had the same problem before when I'm trying import a .aar package into my project, and unfortunately before make the .aar package as a module-dependence of my project, I had two modules (one about ROS-ANDROID-CV-BRIDGE, one is OPENCV-FOR-ANDROID) already. So, I got this error as you guys meet:

Error:Could not find method android() for arguments [org.ros.gradle_plugins.RosAndroidPlugin$_apply_closure2_closure4@7e550e0e] on project ‘:xxx’ of type org.gradle.api.Project.

So, it's the painful gradle-structure caused this problem when you have several modules in your project, and worse, they're imported in different way or have different types (.jar/.aar packages or just a project of Java library). And it's really a headache matter to make the configuration like compile-version, library dependencies etc. in each subproject compatible with the main-project.

I solved my problem just follow this steps:

? Copy .aar package in app/libs.

? Add this in app/build.gradle file:

repositories {
    flatDir {
        dirs 'libs' //this way we can find the .aar file in libs folder
    }
}

? Add this in your add build.gradle file of the module which you want to apply the .aar dependence (in my situation, just add this in my app/build.gradle file):

dependencies {
    compile(name:'package_name', ext:'aar')
}

So, if it's possible, just try export your module-dependence as a .aar package, and then follow this way import it to your main-project. Anyway, I hope this can be a good suggestion and would solve your problem if you have the same situation with me.

Checkbox value true/false

To return true or false depending on whether a checkbox is checked or not, I use this in JQuery

let checkState = $("#checkboxId").is(":checked") ? "true" : "false";

How to validate phone number in laravel 5.2?

One possible solution would to use regex.

'phone' => 'required|regex:/(01)[0-9]{9}/'

This will check the input starts with 01 and is followed by 9 numbers. By using regex you don't need the numeric or size validation rules.

If you want to reuse this validation method else where, it would be a good idea to create your own validation rule for validating phone numbers.

Docs: Custom Validation

In your AppServiceProvider's boot method:

Validator::extend('phone_number', function($attribute, $value, $parameters)
{
    return substr($value, 0, 2) == '01';
});

This will allow you to use the phone_number validation rule anywhere in your application, so your form validation could be:

'phone' => 'required|numeric|phone_number|size:11'

In your validator extension you could also check if the $value is numeric and 11 characters long.

Running Node.Js on Android

Dory - node.js

Great New Application
No Need to root your Phone and You Can Run your js File From anywere.

  • node.js runtime(run ES2015/ES6, ES2016 javascript and node.js APIs in android)
  • API Documents and instant code run from doc
  • syntax highlighting code editor
  • npm supports
  • linux terminal(toybox 0.7.4). node.js REPL and npm command in shell (add '--no-bin-links' option if you execute npm in /sdcard)
  • StartOnBoot / LiveReload
  • native node.js binary and npm are included. no need to be online.

Update instruction to node js 8 (async await)

  1. Download node.js v8.3.0 arm zip file and unzip.

  2. copy 'node' to android's sdcard(/sdcard or /sdcard/path/to/...)

  3. open the shell(check it out in the app's menu)

  4. cd /data/user/0/io.tmpage.dorynode/files/bin (or, just type cd && cd .. && cd files/bin )

  5. rm node

  6. cp /sdcard/node .

  7. (chmod a+x node

(https://play.google.com/store/apps/details?id=io.tempage.dorynode&hl=en)

Is there a way to specify which pytest tests to run from a file?

According to the doc about Run tests by node ids

since you have all node ids in foo.txt, just run

pytest `cat foo.txt | tr '\n' ' '`

this is same with below command (with file content in the question)

pytest tests_directory/foo.py::test_001 tests_directory/bar.py::test_some_other_test

PostgreSQL INSERT ON CONFLICT UPDATE (upsert) use all excluded values

Postgres hasn't implemented an equivalent to INSERT OR REPLACE. From the ON CONFLICT docs (emphasis mine):

It can be either DO NOTHING, or a DO UPDATE clause specifying the exact details of the UPDATE action to be performed in case of a conflict.

Though it doesn't give you shorthand for replacement, ON CONFLICT DO UPDATE applies more generally, since it lets you set new values based on preexisting data. For example:

INSERT INTO users (id, level)
VALUES (1, 0)
ON CONFLICT (id) DO UPDATE
SET level = users.level + 1;

Angular2 get clicked element id

There is no need to pass the entire event (unless you need other aspects of the event than you have stated). In fact, it is not recommended. You can pass the element reference with just a little modification.

import {Component} from 'angular2/core';

@Component({
  selector: 'my-app',
  template: `
    <button #btn1 (click)="toggle(btn1)" class="someclass" id="btn1">Button 1</button>
    <button #btn2 (click)="toggle(btn2)" class="someclass" id="btn2">Button 2</button>
  `
})
export class AppComponent {
  buttonValue: string;

  toggle(button) {
    this.buttonValue = button.id;
  }

}

StackBlitz demo

Technically, you don't need to find the button that was clicked, because you have passed the actual element.

Angular guidance

Format date as dd/MM/yyyy using pipes

You can achieve this using by a simple custom pipe.

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

@Pipe({
    name: 'dateFormatPipe',
})
export class dateFormatPipe implements PipeTransform {
    transform(value: string) {
       var datePipe = new DatePipe("en-US");
        value = datePipe.transform(value, 'dd/MM/yyyy');
        return value;
    }
}


{{currentDate | dateFormatPipe }}

Advantage of using a custom pipe is that, if you want to update the date format in future, you can go and update your custom pipe and it will reflect every where.

Custom Pipe examples

SSL: CERTIFICATE_VERIFY_FAILED with Python3

On Debian 9 I had to:

$ sudo update-ca-certificates --fresh
$ export SSL_CERT_DIR=/etc/ssl/certs

I'm not sure why, but this enviroment variable was never set.

How to know elastic search installed version from kibana?

from the Chrome Rest client make a GET request or curl -XGET 'http://localhost:9200' in console

rest client: http://localhost:9200

{
    "name": "node",
    "cluster_name": "elasticsearch-cluster",
    "version": {
        "number": "2.3.4",
        "build_hash": "dcxbgvzdfbbhfxbhx",
        "build_timestamp": "2016-06-30T11:24:31Z",
        "build_snapshot": false,
        "lucene_version": "5.5.0"
    },
    "tagline": "You Know, for Search"
}

where number field denotes the elasticsearch version. Here elasticsearch version is 2.3.4

TypeError: tuple indices must be integers, not str

SQlite3 has a method named row_factory. This method would allow you to access the values by column name.

https://www.kite.com/python/examples/3884/sqlite3-use-a-row-factory-to-access-values-by-column-name

How to change the Jupyter start-up folder

I just had the same problem and tested the methods mentioned above. After several trials, I realized that they are partially correct and are not the complete solution. I tested the below in Windows 10 and Anaconda 4.4.0 with python 3.6.

There are two ways to do even though they have only very small difference. Follow the way marneylc suggested above: i.e.

1) Open "Anaconda Prompt" and type jupyter notebook --generate-config

2) You find the file in C:\Users\username\.jupyter\jupyter_notebook_config.py

3) Change the line of #c.NotebookApp.notebook_dir = '' to c.NotebookApp.notebook_dir = 'c:\test\your_root\'

4) Then, go to the shortcut of Jupyter Notebook located in C:\Users\User_name\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Anaconda3 (64-bit)

5) Do the right click and go to the Properties

6) In the Target field, remove %USERPROFILE% as stenlytw suggested above.

7) Then, In the field of Start in, type the same directory of c:\test\your_root\ in jupyter_notebook_config.py

8) Done!

As the simpler way, after step 3, go to C:\Users\User_name\Anaconda3\Scripts

4-2) You can see the file of jupyter-notebook.exe and click it.

5-2) Then, the Jupyter start the folder you specified in jupyter_notebook_config.py. So make the shortcut of this file.

6-2) Done.

Async await in linq select

Existing code is working, but is blocking the thread.

.Select(async ev => await ProcessEventAsync(ev))

creates a new Task for every event, but

.Select(t => t.Result)

blocks the thread waiting for each new task to end.

In the other hand your code produce the same result but keeps asynchronous.

Just one comment on your first code. This line

var tasks = await Task.WhenAll(events...

will produce a single Task<TResult[]> so the variable should be named in singular.

Finally your last code make the same but is more succinct.

For reference: Task.Wait / Task.WhenAll

How to get user's high resolution profile picture on Twitter?

for me the "workaround" solution was to remove the "_normal" from the end of the string

Check it out below:

HTTP 415 unsupported media type error when calling Web API 2 endpoint

In my case it is Asp.Net Core 3.1 API. I changed the HTTP GET method from public ActionResult GetValidationRulesForField( GetValidationRulesForFieldDto getValidationRulesForFieldDto) to public ActionResult GetValidationRulesForField([FromQuery] GetValidationRulesForFieldDto getValidationRulesForFieldDto) and its working.

How to install Android SDK on Ubuntu?

There is no need to download any binaries or files or follow difficult installation instructions.

All you really needed to do is:

sudo apt update && sudo apt install android-sdk

Update: Ubuntu 18.04 only

Why is my JQuery selector returning a n.fn.init[0], and what is it?

Another approach(Inside of $function to asure that the each is executed on document ready):

var ids = [1,2];
$(function(){
  $('.checkbox-wrapper>input[type="checkbox"]').each(function(i,item){
    if(ids.indexOf($(item).data('id')) > -1){
       $(item).prop("checked", "checked");
    }
  });
});

Working fiddle: https://jsfiddle.net/robertrozas/w5uda72v/

What is the n.fn.init[0], and why it is returned? Why are my two seemingly identical JQuery functions returning different things?

Answer: It seems that your elements are not in the DOM yet, when you are trying to find them. As @Rory McCrossan pointed out, the length:0 means that it doesn't find any element based on your search criteria.

About n.fn.init[0], lets look at the core of the Jquery Library:

var jQuery = function( selector, context ) {
   return new jQuery.fn.init( selector, context );
};

Looks familiar, right?, now in a minified version of jquery, this should looks like:

var n = function( selector, context ) {
   return new n.fn.init( selector, context );
};

So when you use a selector you are creating an instance of the jquery function; when found an element based on the selector criteria it returns the matched elements; when the criteria does not match anything it returns the prototype object of the function.

How to send an HTTP request with a header parameter?

With your own Code and a Slight Change withou jQuery,

function testingAPI(){ 
    var key = "8a1c6a354c884c658ff29a8636fd7c18"; 
    var url = "https://api.fantasydata.net/nfl/v2/JSON/PlayerSeasonStats/2015";
    console.log(httpGet(url,key)); 
}


function httpGet(url,key){
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", url, false );
    xmlHttp.setRequestHeader("Ocp-Apim-Subscription-Key",key);
    xmlHttp.send(null);
    return xmlHttp.responseText;
}

Thank You

Using NotNull Annotation in method argument

@Nullable and @NotNull do nothing on their own. They are supposed to act as Documentation tools.

The @Nullable Annotation reminds you about the necessity to introduce an NPE check when:

  1. Calling methods that can return null.
  2. Dereferencing variables (fields, local variables, parameters) that can be null.

The @NotNull Annotation is, actually, an explicit contract declaring the following:

  1. A method should not return null.
  2. A variable (like fields, local variables, and parameters) cannot should not hold null value.

For example, instead of writing:

/**
 * @param aX should not be null
 */
public void setX(final Object aX ) {
    // some code
}

You can use:

public void setX(@NotNull final Object aX ) {
    // some code
}

Additionally, @NotNull is often checked by ConstraintValidators (eg. in spring and hibernate).

The @NotNull annotation doesn't do any validation on its own because the annotation definition does not provide any ConstraintValidator type reference.

For more info see:

  1. Bean validation
  2. NotNull.java
  3. Constraint.java
  4. ConstraintValidator.java

How to add header row to a pandas DataFrame

You can use names directly in the read_csv

names : array-like, default None List of column names to use. If file contains no header row, then you should explicitly pass header=None

Cov = pd.read_csv("path/to/file.txt", 
                  sep='\t', 
                  names=["Sequence", "Start", "End", "Coverage"])

What does from __future__ import absolute_import actually do?

The changelog is sloppily worded. from __future__ import absolute_import does not care about whether something is part of the standard library, and import string will not always give you the standard-library module with absolute imports on.

from __future__ import absolute_import means that if you import string, Python will always look for a top-level string module, rather than current_package.string. However, it does not affect the logic Python uses to decide what file is the string module. When you do

python pkg/script.py

pkg/script.py doesn't look like part of a package to Python. Following the normal procedures, the pkg directory is added to the path, and all .py files in the pkg directory look like top-level modules. import string finds pkg/string.py not because it's doing a relative import, but because pkg/string.py appears to be the top-level module string. The fact that this isn't the standard-library string module doesn't come up.

To run the file as part of the pkg package, you could do

python -m pkg.script

In this case, the pkg directory will not be added to the path. However, the current directory will be added to the path.

You can also add some boilerplate to pkg/script.py to make Python treat it as part of the pkg package even when run as a file:

if __name__ == '__main__' and __package__ is None:
    __package__ = 'pkg'

However, this won't affect sys.path. You'll need some additional handling to remove the pkg directory from the path, and if pkg's parent directory isn't on the path, you'll need to stick that on the path too.

Gradle Error:Execution failed for task ':app:processDebugGoogleServices'

In my case i have multiple product flavors. It used to work earlier. It stopped working after updating project gradle version to 4.0.1 and 'google-services:4.3.4'.

I got error like 'Task :app:processDebugGoogleServices FAILED' when i run the project.

I replaced 'google-services.json' in app module with 'my-product-flavor/google-services.json'. It is working fine now.

Can a website detect when you are using Selenium with chromedriver?

Additionally to the great answer of Erti-Chris Eelmaa - there's annoying window.navigator.webdriver and it is read-only. Event if you change the value of it to false it will still have true. That's why the browser driven by automated software can still be detected.

MDN

The variable is managed by the flag --enable-automation in chrome. The chromedriver launches Chrome with that flag and Chrome sets the window.navigator.webdriver to true. You can find it here. You need to add to "exclude switches" the flag. For instance (Go):

package main

import (
    "github.com/tebeka/selenium"
    "github.com/tebeka/selenium/chrome"
)

func main() {

caps := selenium.Capabilities{
    "browserName": "chrome",
}

chromeCaps := chrome.Capabilities{
    Path:            "/path/to/chrome-binary",
    ExcludeSwitches: []string{"enable-automation"},
}
caps.AddChrome(chromeCaps)

wd, err := selenium.NewRemote(caps, fmt.Sprintf("http://localhost:%d/wd/hub", 4444))
}

How to uninstall jupyter

If you installed Jupiter notebook through anaconda, this may help you:

conda uninstall jupyter notebook

COPYing a file in a Dockerfile, no such file or directory?

I had this problem even though my source directory was in the correct build context. Found the reason was that my source directory was a symbolic link to a location outside the build context.

For example my Dockerfile contains the following:

COPY dir1 /tmp

If dir1 is a symbolic link the COPY command is not working in my case.

How link to any local file with markdown syntax?

After messing around with @BringBackCommodore64 answer I figured it out

[link](file:///d:/absolute.md)    # absolute filesystem path
[link](./relative1.md)            # relative to opened file
[link](/relativeToProject.md)     # relative to opened project

All of them tested in Visual Studio Code and working,

Note: The absolute path works in editor but doesn't work in markdown preview mode!

Logging with Retrofit 2

I was also stuck in similar kind of situation, setLevel() method was not coming, when I was trying to call it with the instance of HttpLoggingInterceptor, like this:

HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

Here is how I resolved it, to generate log for Retrofit2,

I suppose you have added the dependecy,

implementation "com.squareup.okhttp3:logging-interceptor:4.7.2"

For the latest version you can check out, this link:

https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor )

Here they have also explained about how to add.

I created a class with name AddLoggingInterceptor, here is my code,

public class AddLoggingInterceptor {

    public static OkHttpClient setLogging(){
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .build();

        return okHttpClient;
    }
}

Then, where we are instantiating our Retrofit,

 public static Retrofit getRetrofitInstance() {
    if (retrofit == null) {
        retrofit = new retrofit2.Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(AddLoggingInterceptor.setLogging()) // here the method is called inside client() method, with the name of class, since it is a static method.
                .build();
    }
    return retrofit;
}

Now you can see log generated in your Android Studio, you may need to search, okHttp for filtering process. It worked for me. If any issues you can text me here.

Explain ggplot2 warning: "Removed k rows containing missing values"

Even if your data falls within your specified limits (e.g. c(0, 335)), adding a geom_jitter() statement could push some points outside those limits, producing the same error message.

library(ggplot2)

range(mtcars$hp)
#> [1]  52 335

# No jitter -- no error message
ggplot(mtcars, aes(mpg, hp)) + 
    geom_point() +
    scale_y_continuous(limits=c(0,335))


# Jitter is too large -- this generates the error message
ggplot(mtcars, aes(mpg, hp)) + 
    geom_point() +
    geom_jitter(position = position_jitter(w = 0.2, h = 0.2)) +
    scale_y_continuous(limits=c(0,335))
#> Warning: Removed 1 rows containing missing values (geom_point).

Created on 2020-08-24 by the reprex package (v0.3.0)

What are NR and FNR and what does "NR==FNR" imply?

Look up NR and FNR in the awk manual and then ask yourself what is the condition under which NR==FNR in the following example:

$ cat file1
a
b
c

$ cat file2
d
e

$ awk '{print FILENAME, NR, FNR, $0}' file1 file2
file1 1 1 a
file1 2 2 b
file1 3 3 c
file2 4 1 d
file2 5 2 e

Git push: "fatal 'origin' does not appear to be a git repository - fatal Could not read from remote repository."

Sometimes you don't have a local REF for pushing that branch back to the origin.
Try

git push origin master:master

This explicitly indicates which branch to push to (and from)

What exactly is std::atomic?

std::atomic exists because many ISAs have direct hardware support for it

What the C++ standard says about std::atomic has been analyzed in other answers.

So now let's see what std::atomic compiles to to get a different kind of insight.

The main takeaway from this experiment is that modern CPUs have direct support for atomic integer operations, for example the LOCK prefix in x86, and std::atomic basically exists as a portable interface to those intructions: What does the "lock" instruction mean in x86 assembly? In aarch64, LDADD would be used.

This support allows for faster alternatives to more general methods such as std::mutex, which can make more complex multi-instruction sections atomic, at the cost of being slower than std::atomic because std::mutex it makes futex system calls in Linux, which is way slower than the userland instructions emitted by std::atomic, see also: Does std::mutex create a fence?

Let's consider the following multi-threaded program which increments a global variable across multiple threads, with different synchronization mechanisms depending on which preprocessor define is used.

main.cpp

#include <atomic>
#include <iostream>
#include <thread>
#include <vector>

size_t niters;

#if STD_ATOMIC
std::atomic_ulong global(0);
#else
uint64_t global = 0;
#endif

void threadMain() {
    for (size_t i = 0; i < niters; ++i) {
#if LOCK
        __asm__ __volatile__ (
            "lock incq %0;"
            : "+m" (global),
              "+g" (i) // to prevent loop unrolling
            :
            :
        );
#else
        __asm__ __volatile__ (
            ""
            : "+g" (i) // to prevent he loop from being optimized to a single add
            : "g" (global)
            :
        );
        global++;
#endif
    }
}

int main(int argc, char **argv) {
    size_t nthreads;
    if (argc > 1) {
        nthreads = std::stoull(argv[1], NULL, 0);
    } else {
        nthreads = 2;
    }
    if (argc > 2) {
        niters = std::stoull(argv[2], NULL, 0);
    } else {
        niters = 10;
    }
    std::vector<std::thread> threads(nthreads);
    for (size_t i = 0; i < nthreads; ++i)
        threads[i] = std::thread(threadMain);
    for (size_t i = 0; i < nthreads; ++i)
        threads[i].join();
    uint64_t expect = nthreads * niters;
    std::cout << "expect " << expect << std::endl;
    std::cout << "global " << global << std::endl;
}

GitHub upstream.

Compile, run and disassemble:

comon="-ggdb3 -O3 -std=c++11 -Wall -Wextra -pedantic main.cpp -pthread"
g++ -o main_fail.out                    $common
g++ -o main_std_atomic.out -DSTD_ATOMIC $common
g++ -o main_lock.out       -DLOCK       $common

./main_fail.out       4 100000
./main_std_atomic.out 4 100000
./main_lock.out       4 100000

gdb -batch -ex "disassemble threadMain" main_fail.out
gdb -batch -ex "disassemble threadMain" main_std_atomic.out
gdb -batch -ex "disassemble threadMain" main_lock.out

Extremely likely "wrong" race condition output for main_fail.out:

expect 400000
global 100000

and deterministic "right" output of the others:

expect 400000
global 400000

Disassembly of main_fail.out:

   0x0000000000002780 <+0>:     endbr64 
   0x0000000000002784 <+4>:     mov    0x29b5(%rip),%rcx        # 0x5140 <niters>
   0x000000000000278b <+11>:    test   %rcx,%rcx
   0x000000000000278e <+14>:    je     0x27b4 <threadMain()+52>
   0x0000000000002790 <+16>:    mov    0x29a1(%rip),%rdx        # 0x5138 <global>
   0x0000000000002797 <+23>:    xor    %eax,%eax
   0x0000000000002799 <+25>:    nopl   0x0(%rax)
   0x00000000000027a0 <+32>:    add    $0x1,%rax
   0x00000000000027a4 <+36>:    add    $0x1,%rdx
   0x00000000000027a8 <+40>:    cmp    %rcx,%rax
   0x00000000000027ab <+43>:    jb     0x27a0 <threadMain()+32>
   0x00000000000027ad <+45>:    mov    %rdx,0x2984(%rip)        # 0x5138 <global>
   0x00000000000027b4 <+52>:    retq

Disassembly of main_std_atomic.out:

   0x0000000000002780 <+0>:     endbr64 
   0x0000000000002784 <+4>:     cmpq   $0x0,0x29b4(%rip)        # 0x5140 <niters>
   0x000000000000278c <+12>:    je     0x27a6 <threadMain()+38>
   0x000000000000278e <+14>:    xor    %eax,%eax
   0x0000000000002790 <+16>:    lock addq $0x1,0x299f(%rip)        # 0x5138 <global>
   0x0000000000002799 <+25>:    add    $0x1,%rax
   0x000000000000279d <+29>:    cmp    %rax,0x299c(%rip)        # 0x5140 <niters>
   0x00000000000027a4 <+36>:    ja     0x2790 <threadMain()+16>
   0x00000000000027a6 <+38>:    retq   

Disassembly of main_lock.out:

Dump of assembler code for function threadMain():
   0x0000000000002780 <+0>:     endbr64 
   0x0000000000002784 <+4>:     cmpq   $0x0,0x29b4(%rip)        # 0x5140 <niters>
   0x000000000000278c <+12>:    je     0x27a5 <threadMain()+37>
   0x000000000000278e <+14>:    xor    %eax,%eax
   0x0000000000002790 <+16>:    lock incq 0x29a0(%rip)        # 0x5138 <global>
   0x0000000000002798 <+24>:    add    $0x1,%rax
   0x000000000000279c <+28>:    cmp    %rax,0x299d(%rip)        # 0x5140 <niters>
   0x00000000000027a3 <+35>:    ja     0x2790 <threadMain()+16>
   0x00000000000027a5 <+37>:    retq

Conclusions:

  • the non-atomic version saves the global to a register, and increments the register.

    Therefore, at the end, very likely four writes happen back to global with the same "wrong" value of 100000.

  • std::atomic compiles to lock addq. The LOCK prefix makes the following inc fetch, modify and update memory atomically.

  • our explicit inline assembly LOCK prefix compiles to almost the same thing as std::atomic, except that our inc is used instead of add. Not sure why GCC chose add, considering that our INC generated a decoding 1 byte smaller.

ARMv8 could use either LDAXR + STLXR or LDADD in newer CPUs: How do I start threads in plain C?

Tested in Ubuntu 19.10 AMD64, GCC 9.2.1, Lenovo ThinkPad P51.

What exactly does numpy.exp() do?

exp(x) = e^x where e= 2.718281(approx)

import numpy as np

ar=np.array([1,2,3])
ar=np.exp(ar)
print ar

outputs:

[ 2.71828183  7.3890561  20.08553692]

Check if a file exists or not in Windows PowerShell?

Test-Path may give odd answer. E.g. "Test-Path c:\temp\ -PathType leaf" gives false, but "Test-Path c:\temp* -PathType leaf" gives true. Sad :(

LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1

LDAP is trying to authenticate with AD when sending a transaction to another server DB. This authentication fails because the user has recently changed her password, although this transaction was generated using the previous credentials. This authentication will keep failing until ... unless you change the transaction status to Complete or Cancel in which case LDAP will stop sending these transactions.

Module is not available, misspelled or forgot to load (but I didn't)

I found this question when I got the same error for a different reason.

My issue was that my Gulp hadn't picked up on the fact that I had declared a new module and I needed to manually re-run Gulp.

Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which?

There is a lot of confusion here, especially if you read outdated sources.

The basic one is Activity, which can show Fragments. You can use this combination if you're on Android version > 4.

However, there is also a support library which encompasses the other classes you mentioned: FragmentActivity, ActionBarActivity and AppCompat. Originally they were used to support fragments on Android versions < 4, but actually they're also used to backport functionality from newer versions of Android (material design for example).

The latest one is AppCompat, the other 2 are older. The strategy I use is to always use AppCompat, so that the app will be ready in case of backports from future versions of Android.

Excel doesn't update value unless I hit Enter

I have the same problem with that guy here: mrexcel.com/forum/excel-questions/318115-enablecalculation.html Application.CalculateFull sold my problem. However I am afraid if this will happen again. I will try not to use EnableCalculation again.

Logarithmic returns in pandas dataframe

Here is one way to calculate log return using .shift(). And the result is similar to but not the same as the gross return calculated by pct_change(). Can you upload a copy of your sample data (dropbox share link) to reproduce the inconsistency you saw?

import pandas as pd
import numpy as np

np.random.seed(0)
df = pd.DataFrame(100 + np.random.randn(100).cumsum(), columns=['price'])
df['pct_change'] = df.price.pct_change()
df['log_ret'] = np.log(df.price) - np.log(df.price.shift(1))

Out[56]: 
       price  pct_change  log_ret
0   101.7641         NaN      NaN
1   102.1642      0.0039   0.0039
2   103.1429      0.0096   0.0095
3   105.3838      0.0217   0.0215
4   107.2514      0.0177   0.0176
5   106.2741     -0.0091  -0.0092
6   107.2242      0.0089   0.0089
7   107.0729     -0.0014  -0.0014
..       ...         ...      ...
92  101.6160      0.0021   0.0021
93  102.5926      0.0096   0.0096
94  102.9490      0.0035   0.0035
95  103.6555      0.0069   0.0068
96  103.6660      0.0001   0.0001
97  105.4519      0.0172   0.0171
98  105.5788      0.0012   0.0012
99  105.9808      0.0038   0.0038

[100 rows x 3 columns]

How can I see function arguments in IPython Notebook Server 3?

Try Shift-Tab-Tab a bigger documentation appears, than with Shift-Tab. It's the same but you can scroll down.

Shift-Tab-Tab-Tab and the tooltip will linger for 10 seconds while you type.

Shift-Tab-Tab-Tab-Tab and the docstring appears in the pager (small part at the bottom of the window) and stays there.

reCAPTCHA ERROR: Invalid domain for site key

For me, I had simply forgotten to enter the actual domain name in the "Key Settings" area where it says Domains (one per line).

Flexbox: how to get divs to fill up 100% of the container width without wrapping?

To prevent the flex items from shrinking, set the flex shrink factor to 0:

The flex shrink factor determines how much the flex item will shrink relative to the rest of the flex items in the flex container when negative free space is distributed. When omitted, it is set to 1.

.boxcontainer .box {
  flex-shrink: 0;
}

_x000D_
_x000D_
* {_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
.wrapper {_x000D_
  width: 200px;_x000D_
  background-color: #EEEEEE;_x000D_
  border: 2px solid #DDDDDD;_x000D_
  padding: 1rem;_x000D_
}_x000D_
.boxcontainer {_x000D_
  position: relative;_x000D_
  left: 0;_x000D_
  border: 2px solid #BDC3C7;_x000D_
  transition: all 0.4s ease;_x000D_
  display: flex;_x000D_
}_x000D_
.boxcontainer .box {_x000D_
  width: 100%;_x000D_
  padding: 1rem;_x000D_
  flex-shrink: 0;_x000D_
}_x000D_
.boxcontainer .box:first-child {_x000D_
  background-color: #F47983;_x000D_
}_x000D_
.boxcontainer .box:nth-child(2) {_x000D_
  background-color: #FABCC1;_x000D_
}_x000D_
#slidetrigger:checked ~ .wrapper .boxcontainer {_x000D_
  left: -100%;_x000D_
}_x000D_
#overflowtrigger:checked ~ .wrapper {_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<input type="checkbox" id="overflowtrigger" />_x000D_
<label for="overflowtrigger">Hide overflow</label><br />_x000D_
<input type="checkbox" id="slidetrigger" />_x000D_
<label for="slidetrigger">Slide!</label>_x000D_
<div class="wrapper">_x000D_
  <div class="boxcontainer">_x000D_
    <div class="box">_x000D_
      First bunch of content._x000D_
    </div>_x000D_
    <div class="box">_x000D_
      Second load  of content._x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

beyond top level package error in relative import

In my humble opinion, I understand this question in this way:

[CASE 1] When you start an absolute-import like

python -m test_A.test

or

import test_A.test

or

from test_A import test

you're actually setting the import-anchor to be test_A, in other word, top-level package is test_A . So, when we have test.py do from ..A import xxx, you are escaping from the anchor, and Python does not allow this.

[CASE 2] When you do

python -m package.test_A.test

or

from package.test_A import test

your anchor becomes package, so package/test_A/test.py doing from ..A import xxx does not escape the anchor(still inside package folder), and Python happily accepts this.

In short:

  • Absolute-import changes current anchor (=redefines what is the top-level package);
  • Relative-import does not change the anchor but confines to it.

Furthermore, we can use full-qualified module name(FQMN) to inspect this problem.

Check FQMN in each case:

  • [CASE2] test.__name__ = package.test_A.test
  • [CASE1] test.__name__ = test_A.test

So, for CASE2, an from .. import xxx will result in a new module with FQMN=package.xxx, which is acceptable.

While for CASE1, the .. from within from .. import xxx will jump out of the starting node(anchor) of test_A, and this is NOT allowed by Python.

Why does Oracle not find oci.dll?

I notice that recent Oracle client installers change file permissions.

I had Oracle 12.0.1 32 bit client installed for a year. I recently installed Oracle 12.0.1 64 bit client. The Oracle install change ALL file permissions in the 32 bit folders.

My application suddenly failed to run.

I used PROCMON.EXE (https://docs.microsoft.com/en-us/sysinternals/downloads/) and noticed that permission was denied opening OCI.DLL

I changed the permissions for everything in the Oracle client folders and application works as expected.

Android Firebase, simply get one child object's data

You don't directly read a value. You can set it with .setValue(), but there is no .getValue() on the reference object.

You have to use a listener. If you just want to read the value once, you use ref.addListenerForSingleValueEvent().

Example:

Firebase ref = new Firebase("YOUR-URL-HERE/PATH/TO/YOUR/STUFF");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
   @Override
   public void onDataChange(DataSnapshot dataSnapshot) {
       String value = (String) dataSnapshot.getValue();

       // do your stuff here with value

   }

   @Override
   public void onCancelled(FirebaseError firebaseError) {

   }
});

Source: https://www.firebase.com/docs/android/guide/retrieving-data.html#section-reading-once

Oracle SQL - DATE greater than statement

You need to convert the string to date using the to_date() function

SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('31-Dec-2014','DD-MON-YYYY');

OR

SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('31 Dec 2014','DD MON YYYY');

OR

SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('2014-12-31','yyyy-MM-dd');

This will work only if OrderDate is stored in Date format. If it is Varchar you should apply to_date() func on that column also like

 SELECT * FROM OrderArchive
    WHERE to_date(OrderDate,'yyyy-Mm-dd') <= to_date('2014-12-31','yyyy-MM-dd');

Guzzlehttp - How get the body of a response from Guzzle 6?

Guzzle implements PSR-7. That means that it will by default store the body of a message in a Stream that uses PHP temp streams. To retrieve all the data, you can use casting operator:

$contents = (string) $response->getBody();

You can also do it with

$contents = $response->getBody()->getContents();

The difference between the two approaches is that getContents returns the remaining contents, so that a second call returns nothing unless you seek the position of the stream with rewind or seek .

$stream = $response->getBody();
$contents = $stream->getContents(); // returns all the contents
$contents = $stream->getContents(); // empty string
$stream->rewind(); // Seek to the beginning
$contents = $stream->getContents(); // returns all the contents

Instead, usings PHP's string casting operations, it will reads all the data from the stream from the beginning until the end is reached.

$contents = (string) $response->getBody(); // returns all the contents
$contents = (string) $response->getBody(); // returns all the contents

Documentation: http://docs.guzzlephp.org/en/latest/psr7.html#responses

How to solve : SQL Error: ORA-00604: error occurred at recursive SQL level 1

One possible explanation is a database trigger that fires for each DROP TABLE statement. To find the trigger, query the _TRIGGERS dictionary views:

select * from all_triggers
where trigger_type in ('AFTER EVENT', 'BEFORE EVENT')

disable any suspicious trigger with

   alter trigger <trigger_name> disable;

and try re-running your DROP TABLE statement

How does Content Security Policy (CSP) work?

Apache 2 mod_headers

You could also enable Apache 2 mod_headers. On Fedora it's already enabled by default. If you use Ubuntu/Debian, enable it like this:

# First enable headers module for Apache 2,
# and then restart the Apache2 service
a2enmod headers
apache2 -k graceful

On Ubuntu/Debian you can configure headers in the file /etc/apache2/conf-enabled/security.conf

#
# Setting this header will prevent MSIE from interpreting files as something
# else than declared by the content type in the HTTP headers.
# Requires mod_headers to be enabled.
#
#Header set X-Content-Type-Options: "nosniff"

#
# Setting this header will prevent other sites from embedding pages from this
# site as frames. This defends against clickjacking attacks.
# Requires mod_headers to be enabled.
#
Header always set X-Frame-Options: "sameorigin"
Header always set X-Content-Type-Options nosniff
Header always set X-XSS-Protection "1; mode=block"
Header always set X-Permitted-Cross-Domain-Policies "master-only"
Header always set Cache-Control "no-cache, no-store, must-revalidate"
Header always set Pragma "no-cache"
Header always set Expires "-1"
Header always set Content-Security-Policy: "default-src 'none';"
Header always set Content-Security-Policy: "script-src 'self' www.google-analytics.com adserver.example.com www.example.com;"
Header always set Content-Security-Policy: "style-src 'self' www.example.com;"

Note: This is the bottom part of the file. Only the last three entries are CSP settings.

The first parameter is the directive, the second is the sources to be white-listed. I've added Google analytics and an adserver, which you might have. Furthermore, I found that if you have aliases, e.g, www.example.com and example.com configured in Apache 2 you should add them to the white-list as well.

Inline code is considered harmful, and you should avoid it. Copy all the JavaScript code and CSS to separate files and add them to the white-list.

While you're at it you could take a look at the other header settings and install mod_security

Further reading:

https://developers.google.com/web/fundamentals/security/csp/

https://www.w3.org/TR/CSP/

How to add element in Python to the end of list using list.insert?

You'll have to pass the new ordinal position to insert using len in this case:

In [62]:

a=[1,2,3,4]
a.insert(len(a),5)
a
Out[62]:
[1, 2, 3, 4, 5]

Using an authorization header with Fetch in React Native

Example fetch with authorization header:

fetch('URL_GOES_HERE', { 
   method: 'post', 
   headers: new Headers({
     'Authorization': 'Basic '+btoa('username:password'), 
     'Content-Type': 'application/x-www-form-urlencoded'
   }), 
   body: 'A=1&B=2'
 });

How can I print out just the index of a pandas dataframe?

You can access the index attribute of a df using df.index[i]

>> import pandas as pd
>> import numpy as np
>> df = pd.DataFrame({'a':np.arange(5), 'b':np.random.randn(5)})
   a         b
0  0  1.088998
1  1 -1.381735
2  2  0.035058
3  3 -2.273023
4  4  1.345342

>> df.index[1] ## Second index
>> df.index[-1] ## Last index

>> for i in xrange(len(df)):print df.index[i] ## Using loop
... 
0
1
2
3
4

How do I jump to a closing bracket in Visual Studio Code?

For this, I installed an extension called TabOut. Pretty much does what the name suggests.

Chrome net::ERR_INCOMPLETE_CHUNKED_ENCODING error

I just wanted to share my experience with you if someone might has the same problem with MOODLE.

Our moodle platform was suddenly very slowly, the dashboard took about 2-3 times longer to load (up to 6 seconds) then usual and from time to time some pages didn't get loaded at all (not a 404 error but a blank page). In the Developer Tools Console the following error was visible: net::ERR_INCOMPLETE_CHUNKED_ENCODING.

Searching for this error, it looks like Chrome is the issue, but we had the problem with various browsers. After hours of research and comparing the databases from the days before I finally found the problem, someone turned the Event Monitoring on. However, in the "Config changes" log, this change wasn't visible! Turning Event Monitoring off, finally solved the problem - we had no rules defined for event monitoring.

We're running Moodle 3.1.2+ with MariaDB and PHP 5.4.

Error - replacement has [x] rows, data has [y]

The answer by @akrun certainly does the trick. For future googlers who want to understand why, here is an explanation...

The new variable needs to be created first.

The variable "valueBin" needs to be already in the df in order for the conditional assignment to work. Essentially, the syntax of the code is correct. Just add one line in front of the code chuck to create this name --

df$newVariableName <- NA

Then you continue with whatever conditional assignment rules you have, like

df$newVariableName[which(df$oldVariableName<=250)] <- "<=250"

I blame whoever wrote that package's error message... The debugging was made especially confusing by that error message. It is irrelevant information that you have two arrays in the df with different lengths. No. Simply create the new column first. For more details, consult this post https://www.r-bloggers.com/translating-weird-r-errors/

How to check if any value is NaN in a Pandas DataFrame

let df be the name of the Pandas DataFrame and any value that is numpy.nan is a null value.

  1. If you want to see which columns has nulls and which do not(just True and False)

    df.isnull().any()
    
  2. If you want to see only the columns that has nulls

    df.loc[:, df.isnull().any()].columns
    
  3. If you want to see the count of nulls in every column

    df.isna().sum()
    
  4. If you want to see the percentage of nulls in every column

    df.isna().sum()/(len(df))*100
    
  5. If you want to see the percentage of nulls in columns only with nulls:

df.loc[:,list(df.loc[:,df.isnull().any()].columns)].isnull().sum()/(len(df))*100

EDIT 1:

If you want to see where your data is missing visually:

import missingno
missingdata_df = df.columns[df.isnull().any()].tolist()
missingno.matrix(df[missingdata_df])

Convert Map to JSON using Jackson

If you're using jackson, better to convert directly to ObjectNode.

//not including SerializationFeatures for brevity
static final ObjectMapper mapper = new ObjectMapper();

//pass it your payload
public static ObjectNode convObjToONode(Object o) {
    StringWriter stringify = new StringWriter();
    ObjectNode objToONode = null;

    try {
        mapper.writeValue(stringify, o);
        objToONode = (ObjectNode) mapper.readTree(stringify.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.println(objToONode);
    return objToONode;
}

What exactly does the T and Z mean in timestamp?

The T doesn't really stand for anything. It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time.

The Z stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).

Both characters are just static letters in the format, which is why they are not documented by the datetime.strftime() method. You could have used Q or M or Monty Python and the method would have returned them unchanged as well; the method only looks for patterns starting with % to replace those with information from the datetime object.

Karma: Running a single test file from command line

First you need to start karma server with

karma start

Then, you can use grep to filter a specific test or describe block:

karma run -- --grep=testDescriptionFilter

Android Studio Run/Debug configuration error: Module not specified

I had the same issue after update on Android Studio 3.2.1 I had to re-import project, after that everything works

php codeigniter count rows

Try This :) I created my on model of count all results

in library_model

function count_all_results($column_name = array(),$where=array(), $table_name = array())
{
        $this->db->select($column_name);
        // If Where is not NULL
        if(!empty($where) && count($where) > 0 )
        {
            $this->db->where($where);
        }
        // Return Count Column
        return $this->db->count_all_results($table_name[0]);//table_name array sub 0
}

Your Controller will look like this

public function my_method()
{
  $data = array(
     $countall = $this->model->your_method_model()
  );
   $this->load->view('page',$data);
}

Then Simple Call The Library Model In Your Model

function your_method_model()
{
        return $this->library_model->count_all_results(
               ['id'],
               ['where],
               ['table name']
           );
}

Jquery-How to grey out the background while showing the loading icon over it

I reworked the example you provided in the js fiddle : http://jsfiddle.net/zravs3hp/

Step 1 :

I renamed your container div to overlay, as semantically this div is not a container, but an overlay. I also placed the loader div as a child of this overlay div.

The resulting html is :

<div class="overlay">
    <div id="loading-img"></div>
</div>


<div class="content">
    <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ea velit provident sint aliquid eos omnis aperiam officia architecto error incidunt nemo obcaecati adipisci doloremque dicta neque placeat natus beatae cupiditate minima ipsam quaerat explicabo non reiciendis qui sit. ...</div>
    <button id="button">Submit</button>
</div>

The css of the overlay is the following

.overlay {
    background: #e9e9e9;  <- I left your 'gray' background
    display: none;        <- Not displayed by default
    position: absolute;   <- This and the following properties will
    top: 0;                  make the overlay, the element will expand
    right: 0;                so as to cover the whole body of the page
    bottom: 0;
    left: 0;
    opacity: 0.5;
}

Step 2 :

I added some dummy text so as to have something to overlay.

Step 3 :

Then, in the click handler we just need to show the overlay :

$("#button").click(function () {
    $(".overlay").show();
});

How to use curl to get a GET request exactly same as using Chrome?

If you need to set the user header string in the curl request, you can use the -H option to set user agent like:

curl -H "user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36" http://stackoverflow.com/questions/28760694/how-to-use-curl-to-get-a-get-request-exactly-same-as-using-chrome

Updated user-agent form newest Chrome at 02-22-2021


Using a proxy tool like Charles Proxy really helps make short work of something like what you are asking. Here is what I do, using this SO page as an example (as of July 2015 using Charles version 3.10):

  1. Get Charles Proxy running
  2. Make web request using browser
  3. Find desired request in Charles Proxy
  4. Right click on request in Charles Proxy
  5. Select 'Copy cURL Request'

Copy cURL Request example in Charles 3.10.2

You now have a cURL request you can run in a terminal that will mirror the request your browser made. Here is what my request to this page looked like (with the cookie header removed):

curl -H "Host: stackoverflow.com" -H "Cache-Control: max-age=0" -H "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8" -H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.89 Safari/537.36" -H "HTTPS: 1" -H "DNT: 1" -H "Referer: https://www.google.com/" -H "Accept-Language: en-US,en;q=0.8,en-GB;q=0.6,es;q=0.4" -H "If-Modified-Since: Thu, 23 Jul 2015 20:31:28 GMT" --compressed http://stackoverflow.com/questions/28760694/how-to-use-curl-to-get-a-get-request-exactly-same-as-using-chrome

Why do I get PLS-00302: component must be declared when it exists?

I came here because I had the same problem.
What was the problem for me was that the procedure was defined in the package body, but not in the package header.
I was executing my function with a lose BEGIN END statement.

What exactly is the difference between Web API and REST API in MVC?

I have been there, like so many of us. There are so many confusing words like Web API, REST, RESTful, HTTP, SOAP, WCF, Web Services... and many more around this topic. But I am going to give brief explanation of only those which you have asked.

REST

It is neither an API nor a framework. It is just an architectural concept. You can find more details here.

RESTful

I have not come across any formal definition of RESTful anywhere. I believe it is just another buzzword for APIs to say if they comply with REST specifications.

EDIT: There is another trending open source initiative OpenAPI Specification (OAS) (formerly known as Swagger) to standardise REST APIs.

Web API

It in an open source framework for writing HTTP APIs. These APIs can be RESTful or not. Most HTTP APIs we write are not RESTful. This framework implements HTTP protocol specification and hence you hear terms like URIs, request/response headers, caching, versioning, various content types(formats).

Note: I have not used the term Web Services deliberately because it is a confusing term to use. Some people use this as a generic concept, I preferred to call them HTTP APIs. There is an actual framework named 'Web Services' by Microsoft like Web API. However it implements another protocol called SOAP.

Converting rows into columns and columns into rows using R

Here is a tidyverse option that might work depending on the data, and some caveats on its usage:

library(tidyverse)

starting_df %>% 
  rownames_to_column() %>% 
  gather(variable, value, -rowname) %>% 
  spread(rowname, value)

rownames_to_column() is necessary if the original dataframe has meaningful row names, otherwise the new column names in the new transposed dataframe will be integers corresponding to the orignal row number. If there are no meaningful row names you can skip rownames_to_column() and replace rowname with the name of the first column in the dataframe, assuming those values are unique and meaningful. Using the tidyr::smiths sample data would be:

smiths %>% 
    gather(variable, value, -subject) %>% 
    spread(subject, value)

Using the example starting_df with the tidyverse approach will throw a warning message about dropping attributes. This is related to converting columns with different attribute types into a single character column. The smiths data will not give that warning because all columns except for subject are doubles.

The earlier answer using as.data.frame(t()) will convert everything to a factor if there are mixed column types unless stringsAsFactors = FALSE is added, whereas the tidyverse option converts everything to a character by default if there are mixed column types.

Refreshing data in RecyclerView and keeping its scroll position

Here is an option for people who use DataBinding for RecyclerView. I have var recyclerViewState: Parcelable? in my adapter. And I use a BindingAdapter with a variation of @DawnYu's answer to set and update data in the RecyclerView:

@BindingAdapter("items")
fun setRecyclerViewItems(
    recyclerView: RecyclerView,
    items: List<RecyclerViewItem>?
) {
    var adapter = (recyclerView.adapter as? RecyclerViewAdapter)
    if (adapter == null) {
        adapter = RecyclerViewAdapter()
        recyclerView.adapter = adapter
    }

    adapter.recyclerViewState = recyclerView.layoutManager?.onSaveInstanceState()
    // the main idea is in this call with a lambda. It allows to avoid blinking on data update
    adapter.submitList(items.orEmpty()) {
        adapter.recyclerViewState?.let {
            recyclerView.layoutManager?.onRestoreInstanceState(it)
        }
    }
}

Finally, the XML part looks like:

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/possible_trips_rv"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    app:items="@{viewState.yourItems}"
    app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"/>

How does the Spring @ResponseBody annotation work?

First of all, the annotation doesn't annotate List. It annotates the method, just as RequestMapping does. Your code is equivalent to

@RequestMapping(value="/orders", method=RequestMethod.GET)
@ResponseBody
public List<Account> accountSummary() {
    return accountManager.getAllAccounts();
}

Now what the annotation means is that the returned value of the method will constitute the body of the HTTP response. Of course, an HTTP response can't contain Java objects. So this list of accounts is transformed to a format suitable for REST applications, typically JSON or XML.

The choice of the format depends on the installed message converters, on the values of the produces attribute of the @RequestMapping annotation, and on the content type that the client accepts (that is available in the HTTP request headers). For example, if the request says it accepts XML, but not JSON, and there is a message converter installed that can transform the list to XML, then XML will be returned.

Fatal error: Call to a member function prepare() on null

You can try/catch PDOExceptions (your configs could differ but the important part is the try/catch):

try {
        $dbh = new PDO(
            DB_TYPE . ':host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET,
            DB_USER,
            DB_PASS,
            [
                PDO::ATTR_PERSISTENT            => true,
                PDO::ATTR_ERRMODE               => PDO::ERRMODE_EXCEPTION,
                PDO::MYSQL_ATTR_INIT_COMMAND    => 'SET NAMES ' . DB_CHARSET . ' COLLATE ' . DB_COLLATE

            ]
        );
    } catch ( PDOException $e ) {
        echo 'ERROR!';
        print_r( $e );
    }

The print_r( $e ); line will show you everything you need, for example I had a recent case where the error message was like unknown database 'my_db'.

How do I get HTTP Request body content in Laravel?

I don't think you want the data from your Request, I think you want the data from your Response. The two are different. Also you should build your response correctly in your controller.

Looking at the class in edit #2, I would make it look like this:

class XmlController extends Controller
{
    public function index()
    {
        $content = Request::all();
        return Response::json($content);
    }
}

Once you've gotten that far you should check the content of your response in your test case (use print_r if necessary), you should see the data inside.

More information on Laravel responses here:

http://laravel.com/docs/5.0/responses

What does question mark and dot operator ?. mean in C# 6.0?

It's the null conditional operator. It basically means:

"Evaluate the first operand; if that's null, stop, with a result of null. Otherwise, evaluate the second operand (as a member access of the first operand)."

In your example, the point is that if a is null, then a?.PropertyOfA will evaluate to null rather than throwing an exception - it will then compare that null reference with foo (using string's == overload), find they're not equal and execution will go into the body of the if statement.

In other words, it's like this:

string bar = (a == null ? null : a.PropertyOfA);
if (bar != foo)
{
    ...
}

... except that a is only evaluated once.

Note that this can change the type of the expression, too. For example, consider FileInfo.Length. That's a property of type long, but if you use it with the null conditional operator, you end up with an expression of type long?:

FileInfo fi = ...; // fi could be null
long? length = fi?.Length; // If fi is null, length will be null

How to push a docker image to a private repository

Following are the steps to push Docker Image to Private Repository of DockerHub

1- First check Docker Images using command

docker images

2- Check Docker Tag command Help

docker tag help

3- Now Tag a name to your created Image

docker tag localImgName:tagName DockerHubUser\Private-repoName:tagName(tag name is optional. Default name is latest)

4- Before pushing Image to DockerHub Private Repo, first login to DockerHub using command

docker login [provide dockerHub username and Password to login]

5- Now push Docker Image to your private Repo using command

docker push [options] ImgName[:tag] e.g docker push DockerHubUser\Private-repoName:tagName

6- Now navigate to the DockerHub Private Repo and you will see Docker image is pushed on your private Repository with name written as TagName in previous steps

Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script

I have encountered this problem twice. First time I used VS 2013 and the second time I used VS 2015 with different solution. The first solution on VS 2013 and python 2.7 is:

  1. Click win+R
  2. Enter SET VS90COMNTOOLS=%VS120COMNTOOLS%
  3. Close all windows
  4. Enter pip install again

Now, one year later, I have found an easier method to fix it. This time I use VS 2015 and python 3.4.

  1. Right click on My Computer.
  2. Click Properties
  3. Advanced system settings
  4. Environment variables
  5. Add New system variable
  6. Enter VS100COMNTOOLSto the variable name
  7. Enter the value of VS140COMNTOOLSto the new variable.
  8. Close all windows

Now I'm sure you will ask some question what is the VSXXXCOMNTOOLSand what should I do if I use VS2008 or other compiler.

There is a file python\Lib\distutils\msvc9compiler.py, beginning on line 216 we see

def find_vcvarsall(version):
    """Find the vcvarsall.bat file
    At first it tries to find the productdir of VS 2010 in the registry. If
    that fails it falls back to the VS100COMNTOOLS env var.
    """

It means that you must give the productdir of VS 2010 for it, so if you are using python 2.x and

  • Visual Studio 2010 (VS10):SET VS90COMNTOOLS=%VS100COMNTOOLS%
  • Visual Studio 2012 (VS11):SET VS90COMNTOOLS=%VS110COMNTOOLS%
  • Visual Studio 2013 (VS12):SET VS90COMNTOOLS=%VS120COMNTOOLS%
  • Visual Studio 2015 (VS15):SET VS90COMNTOOLS=%VS140COMNTOOLS%

or if you are using python 3.x and

  • Visual Studio 2010 (VS10):SET VS100COMNTOOLS=%VS100COMNTOOLS%
  • Visual Studio 2012 (VS11):SET VS100COMNTOOLS=%VS110COMNTOOLS%
  • Visual Studio 2013 (VS12):SET VS100COMNTOOLS=%VS120COMNTOOLS%
  • Visual Studio 2015 (VS15):SET VS100COMNTOOLS=%VS140COMNTOOLS%

And it's the same as adding a new system variable. See the second ways.

Update:Sometimes,it still doesn't work.Check your path,ensure that contains VSxxxCOMNTOOLS

How do I get the current timezone name in Postgres 9.3?

You can access the timezone by the following script:

SELECT * FROM pg_timezone_names WHERE name = current_setting('TIMEZONE');
  • current_setting('TIMEZONE') will give you Continent / Capital information of settings
  • pg_timezone_names The view pg_timezone_names provides a list of time zone names that are recognized by SET TIMEZONE, along with their associated abbreviations, UTC offsets, and daylight-savings status.
  • name column in a view (pg_timezone_names) is time zone name.

output will be :

name- Europe/Berlin, 
abbrev - CET, 
utc_offset- 01:00:00, 
is_dst- false

How to configure Docker port mapping to use Nginx as an upstream proxy?

Just found an article from Anand Mani Sankar wich shows a simple way of using nginx upstream proxy with docker composer.

Basically one must configure the instance linking and ports at the docker-compose file and update upstream at nginx.conf accordingly.

Understanding passport serialize deserialize

  1. Where does user.id go after passport.serializeUser has been called?

The user id (you provide as the second argument of the done function) is saved in the session and is later used to retrieve the whole object via the deserializeUser function.

serializeUser determines which data of the user object should be stored in the session. The result of the serializeUser method is attached to the session as req.session.passport.user = {}. Here for instance, it would be (as we provide the user id as the key) req.session.passport.user = {id: 'xyz'}

  1. We are calling passport.deserializeUser right after it where does it fit in the workflow?

The first argument of deserializeUser corresponds to the key of the user object that was given to the done function (see 1.). So your whole object is retrieved with help of that key. That key here is the user id (key can be any key of the user object i.e. name,email etc). In deserializeUser that key is matched with the in memory array / database or any data resource.

The fetched object is attached to the request object as req.user

Visual Flow

passport.serializeUser(function(user, done) {
    done(null, user.id);
});              ¦
                 ¦ 
                 ¦
                 +--------------------? saved to session
                                   ¦    req.session.passport.user = {id: '..'}
                                   ¦
                                   ?           
passport.deserializeUser(function(id, done) {
                   +---------------+
                   ¦
                   ? 
    User.findById(id, function(err, user) {
        done(err, user);
    });            +--------------? user object attaches to the request as req.user   
});

Am I trying to connect to a TLS-enabled daemon without TLS?

Make sure the Docker daemon is running:

service docker start

That fixed it for me!

You cannot call a method on a null-valued expression

The simple answer for this one is that you have an undeclared (null) variable. In this case it is $md5. From the comment you put this needed to be declared elsewhere in your code

$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider

The error was because you are trying to execute a method that does not exist.

PS C:\Users\Matt> $md5 | gm


   TypeName: System.Security.Cryptography.MD5CryptoServiceProvider

Name                       MemberType Definition                                                                                                                            
----                       ---------- ----------                                                                                                                            
Clear                      Method     void Clear()                                                                                                                          
ComputeHash                Method     byte[] ComputeHash(System.IO.Stream inputStream), byte[] ComputeHash(byte[] buffer), byte[] ComputeHash(byte[] buffer, int offset, ...

The .ComputeHash() of $md5.ComputeHash() was the null valued expression. Typing in gibberish would create the same effect.

PS C:\Users\Matt> $bagel.MakeMeABagel()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $bagel.MakeMeABagel()
+ ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

PowerShell by default allows this to happen as defined its StrictMode

When Set-StrictMode is off, uninitialized variables (Version 1) are assumed to have a value of 0 (zero) or $Null, depending on type. References to non-existent properties return $Null, and the results of function syntax that is not valid vary with the error. Unnamed variables are not permitted.

Adjust icon size of Floating action button (fab)

The design guidelines defines two sizes and unless there is a strong reason to deviate from using either, the size can be controlled with the fabSize XML attribute of the FloatingActionButton component.

Consider specifying using either app:fabSize="normal" or app:fabSize="mini", e.g.:

<android.support.design.widget.FloatingActionButton
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:src="@drawable/ic_done_white_24px"
   app:fabSize="mini" />

Get last 30 day records from today date in SQL Server

This Should Work Fine

SELECT * FROM product 
WHERE pdate BETWEEN datetime('now', '-30 days') AND datetime('now', 'localtime')

How do I make WRAP_CONTENT work on a RecyclerView

I have not worked on my answer but the way I know it StaggridLayoutManager with no. of grid 1 can solve your problem as StaggridLayout will automatically adjust its height and width on the size of the content. if it works dont forget to check it as a right answer.Cheers..

Getting the difference between two Dates (months/days/hours/minutes/seconds) in Swift

A small addition to Leo Dabus' answer to provide the plural versions and be more human readable.

Swift 3

extension Date {
    /// Returns the amount of years from another date
    func years(from date: Date) -> Int {
        return Calendar.current.dateComponents([.year], from: date, to: self).year ?? 0
    }
    /// Returns the amount of months from another date
    func months(from date: Date) -> Int {
        return Calendar.current.dateComponents([.month], from: date, to: self).month ?? 0
    }
    /// Returns the amount of weeks from another date
    func weeks(from date: Date) -> Int {
        return Calendar.current.dateComponents([.weekOfMonth], from: date, to: self).weekOfMonth ?? 0
    }
    /// Returns the amount of days from another date
    func days(from date: Date) -> Int {
        return Calendar.current.dateComponents([.day], from: date, to: self).day ?? 0
    }
    /// Returns the amount of hours from another date
    func hours(from date: Date) -> Int {
        return Calendar.current.dateComponents([.hour], from: date, to: self).hour ?? 0
    }
    /// Returns the amount of minutes from another date
    func minutes(from date: Date) -> Int {
        return Calendar.current.dateComponents([.minute], from: date, to: self).minute ?? 0
    }
    /// Returns the amount of seconds from another date
    func seconds(from date: Date) -> Int {
        return Calendar.current.dateComponents([.second], from: date, to: self).second ?? 0
    }
    /// Returns the a custom time interval description from another date
    func offset(from date: Date) -> String {
        if years(from: date)   == 1 { return "\(years(from: date)) year"   } else if years(from: date)   > 1 { return "\(years(from: date)) years"   }
        if months(from: date)  == 1 { return "\(months(from: date)) month"  } else if months(from: date)  > 1 { return "\(months(from: date)) month"  }
        if weeks(from: date)   == 1 { return "\(weeks(from: date)) week"   } else if weeks(from: date)   > 1 { return "\(weeks(from: date)) weeks"   }
        if days(from: date)    == 1 { return "\(days(from: date)) day"    } else if days(from: date)    > 1 { return "\(days(from: date)) days"    }
        if hours(from: date)   == 1 { return "\(hours(from: date)) hour"   } else if hours(from: date)   > 1 { return "\(hours(from: date)) hours"   }
        if minutes(from: date) == 1 { return "\(minutes(from: date)) minute" } else if minutes(from: date) > 1 { return "\(minutes(from: date)) minutes" }
        return ""
    }
}

Why am I getting a " Traceback (most recent call last):" error?

At the beginning of your file you set raw_input to 0. Do not do this, at it modifies the built-in raw_input() function. Therefore, whenever you call raw_input(), it is essentially calling 0(), which raises the error. To remove the error, remove the first line of your code:

M = 1.6
# Miles to Kilometers 
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54


def intro():
    print("Welcome! This program will convert measures for you.")
    main()

def main():
    print("Select operation.")
    print("1.Miles to Kilometers")
    print("2.Fahrenheit to Celsius")
    print("3.Gallons to liters")
    print("4.Pounds to kilograms")
    print("5.Inches to centimeters")

    choice = input("Enter your choice by number: ")

    if choice == '1':
        convertMK()

    elif choice == '2':
        converCF()

    elif choice == '3':
        convertGL()

    elif choice == '4':
        convertPK()

    elif choice == '5':
        convertPK()

    else:
        print("Error")


def convertMK():
    input_M = float(raw_input(("Miles: ")))
    M_conv = (M) * input_M
    print("Kilometers: %f\n" % M_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def converCF():
    input_F = float(raw_input(("Fahrenheit: ")))
    F_conv = (input_F - 32) * 5/9
    print("Celcius: %f\n") % F_conv
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def convertGL():
    input_G = float(raw_input(("Gallons: ")))
    G_conv = input_G * 3.6
    print("Centimeters: %f\n" % G_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertPK():
    input_P = float(raw_input(("Pounds: ")))
    P_conv = input_P * 0.45
    print("Centimeters: %f\n" % P_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertIC():
    input_cm = float(raw_input(("Inches: ")))
    inches_conv = input_cm * 2.54
    print("Centimeters: %f\n" % inches_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def end():
    print("This program will close.")
    exit()

intro()

Unable to add window -- token null is not valid; is your activity running?

This error happens when you are trying to show popUpWindow too early ,to fix it, give Id to main layout as main_layout and use below code

Java:

 findViewById(R.id.main_layout).post(new Runnable() {
   public void run() {
       popupWindow.showAtLocation(findViewById(R.id.main_layout), Gravity.CENTER, 0, 0);
   }
});

Kotlin:

 main_layout.post {
      popupWindow?.showAtLocation(main_layout, Gravity.CENTER, 0, 0)
    }

Credit to @kordzik

RecyclerView inside ScrollView is not working

It seems that NestedScrollView does solve the problem. I've tested using this layout:

<android.support.v4.widget.NestedScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/dummy_text"
        />

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        >
        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

    </android.support.v7.widget.CardView>

</LinearLayout>

And it works without issues

socket connect() vs bind()

From Wikipedia http://en.wikipedia.org/wiki/Berkeley_sockets#bind.28.29

connect():

The connect() system call connects a socket, identified by its file descriptor, to a remote host specified by that host's address in the argument list.

Certain types of sockets are connectionless, most commonly user datagram protocol sockets. For these sockets, connect takes on a special meaning: the default target for sending and receiving data gets set to the given address, allowing the use of functions such as send() and recv() on connectionless sockets.

connect() returns an integer representing the error code: 0 represents success, while -1 represents an error.

bind():

bind() assigns a socket to an address. When a socket is created using socket(), it is only given a protocol family, but not assigned an address. This association with an address must be performed with the bind() system call before the socket can accept connections to other hosts. bind() takes three arguments:

sockfd, a descriptor representing the socket to perform the bind on. my_addr, a pointer to a sockaddr structure representing the address to bind to. addrlen, a socklen_t field specifying the size of the sockaddr structure. Bind() returns 0 on success and -1 if an error occurs.

Examples: 1.)Using Connect

#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>

int main(){
  int clientSocket;
  char buffer[1024];
  struct sockaddr_in serverAddr;
  socklen_t addr_size;

  /*---- Create the socket. The three arguments are: ----*/
  /* 1) Internet domain 2) Stream socket 3) Default protocol (TCP in this case) */
  clientSocket = socket(PF_INET, SOCK_STREAM, 0);

  /*---- Configure settings of the server address struct ----*/
  /* Address family = Internet */
  serverAddr.sin_family = AF_INET;
  /* Set port number, using htons function to use proper byte order */
  serverAddr.sin_port = htons(7891);
  /* Set the IP address to desired host to connect to */
  serverAddr.sin_addr.s_addr = inet_addr("192.168.1.17");
  /* Set all bits of the padding field to 0 */
  memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);  

  /*---- Connect the socket to the server using the address struct ----*/
  addr_size = sizeof serverAddr;
  connect(clientSocket, (struct sockaddr *) &serverAddr, addr_size);

  /*---- Read the message from the server into the buffer ----*/
  recv(clientSocket, buffer, 1024, 0);

  /*---- Print the received message ----*/
  printf("Data received: %s",buffer);   

  return 0;
}

2.)Bind Example:

int main()
{
    struct sockaddr_in source, destination = {};  //two sockets declared as previously
    int sock = 0;
    int datalen = 0;
    int pkt = 0;

    uint8_t *send_buffer, *recv_buffer;

    struct sockaddr_storage fromAddr;   // same as the previous entity struct sockaddr_storage serverStorage;
    unsigned int addrlen;  //in the previous example socklen_t addr_size;
    struct timeval tv;
    tv.tv_sec = 3;  /* 3 Seconds Time-out */
    tv.tv_usec = 0;

    /* creating the socket */         
    if ((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) 
        printf("Failed to create socket\n");

    /*set the socket options*/
    setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(struct timeval));

    /*Inititalize source to zero*/
    memset(&source, 0, sizeof(source));       //source is an instance of sockaddr_in. Initialization to zero
    /*Inititalize destinaton to zero*/
    memset(&destination, 0, sizeof(destination));


    /*---- Configure settings of the source address struct, WHERE THE PACKET IS COMING FROM ----*/
    /* Address family = Internet */
    source.sin_family = AF_INET;    
    /* Set IP address to localhost */   
    source.sin_addr.s_addr = INADDR_ANY;  //INADDR_ANY = 0.0.0.0
    /* Set port number, using htons function to use proper byte order */
    source.sin_port = htons(7005); 
    /* Set all bits of the padding field to 0 */
    memset(source.sin_zero, '\0', sizeof source.sin_zero); //optional


    /*bind socket to the source WHERE THE PACKET IS COMING FROM*/
    if (bind(sock, (struct sockaddr *) &source, sizeof(source)) < 0) 
        printf("Failed to bind socket");

    /* setting the destination, i.e our OWN IP ADDRESS AND PORT */
    destination.sin_family = AF_INET;                 
    destination.sin_addr.s_addr = inet_addr("127.0.0.1");  
    destination.sin_port = htons(7005); 

    //Creating a Buffer;
    send_buffer=(uint8_t *) malloc(350);
    recv_buffer=(uint8_t *) malloc(250);

    addrlen=sizeof(fromAddr);

    memset((void *) recv_buffer, 0, 250);
    memset((void *) send_buffer, 0, 350);

    sendto(sock, send_buffer, 20, 0,(struct sockaddr *) &destination, sizeof(destination));

    pkt=recvfrom(sock, recv_buffer, 98,0,(struct sockaddr *)&destination, &addrlen);
    if(pkt > 0)
        printf("%u bytes received\n", pkt);
    }

I hope that clarifies the difference

Please note that the socket type that you declare will depend on what you require, this is extremely important

What steps are needed to stream RTSP from FFmpeg?

You can use FFserver to stream a video using RTSP.

Just change console syntax to something like this:

ffmpeg -i space.mp4 -vcodec libx264 -tune zerolatency -crf 18 http://localhost:1234/feed1.ffm

Create a ffserver.config file (sample) where you declare HTTPPort, RTSPPort and SDP stream. Your config file could look like this (some important stuff might be missing):

HTTPPort 1234
RTSPPort 1235

<Feed feed1.ffm>
        File /tmp/feed1.ffm
        FileMaxSize 2M
        ACL allow 127.0.0.1
</Feed>

<Stream test1.sdp>
    Feed feed1.ffm
    Format rtp
    Noaudio
    VideoCodec libx264
    AVOptionVideo flags +global_header
    AVOptionVideo me_range 16
    AVOptionVideo qdiff 4
    AVOptionVideo qmin 10
    AVOptionVideo qmax 51
    ACL allow 192.168.0.0 192.168.255.255
</Stream>

With such setup you can watch the stream with i.e. VLC by typing:

rtsp://192.168.0.xxx:1235/test1.sdp

Here is the FFserver documentation.

Purpose of installing Twitter Bootstrap through npm?

  1. Use npm/bower to install bootstrap if you want to recompile it/change less files/test. With grunt it would be easier to do this, as shown on http://getbootstrap.com/getting-started/#grunt. If you only want to add precompiled libraries feel free to manually include files to project.

  2. No, you have to do this by yourself or use separate grunt tool. For example 'grunt-contrib-concat' How to concatenate and minify multiple CSS and JavaScript files with Grunt.js (0.3.x)

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

Kubernetes is an open source project that brings 'Google style' cluster management capabilities to the world of virtual machines, or 'on the metal' scenarios. It works very well with modern operating system environments (like CoreOS or Red Hat Atomic) that offer up lightweight computing 'nodes' that are managed for you. It is written in Golang and is lightweight, modular, portable and extensible. We (the Kubernetes team) are working with a number of different technology companies (including Mesosphere who curate the Mesos open source project) to establish Kubernetes as the standard way to interact with computing clusters. The idea is to reproduce the patterns that we see people needing to build cluster applications based on our experience at Google. Some of these concepts include:

  • pods — a way to group containers together
  • replication controllers — a way to handle the lifecycle of containers
  • labels — a way to find and query containers, and
  • services — a set of containers performing a common function.

So with Kubernetes alone you will have something that is simple, easy to get up-and-running, portable and extensible that adds 'cluster' as a noun to the things that you manage in the lightest weight manner possible. Run an application on a cluster, and stop worrying about an individual machine. In this case, cluster is a flexible resource just like a VM. It is a logical computing unit. Turn it up, use it, resize it, turn it down quickly and easily.

With Mesos, there is a fair amount of overlap in terms of the basic vision, but the products are at quite different points in their lifecycle and have different sweet spots. Mesos is a distributed systems kernel that stitches together a lot of different machines into a logical computer. It was born for a world where you own a lot of physical resources to create a big static computing cluster. The great thing about it is that lots of modern scalable data processing application run well on Mesos (Hadoop, Kafka, Spark) and it is nice because you can run them all on the same basic resource pool, along with your new age container packaged apps. It is somewhat more heavy weight than the Kubernetes project, but is getting easier and easier to manage thanks to the work of folks like Mesosphere.

Now what gets really interesting is that Mesos is currently being adapted to add a lot of the Kubernetes concepts and to support the Kubernetes API. So it will be a gateway to getting more capabilities for your Kubernetes app (high availability master, more advanced scheduling semantics, ability to scale to a very large number of nodes) if you need them, and is well suited to run production workloads (Kubernetes is still in an alpha state).

When asked, I tend to say:

  1. Kubernetes is a great place to start if you are new to the clustering world; it is the quickest, easiest and lightest way to kick the tires and start experimenting with cluster oriented development. It offers a very high level of portability since it is being supported by a lot of different providers (Microsoft, IBM, Red Hat, CoreOs, MesoSphere, VMWare, etc).

  2. If you have existing workloads (Hadoop, Spark, Kafka, etc), Mesos gives you a framework that let's you interleave those workloads with each other, and mix in a some of the new stuff including Kubernetes apps.

  3. Mesos gives you an escape valve if you need capabilities that are not yet implemented by the community in the Kubernetes framework.

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

The reason your attempt wasn't working, is because the two animations (fade-in and fade-out) were working against each other.

Right before an object became visible, it was still invisible and so the animation for fading-out would run. Then, the fraction of a second later when that same object had become visible, the fade-in animation would try to run, but the fade-out was still running. So they would work against each other and you would see nothing.

Eventually the object would become visible (most of the time), but it would take a while. And if you would scroll down by using the arrow-button at the button of the scrollbar, the animation would sort of work, because you would scroll using bigger increments, creating less scroll-events.


Enough explanation, the solution (JS, CSS, HTML):

_x000D_
_x000D_
$(window).on("load",function() {_x000D_
  $(window).scroll(function() {_x000D_
    var windowBottom = $(this).scrollTop() + $(this).innerHeight();_x000D_
    $(".fade").each(function() {_x000D_
      /* Check the location of each desired element */_x000D_
      var objectBottom = $(this).offset().top + $(this).outerHeight();_x000D_
      _x000D_
      /* If the element is completely within bounds of the window, fade it in */_x000D_
      if (objectBottom < windowBottom) { //object comes into view (scrolling down)_x000D_
        if ($(this).css("opacity")==0) {$(this).fadeTo(500,1);}_x000D_
      } else { //object goes out of view (scrolling up)_x000D_
        if ($(this).css("opacity")==1) {$(this).fadeTo(500,0);}_x000D_
      }_x000D_
    });_x000D_
  }).scroll(); //invoke scroll-handler on page-load_x000D_
});
_x000D_
.fade {_x000D_
  margin: 50px;_x000D_
  padding: 50px;_x000D_
  background-color: lightgreen;_x000D_
  opacity: 1;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>_x000D_
_x000D_
<div>_x000D_
  <div class="fade">Fade In 01</div>_x000D_
  <div class="fade">Fade In 02</div>_x000D_
  <div class="fade">Fade In 03</div>_x000D_
  <div class="fade">Fade In 04</div>_x000D_
  <div class="fade">Fade In 05</div>_x000D_
  <div class="fade">Fade In 06</div>_x000D_
  <div class="fade">Fade In 07</div>_x000D_
  <div class="fade">Fade In 08</div>_x000D_
  <div class="fade">Fade In 09</div>_x000D_
  <div class="fade">Fade In 10</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_ (fiddle: http://jsfiddle.net/eLwex993/2/)

  • I wrapped the fade-codeline in an if-clause: if ($(this).css("opacity")==0) {...}. This makes sure the object is only faded in when the opacity is 0. Same goes for fading out. And this prevents the fade-in and fade-out from working against each other, because now there's ever only one of the two running at one time on an object.
  • I changed .animate() to .fadeTo(). It's jQuery's specialized function for opacity, a lot shorter to write and probably lighter than animate.
  • I changed .position() to .offset(). This always calculates relative to the body, whereas position is relative to the parent. For your case I believe offset is the way to go.
  • I changed $(window).height() to $(window).innerHeight(). The latter is more reliable in my experience.
  • Directly after the scroll-handler, I invoke that handler once on page-load with $(window).scroll();. Now you can give all desired objects on the page the .fade class, and objects that should be invisible at page-load, will be faded out immediately.
  • I removed #container from both HTML and CSS, because (at least for this answer) it isn't necessary. (I thought maybe you needed the height:2000px because you used .position() instead of .offset(), otherwise I don't know. Feel free of course to leave it in your code.)

UPDATE

If you want opacity values other than 0 and 1, use the following code:

_x000D_
_x000D_
$(window).on("load",function() {_x000D_
  function fade(pageLoad) {_x000D_
    var windowBottom = $(window).scrollTop() + $(window).innerHeight();_x000D_
    var min = 0.3;_x000D_
    var max = 0.7;_x000D_
    var threshold = 0.01;_x000D_
    _x000D_
    $(".fade").each(function() {_x000D_
      /* Check the location of each desired element */_x000D_
      var objectBottom = $(this).offset().top + $(this).outerHeight();_x000D_
      _x000D_
      /* If the element is completely within bounds of the window, fade it in */_x000D_
      if (objectBottom < windowBottom) { //object comes into view (scrolling down)_x000D_
        if ($(this).css("opacity")<=min+threshold || pageLoad) {$(this).fadeTo(500,max);}_x000D_
      } else { //object goes out of view (scrolling up)_x000D_
        if ($(this).css("opacity")>=max-threshold || pageLoad) {$(this).fadeTo(500,min);}_x000D_
      }_x000D_
    });_x000D_
  } fade(true); //fade elements on page-load_x000D_
  $(window).scroll(function(){fade(false);}); //fade elements on scroll_x000D_
});
_x000D_
.fade {_x000D_
  margin: 50px;_x000D_
  padding: 50px;_x000D_
  background-color: lightgreen;_x000D_
  opacity: 1;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>_x000D_
_x000D_
<div>_x000D_
  <div class="fade">Fade In 01</div>_x000D_
  <div class="fade">Fade In 02</div>_x000D_
  <div class="fade">Fade In 03</div>_x000D_
  <div class="fade">Fade In 04</div>_x000D_
  <div class="fade">Fade In 05</div>_x000D_
  <div class="fade">Fade In 06</div>_x000D_
  <div class="fade">Fade In 07</div>_x000D_
  <div class="fade">Fade In 08</div>_x000D_
  <div class="fade">Fade In 09</div>_x000D_
  <div class="fade">Fade In 10</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_ (fiddle: http://jsfiddle.net/eLwex993/3/)

  • I added a threshold to the if-clause, see explanation below.
  • I created variables for the threshold and for min/max at the start of the function. In the rest of the function these variables are referenced. This way, if you ever want to change the values again, you only have to do it in one place.
  • I also added || pageLoad to the if-clause. This was necessary to make sure all objects are faded to the correct opacity on page-load. pageLoad is a boolean that is send along as an argument when fade() is invoked.
    I had to put the fade-code inside the extra function fade() {...}, in order to be able to send along the pageLoad boolean when the scroll-handler is invoked.
    I did't see any other way to do this, if anyone else does, please leave a comment.

Explanation:
The reason the code in your fiddle didn't work, is because the actual opacity values are always a little off from the value you set it to. So if you set the opacity to 0.3, the actual value (in this case) is 0.300000011920929. That's just one of those little bugs you have to learn along the way by trail and error. That's why this if-clause won't work: if ($(this).css("opacity") == 0.3) {...}.

I added a threshold, to take that difference into account: == 0.3 becomes <= 0.31.
(I've set the threshold to 0.01, this can be changed of course, just as long as the actual opacity will fall between the set value and this threshold.)

The operators are now changed from == to <= and >=.


UPDATE 2:

If you want to fade the elements based on their visible percentage, use the following code:

_x000D_
_x000D_
$(window).on("load",function() {_x000D_
  function fade(pageLoad) {_x000D_
    var windowTop=$(window).scrollTop(), windowBottom=windowTop+$(window).innerHeight();_x000D_
    var min=0.3, max=0.7, threshold=0.01;_x000D_
    _x000D_
    $(".fade").each(function() {_x000D_
      /* Check the location of each desired element */_x000D_
      var objectHeight=$(this).outerHeight(), objectTop=$(this).offset().top, objectBottom=$(this).offset().top+objectHeight;_x000D_
      _x000D_
      /* Fade element in/out based on its visible percentage */_x000D_
      if (objectTop < windowTop) {_x000D_
        if (objectBottom > windowTop) {$(this).fadeTo(0,min+((max-min)*((objectBottom-windowTop)/objectHeight)));}_x000D_
        else if ($(this).css("opacity")>=min+threshold || pageLoad) {$(this).fadeTo(0,min);}_x000D_
      } else if (objectBottom > windowBottom) {_x000D_
        if (objectTop < windowBottom) {$(this).fadeTo(0,min+((max-min)*((windowBottom-objectTop)/objectHeight)));}_x000D_
        else if ($(this).css("opacity")>=min+threshold || pageLoad) {$(this).fadeTo(0,min);}_x000D_
      } else if ($(this).css("opacity")<=max-threshold || pageLoad) {$(this).fadeTo(0,max);}_x000D_
    });_x000D_
  } fade(true); //fade elements on page-load_x000D_
  $(window).scroll(function(){fade(false);}); //fade elements on scroll_x000D_
});
_x000D_
.fade {_x000D_
  margin: 50px;_x000D_
  padding: 50px;_x000D_
  background-color: lightgreen;_x000D_
  opacity: 1;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>_x000D_
_x000D_
<div>_x000D_
  <div class="fade">Fade In 01</div>_x000D_
  <div class="fade">Fade In 02</div>_x000D_
  <div class="fade">Fade In 03</div>_x000D_
  <div class="fade">Fade In 04</div>_x000D_
  <div class="fade">Fade In 05</div>_x000D_
  <div class="fade">Fade In 06</div>_x000D_
  <div class="fade">Fade In 07</div>_x000D_
  <div class="fade">Fade In 08</div>_x000D_
  <div class="fade">Fade In 09</div>_x000D_
  <div class="fade">Fade In 10</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_ (fiddle: http://jsfiddle.net/eLwex993/5/)

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

You are not getting value of $id=$_GET['id'];

And you are using it (before it gets initialised).

Use php's in built isset() function to check whether the variable is defied or not.

So, please update the line to:

$id = isset($_GET['id']) ? $_GET['id'] : '';

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

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

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

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

How to add elements to a list in R (loop)

The following adds elements to a list in a loop.

l<-c()
i=1

while(i<100) {

    b<-i
    l<-c(l,b)
    i=i+1
}

How to use goto statement correctly

Java also does not use line numbers, which is a necessity for a GOTO function. Unlike C/C++, Java does not have goto statement, but java supports label. The only place where a label is useful in Java is right before nested loop statements. We can specify label name with break to break out a specific outer loop.

resize2fs: Bad magic number in super-block while trying to open

In Centos 7 default filesystem is xfs.

xfs file system support only extend not reduce. So if you want to resize the filesystem use xfs_growfs rather than resize2fs.

xfs_growfs /dev/root_vg/root 

Note: For ext4 filesystem use

resize2fs /dev/root_vg/root

Subtracting time.Duration from time in Go

In response to Thomas Browne's comment, because lnmx's answer only works for subtracting a date, here is a modification of his code that works for subtracting time from a time.Time type.

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()

    fmt.Println("now:", now)

    count := 10
    then := now.Add(time.Duration(-count) * time.Minute)
    // if we had fix number of units to subtract, we can use following line instead fo above 2 lines. It does type convertion automatically.
    // then := now.Add(-10 * time.Minute)
    fmt.Println("10 minutes ago:", then)
}

Produces:

now: 2009-11-10 23:00:00 +0000 UTC
10 minutes ago: 2009-11-10 22:50:00 +0000 UTC

Not to mention, you can also use time.Hour or time.Second instead of time.Minute as per your needs.

Playground: https://play.golang.org/p/DzzH4SA3izp

Global constants file in Swift

Although I prefer @Francescu's way (using a struct with static properties), you can also define global constants and variables:

let someNotification = "TEST"

Note however that differently from local variables/constants and class/struct properties, globals are implicitly lazy, which means they are initialized when they are accessed for the first time.

Suggested reading: Global and Local Variables, and also Global variables in Swift are not variables

Cannot read property 'addEventListener' of null

As others have said problem is that script is executed before the page (and in particular the target element) is loaded.

But I don't like the solution of reordering the content.

Preferred solution is to put an event handler on page onload event and set the Listener there. That will ensure the page and the target element is loaded before the assignment is executed. eg

    <script>
    function onLoadFunct(){
            // set Listener here, also using suggested test for null
    }
    ....
    </script>

    <body onload="onLoadFunct()" ....>
    .....

Using "-Filter" with a variable

You don't need quotes around the variable, so simply change this:

Get-ADComputer -Filter {name -like '$nameregex' -and Enabled -eq "true"}

into this:

Get-ADComputer -Filter {name -like $nameregex -and Enabled -eq "true"}

Note, however, that the scriptblock notation for filter statements is misleading, because the statement is actually a string, so it's better to write it as such:

Get-ADComputer -Filter "name -like '$nameregex' -and Enabled -eq 'true'"

Related. Also related.

And FTR: you're using wildcard matching here (operator -like), not regular expressions (operator -match).

Java: convert seconds to minutes, hours and days

You can use the Java enum TimeUnit to perform your math and avoid any hard coded values. Then we can use String.format(String, Object...) and a pair of StringBuilder(s) as well as a DecimalFormat to build the requested output. Something like,

Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a number of seconds:");
String str = scanner.nextLine().replace("\\,", "").trim();
long secondsIn = Long.parseLong(str);
long dayCount = TimeUnit.SECONDS.toDays(secondsIn);
long secondsCount = secondsIn - TimeUnit.DAYS.toSeconds(dayCount);
long hourCount = TimeUnit.SECONDS.toHours(secondsCount);
secondsCount -= TimeUnit.HOURS.toSeconds(hourCount);
long minutesCount = TimeUnit.SECONDS.toMinutes(secondsCount);
secondsCount -= TimeUnit.MINUTES.toSeconds(minutesCount);
StringBuilder sb = new StringBuilder();
sb.append(String.format("%d %s, ", dayCount, (dayCount == 1) ? "day"
        : "days"));
StringBuilder sb2 = new StringBuilder();
sb2.append(sb.toString());
sb2.append(String.format("%02d:%02d:%02d %s", hourCount, minutesCount,
        secondsCount, (hourCount == 1) ? "hour" : "hours"));
sb.append(String.format("%d %s, ", hourCount, (hourCount == 1) ? "hour"
        : "hours"));
sb.append(String.format("%d %s and ", minutesCount,
        (minutesCount == 1) ? "minute" : "minutes"));
sb.append(String.format("%d %s.", secondsCount,
        (secondsCount == 1) ? "second" : "seconds"));
System.out.printf("You entered %s seconds, which is %s (%s)%n",
        new DecimalFormat("#,###").format(secondsIn), sb, sb2);

Which, when I enter 500000 outputs the requested (manual line break added for post) -

You entered 500,000 seconds, which is 5 days, 18 hours, 
53 minutes and 20 seconds. (5 days, 18:53:20 hours)

Error:java: invalid source release: 8 in Intellij. What does it mean?

If you are using Gradle as a build tool and you get this error when executing a Gradle task i.e TomcatRun take a look to my other answer to the same question

javac: invalid target release: 1.8

Slick.js: Get current and total slides (ie. 3/5)

You need to bind init before initialization.

$('.slider-for').on('init', function(event, slick){
        $(this).append('<div class="slider-count"><p><span id="current">1</span> von <span id="total">'+slick.slideCount+'</span></p></div>');
    });
    $('.slider-for').slick({
      slidesToShow: 1,
      slidesToScroll: 1,
      arrows: true,
      fade: true
    });
    $('.slider-for')
        .on('afterChange', function(event, slick, currentSlide, nextSlide){
            // finally let's do this after changing slides
            $('.slider-count #current').html(currentSlide+1);
        });

What is the OAuth 2.0 Bearer Token exactly?

Bearer token is one or more repetition of alphabet, digit, "-" , "." , "_" , "~" , "+" , "/" followed by 0 or more "=".

RFC 6750 2.1. Authorization Request Header Field (Format is ABNF (Augmented BNF))

The syntax for Bearer credentials is as follows:

     b64token    = 1*( ALPHA / DIGIT /
                       "-" / "." / "_" / "~" / "+" / "/" ) *"="
     credentials = "Bearer" 1*SP b64token

It looks like Base64 but according to Should the token in the header be base64 encoded?, it is not.

Digging a bit deeper in to "HTTP/1.1, part 7: Authentication"**, however, I see that b64token is just an ABNF syntax definition allowing for characters typically used in base64, base64url, etc.. So the b64token doesn't define any encoding or decoding but rather just defines what characters can be used in the part of the Authorization header that will contain the access token.

This fully addresses the first 3 items in the OP question's list. So I'm extending this answer to address the 4th question, about whether the token must be validated, so @mon feel free to remove or edit:

The authorizer is responsible for accepting or rejecting the http request. If the authorizer says the token is valid, it's up to you to decide what this means:

  • Does the authorizer have a way of inspecting the URL, identifying the operation, and looking up some role-based access control database to see if it is allowed? If yes and the request comes through, the service can assume it is allowed, and does not need to verify.
  • Is the token an all-or-nothing, so if the token is correct, all operations are allowed? Then the service doesn't need to verify.
  • Does the token mean "this request is allowed, but here is the UUID for the role, you check whether the operation is allowed". Then it's up to the service to look up that role, and see if the operation is allowed.

References

JSON ValueError: Expecting property name: line 1 column 2 (char 1)

json.loads will load a json string into a python dict, json.dumps will dump a python dict to a json string, for example:

>>> json_string = '{"favorited": false, "contributors": null}'
'{"favorited": false, "contributors": null}'
>>> value = json.loads(json_string)
{u'favorited': False, u'contributors': None}
>>> json_dump = json.dumps(value)
'{"favorited": false, "contributors": null}'

So that line is incorrect since you are trying to load a python dict, and json.loads is expecting a valid json string which should have <type 'str'>.

So if you are trying to load the json, you should change what you are loading to look like the json_string above, or you should be dumping it. This is just my best guess from the given information. What is it that you are trying to accomplish?

Also you don't need to specify the u before your strings, as @Cld mentioned in the comments.

Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given... what I do wrong?

If you use the procedural style, you have to provide both a connection and a string:

$name = mysqli_real_escape_string($conn, $name);

Only the object oriented version can be done with just a string:

$name = $link->real_escape_string($name);

The documentation should hopefully make this clear.

WinSCP: Permission denied. Error code: 3 Error message from server: Permission denied

You possibly do not have create permissions to the folder. So WinSCP fails to create a temporary file for the transfer.

You have two options:

Dynamically add item to jQuery Select2 control that uses AJAX

I did it this way and it worked for me like a charm.

var data = [{ id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2, 

    text: 'duplicate' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' }];

    $(".js-example-data-array").select2({
      data: data
    })

Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes

If you have a hard time remembering the default values (I know I have...) here's a short extract from BalusC's answer:

Component    | Submit          | Refresh
------------ | --------------- | --------------
f:ajax       | execute="@this" | render="@none"
p:ajax       | process="@this" | update="@none"
p:commandXXX | process="@form" | update="@none"

Intel's HAXM equivalent for AMD on Windows OS

Buying a new processor is one solution, but for some of us that means buying other components as well. Alternatively you could just buy an Android phone that supports your lowest target API level and run your apps off the phone. You can find some of those phones on Amazon, Ebay, craigslist for pennies (sometimes). Plus this grants you the benefit of actually running on the minimum hardware you intend to support. While this may be a bit slower than installing your app on an emulated system, it will probably save you money.

Android, device testing/debugging link: http://developer.android.com/tools/device.html

Difference between Width:100% and width:100vw?

Havengard's answer doesn't seem to be strictly true. I've found that vw fills the viewport width, but doesn't account for the scrollbars. So, if your content is taller than the viewport (so that your site has a vertical scrollbar), then using vw results in a small horizontal scrollbar. I had to switch out width: 100vw for width: 100% to get rid of the horizontal scrollbar.

async await return Task

You need to use the await keyword when use async and your function return type should be generic Here is an example with return value:

public async Task<object> MethodName()
{
    return await Task.FromResult<object>(null);
}

Here is an example with no return value:

public async Task MethodName()
{
    await Task.CompletedTask;
}

Read these:

TPL: http://msdn.microsoft.com/en-us/library/dd460717(v=vs.110).aspx and Tasks: http://msdn.microsoft.com/en-us/library/system.threading.tasks(v=vs.110).aspx

Async: http://msdn.microsoft.com/en-us/library/hh156513.aspx Await: http://msdn.microsoft.com/en-us/library/hh156528.aspx

Using GPU from a docker container?

Ok i finally managed to do it without using the --privileged mode.

I'm running on ubuntu server 14.04 and i'm using the latest cuda (6.0.37 for linux 13.04 64 bits).


Preparation

Install nvidia driver and cuda on your host. (it can be a little tricky so i will suggest you follow this guide https://askubuntu.com/questions/451672/installing-and-testing-cuda-in-ubuntu-14-04)

ATTENTION : It's really important that you keep the files you used for the host cuda installation


Get the Docker Daemon to run using lxc

We need to run docker daemon using lxc driver to be able to modify the configuration and give the container access to the device.

One time utilization :

sudo service docker stop
sudo docker -d -e lxc

Permanent configuration Modify your docker configuration file located in /etc/default/docker Change the line DOCKER_OPTS by adding '-e lxc' Here is my line after modification

DOCKER_OPTS="--dns 8.8.8.8 --dns 8.8.4.4 -e lxc"

Then restart the daemon using

sudo service docker restart

How to check if the daemon effectively use lxc driver ?

docker info

The Execution Driver line should look like that :

Execution Driver: lxc-1.0.5

Build your image with the NVIDIA and CUDA driver.

Here is a basic Dockerfile to build a CUDA compatible image.

FROM ubuntu:14.04
MAINTAINER Regan <http://stackoverflow.com/questions/25185405/using-gpu-from-a-docker-container>

RUN apt-get update && apt-get install -y build-essential
RUN apt-get --purge remove -y nvidia*

ADD ./Downloads/nvidia_installers /tmp/nvidia                             > Get the install files you used to install CUDA and the NVIDIA drivers on your host
RUN /tmp/nvidia/NVIDIA-Linux-x86_64-331.62.run -s -N --no-kernel-module   > Install the driver.
RUN rm -rf /tmp/selfgz7                                                   > For some reason the driver installer left temp files when used during a docker build (i don't have any explanation why) and the CUDA installer will fail if there still there so we delete them.
RUN /tmp/nvidia/cuda-linux64-rel-6.0.37-18176142.run -noprompt            > CUDA driver installer.
RUN /tmp/nvidia/cuda-samples-linux-6.0.37-18176142.run -noprompt -cudaprefix=/usr/local/cuda-6.0   > CUDA samples comment if you don't want them.
RUN export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda/lib64         > Add CUDA library into your PATH
RUN touch /etc/ld.so.conf.d/cuda.conf                                     > Update the ld.so.conf.d directory
RUN rm -rf /temp/*  > Delete installer files.

Run your image.

First you need to identify your the major number associated with your device. Easiest way is to do the following command :

ls -la /dev | grep nvidia

If the result is blank, use launching one of the samples on the host should do the trick. The result should look like that enter image description here As you can see there is a set of 2 numbers between the group and the date. These 2 numbers are called major and minor numbers (wrote in that order) and design a device. We will just use the major numbers for convenience.

Why do we activated lxc driver? To use the lxc conf option that allow us to permit our container to access those devices. The option is : (i recommend using * for the minor number cause it reduce the length of the run command)

--lxc-conf='lxc.cgroup.devices.allow = c [major number]:[minor number or *] rwm'

So if i want to launch a container (Supposing your image name is cuda).

docker run -ti --lxc-conf='lxc.cgroup.devices.allow = c 195:* rwm' --lxc-conf='lxc.cgroup.devices.allow = c 243:* rwm' cuda

Oracle query to identify columns having special characters

Compare the length using lengthB and length function in oracle.

SELECT * FROM test WHERE length(sampletext) <> lengthb(sampletext)

How to create JNDI context in Spring Boot with Embedded Tomcat Container

In SpringBoot 2.1, I found another solution. Extend standard factory class method getTomcatWebServer. And then return it as a bean from anywhere.

public class CustomTomcatServletWebServerFactory extends TomcatServletWebServerFactory {

    @Override
    protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {
        System.setProperty("catalina.useNaming", "true");
        tomcat.enableNaming();
        return new TomcatWebServer(tomcat, getPort() >= 0);
    }
}

@Component
public class TomcatConfiguration {
    @Bean
    public ConfigurableServletWebServerFactory webServerFactory() {
        TomcatServletWebServerFactory factory = new CustomTomcatServletWebServerFactory();

        return factory;
    }

Loading resources from context.xml doesn't work though. Will try to find out.

iOS 8 removed "minimal-ui" viewport property, are there other "soft fullscreen" solutions?

It IS possible, using something like the below example that I put together with the help of work from (https://gist.github.com/bitinn/1700068a276fb29740a7) that didn't quite work on iOS 11:

Here's the modified code that works on iOS 11.03, please comment if it worked for you.

The key is adding some size to BODY so the browser can scroll, ex: height: calc(100% + 40px);

Full sample below & link to view in your browser (please test!)

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CodeHots iOS WebApp Minimal UI via Scroll Test</title>

    <style>
        html, body {
            height: 100%;
        }
        html {
            background-color: red;
        }
        body {
            background-color: blue;
            /* important to allow page to scroll */
            height: calc(100% + 40px);
            margin: 0;
        }
        div.header {
            width: 100%;
            height: 40px;
            background-color: green;
            overflow: hidden;
        }
        div.content {
            height: 100%;
            height: calc(100% - 40px);
            width: 100%;
            background-color: purple;
            overflow: hidden;
        }
        div.cover {
            position: absolute;
            top: 0;
            left: 0;
            z-index: 100;
            width: 100%;
            height: 100%;
            overflow: hidden;
            background-color: rgba(0, 0, 0, 0.5);
            color: #fff;
            display: none;
        }
        @media screen and (width: 320px) {
            html {
                height: calc(100% + 72px);
            }
            div.cover {
                display: block;
            }
        }
    </style>
    <script>
        var timeout;

        function interceptTouchMove(){
            // and disable the touchmove features 
            window.addEventListener("touchmove", (event)=>{
                if (!event.target.classList.contains('scrollable')) {
                    // no more scrolling
                    event.preventDefault();
                }
            }, false); 
        }

        function scrollDetect(event){
            // wait for the result to settle
            if( timeout ) clearTimeout(timeout);

            timeout = setTimeout(function() {
                console.log( 'scrolled up detected..' );
                if (window.scrollY > 35) {
                    console.log( ' .. moved up enough to go into minimal UI mode. cover off and locking touchmove!');
                    // hide the fixed scroll-cover
                    var cover = document.querySelector('div.cover');
                    cover.style.display = 'none';

                    // push back down to designated start-point. (as it sometimes overscrolls (this is jQuery implementation I used))
                    window.scrollY = 40;

                    // and disable the touchmove features 
                    interceptTouchMove();

                    // turn off scroll checker
                    window.removeEventListener('scroll', scrollDetect );                
                }
            }, 200);            
        }

        // listen to scroll to know when in minimal-ui mode.
        window.addEventListener('scroll', scrollDetect, false );
    </script>
</head>
<body>

    <div class="header">
        <p>header zone</p>
    </div>
    <div class="content">
        <p>content</p>
    </div>
    <div class="cover">
        <p>scroll to soft fullscreen</p>
    </div>

</body>

Full example link here: https://repos.codehot.tech/misc/ios-webapp-example2.html

Comparing two maps

As long as you override equals() on each key and value contained in the map, then m1.equals(m2) should be reliable to check for maps equality.

The same result can be obtained also by comparing toString() of each map as you suggested, but using equals() is a more intuitive approach.

May not be your specific situation, but if you store arrays in the map, may be a little tricky, because they must be compared value by value, or using Arrays.equals(). More details about this see here.

When is the init() function run?

Take for example a framework or a library you're designing for other users, these users eventually will have a main function in their code in order to execute their app. If the user directly imports a sub-package of your library's project then the init of that sub-package will be called(once) first of all. The same for the root package of the library, etc...

There are many times when you may want a code block to be executed without the existence of a main func, directly or not.

If you, as the developer of the imaginary library, import your library's sub-package that has an init function, it will be called first and once, you don't have a main func but you need to make sure that some variables, or a table, will be initialized before the calls of other functions.

A good thing to remember and not to worry about, is that: the init always execute once per application.

init execution happens:

  1. right before the init function of the "caller" package,
  2. before the, optionally, main func,
  3. but after the package-level variables, var = [...] or cost = [...],

When you import a package it will run all of its init functions, by order.

I'll will give a very good example of an init function. It will add mime types to a standard go's library named mime and a package-level function will use the mime standard package directly to get the custom mime types that are already be initialized at its init function:

package mime

import (
    "mime"
    "path/filepath"
)

var types = map[string]string{
    ".3dm":       "x-world/x-3dmf",
    ".3dmf":      "x-world/x-3dmf",
    ".7z":        "application/x-7z-compressed",
    ".a":         "application/octet-stream",
    ".aab":       "application/x-authorware-bin",
    ".aam":       "application/x-authorware-map",
    ".aas":       "application/x-authorware-seg",
    ".abc":       "text/vndabc",
    ".ace":       "application/x-ace-compressed",
    ".acgi":      "text/html",
    ".afl":       "video/animaflex",
    ".ai":        "application/postscript",
    ".aif":       "audio/aiff",
    ".aifc":      "audio/aiff",
    ".aiff":      "audio/aiff",
    ".aim":       "application/x-aim",
    ".aip":       "text/x-audiosoft-intra",
    ".alz":       "application/x-alz-compressed",
    ".ani":       "application/x-navi-animation",
    ".aos":       "application/x-nokia-9000-communicator-add-on-software",
    ".aps":       "application/mime",
    ".apk":       "application/vnd.android.package-archive",
    ".arc":       "application/x-arc-compressed",
    ".arj":       "application/arj",
    ".art":       "image/x-jg",
    ".asf":       "video/x-ms-asf",
    ".asm":       "text/x-asm",
    ".asp":       "text/asp",
    ".asx":       "application/x-mplayer2",
    ".au":        "audio/basic",
    ".avi":       "video/x-msvideo",
    ".avs":       "video/avs-video",
    ".bcpio":     "application/x-bcpio",
    ".bin":       "application/mac-binary",
    ".bmp":       "image/bmp",
    ".boo":       "application/book",
    ".book":      "application/book",
    ".boz":       "application/x-bzip2",
    ".bsh":       "application/x-bsh",
    ".bz2":       "application/x-bzip2",
    ".bz":        "application/x-bzip",
    ".c++":       "text/plain",
    ".c":         "text/x-c",
    ".cab":       "application/vnd.ms-cab-compressed",
    ".cat":       "application/vndms-pkiseccat",
    ".cc":        "text/x-c",
    ".ccad":      "application/clariscad",
    ".cco":       "application/x-cocoa",
    ".cdf":       "application/cdf",
    ".cer":       "application/pkix-cert",
    ".cha":       "application/x-chat",
    ".chat":      "application/x-chat",
    ".chrt":      "application/vnd.kde.kchart",
    ".class":     "application/java",
    ".com":       "text/plain",
    ".conf":      "text/plain",
    ".cpio":      "application/x-cpio",
    ".cpp":       "text/x-c",
    ".cpt":       "application/mac-compactpro",
    ".crl":       "application/pkcs-crl",
    ".crt":       "application/pkix-cert",
    ".crx":       "application/x-chrome-extension",
    ".csh":       "text/x-scriptcsh",
    ".css":       "text/css",
    ".csv":       "text/csv",
    ".cxx":       "text/plain",
    ".dar":       "application/x-dar",
    ".dcr":       "application/x-director",
    ".deb":       "application/x-debian-package",
    ".deepv":     "application/x-deepv",
    ".def":       "text/plain",
    ".der":       "application/x-x509-ca-cert",
    ".dif":       "video/x-dv",
    ".dir":       "application/x-director",
    ".divx":      "video/divx",
    ".dl":        "video/dl",
    ".dmg":       "application/x-apple-diskimage",
    ".doc":       "application/msword",
    ".dot":       "application/msword",
    ".dp":        "application/commonground",
    ".drw":       "application/drafting",
    ".dump":      "application/octet-stream",
    ".dv":        "video/x-dv",
    ".dvi":       "application/x-dvi",
    ".dwf":       "drawing/x-dwf=(old)",
    ".dwg":       "application/acad",
    ".dxf":       "application/dxf",
    ".dxr":       "application/x-director",
    ".el":        "text/x-scriptelisp",
    ".elc":       "application/x-bytecodeelisp=(compiled=elisp)",
    ".eml":       "message/rfc822",
    ".env":       "application/x-envoy",
    ".eps":       "application/postscript",
    ".es":        "application/x-esrehber",
    ".etx":       "text/x-setext",
    ".evy":       "application/envoy",
    ".exe":       "application/octet-stream",
    ".f77":       "text/x-fortran",
    ".f90":       "text/x-fortran",
    ".f":         "text/x-fortran",
    ".fdf":       "application/vndfdf",
    ".fif":       "application/fractals",
    ".fli":       "video/fli",
    ".flo":       "image/florian",
    ".flv":       "video/x-flv",
    ".flx":       "text/vndfmiflexstor",
    ".fmf":       "video/x-atomic3d-feature",
    ".for":       "text/x-fortran",
    ".fpx":       "image/vndfpx",
    ".frl":       "application/freeloader",
    ".funk":      "audio/make",
    ".g3":        "image/g3fax",
    ".g":         "text/plain",
    ".gif":       "image/gif",
    ".gl":        "video/gl",
    ".gsd":       "audio/x-gsm",
    ".gsm":       "audio/x-gsm",
    ".gsp":       "application/x-gsp",
    ".gss":       "application/x-gss",
    ".gtar":      "application/x-gtar",
    ".gz":        "application/x-compressed",
    ".gzip":      "application/x-gzip",
    ".h":         "text/x-h",
    ".hdf":       "application/x-hdf",
    ".help":      "application/x-helpfile",
    ".hgl":       "application/vndhp-hpgl",
    ".hh":        "text/x-h",
    ".hlb":       "text/x-script",
    ".hlp":       "application/hlp",
    ".hpg":       "application/vndhp-hpgl",
    ".hpgl":      "application/vndhp-hpgl",
    ".hqx":       "application/binhex",
    ".hta":       "application/hta",
    ".htc":       "text/x-component",
    ".htm":       "text/html",
    ".html":      "text/html",
    ".htmls":     "text/html",
    ".htt":       "text/webviewhtml",
    ".htx":       "text/html",
    ".ice":       "x-conference/x-cooltalk",
    ".ico":       "image/x-icon",
    ".ics":       "text/calendar",
    ".icz":       "text/calendar",
    ".idc":       "text/plain",
    ".ief":       "image/ief",
    ".iefs":      "image/ief",
    ".iges":      "application/iges",
    ".igs":       "application/iges",
    ".ima":       "application/x-ima",
    ".imap":      "application/x-httpd-imap",
    ".inf":       "application/inf",
    ".ins":       "application/x-internett-signup",
    ".ip":        "application/x-ip2",
    ".isu":       "video/x-isvideo",
    ".it":        "audio/it",
    ".iv":        "application/x-inventor",
    ".ivr":       "i-world/i-vrml",
    ".ivy":       "application/x-livescreen",
    ".jam":       "audio/x-jam",
    ".jav":       "text/x-java-source",
    ".java":      "text/x-java-source",
    ".jcm":       "application/x-java-commerce",
    ".jfif-tbnl": "image/jpeg",
    ".jfif":      "image/jpeg",
    ".jnlp":      "application/x-java-jnlp-file",
    ".jpe":       "image/jpeg",
    ".jpeg":      "image/jpeg",
    ".jpg":       "image/jpeg",
    ".jps":       "image/x-jps",
    ".js":        "application/javascript",
    ".json":      "application/json",
    ".jut":       "image/jutvision",
    ".kar":       "audio/midi",
    ".karbon":    "application/vnd.kde.karbon",
    ".kfo":       "application/vnd.kde.kformula",
    ".flw":       "application/vnd.kde.kivio",
    ".kml":       "application/vnd.google-earth.kml+xml",
    ".kmz":       "application/vnd.google-earth.kmz",
    ".kon":       "application/vnd.kde.kontour",
    ".kpr":       "application/vnd.kde.kpresenter",
    ".kpt":       "application/vnd.kde.kpresenter",
    ".ksp":       "application/vnd.kde.kspread",
    ".kwd":       "application/vnd.kde.kword",
    ".kwt":       "application/vnd.kde.kword",
    ".ksh":       "text/x-scriptksh",
    ".la":        "audio/nspaudio",
    ".lam":       "audio/x-liveaudio",
    ".latex":     "application/x-latex",
    ".lha":       "application/lha",
    ".lhx":       "application/octet-stream",
    ".list":      "text/plain",
    ".lma":       "audio/nspaudio",
    ".log":       "text/plain",
    ".lsp":       "text/x-scriptlisp",
    ".lst":       "text/plain",
    ".lsx":       "text/x-la-asf",
    ".ltx":       "application/x-latex",
    ".lzh":       "application/octet-stream",
    ".lzx":       "application/lzx",
    ".m1v":       "video/mpeg",
    ".m2a":       "audio/mpeg",
    ".m2v":       "video/mpeg",
    ".m3u":       "audio/x-mpegurl",
    ".m":         "text/x-m",
    ".man":       "application/x-troff-man",
    ".manifest":  "text/cache-manifest",
    ".map":       "application/x-navimap",
    ".mar":       "text/plain",
    ".mbd":       "application/mbedlet",
    ".mc$":       "application/x-magic-cap-package-10",
    ".mcd":       "application/mcad",
    ".mcf":       "text/mcf",
    ".mcp":       "application/netmc",
    ".me":        "application/x-troff-me",
    ".mht":       "message/rfc822",
    ".mhtml":     "message/rfc822",
    ".mid":       "application/x-midi",
    ".midi":      "application/x-midi",
    ".mif":       "application/x-frame",
    ".mime":      "message/rfc822",
    ".mjf":       "audio/x-vndaudioexplosionmjuicemediafile",
    ".mjpg":      "video/x-motion-jpeg",
    ".mm":        "application/base64",
    ".mme":       "application/base64",
    ".mod":       "audio/mod",
    ".moov":      "video/quicktime",
    ".mov":       "video/quicktime",
    ".movie":     "video/x-sgi-movie",
    ".mp2":       "audio/mpeg",
    ".mp3":       "audio/mpeg3",
    ".mp4":       "video/mp4",
    ".mpa":       "audio/mpeg",
    ".mpc":       "application/x-project",
    ".mpe":       "video/mpeg",
    ".mpeg":      "video/mpeg",
    ".mpg":       "video/mpeg",
    ".mpga":      "audio/mpeg",
    ".mpp":       "application/vndms-project",
    ".mpt":       "application/x-project",
    ".mpv":       "application/x-project",
    ".mpx":       "application/x-project",
    ".mrc":       "application/marc",
    ".ms":        "application/x-troff-ms",
    ".mv":        "video/x-sgi-movie",
    ".my":        "audio/make",
    ".mzz":       "application/x-vndaudioexplosionmzz",
    ".nap":       "image/naplps",
    ".naplps":    "image/naplps",
    ".nc":        "application/x-netcdf",
    ".ncm":       "application/vndnokiaconfiguration-message",
    ".nif":       "image/x-niff",
    ".niff":      "image/x-niff",
    ".nix":       "application/x-mix-transfer",
    ".nsc":       "application/x-conference",
    ".nvd":       "application/x-navidoc",
    ".o":         "application/octet-stream",
    ".oda":       "application/oda",
    ".odb":       "application/vnd.oasis.opendocument.database",
    ".odc":       "application/vnd.oasis.opendocument.chart",
    ".odf":       "application/vnd.oasis.opendocument.formula",
    ".odg":       "application/vnd.oasis.opendocument.graphics",
    ".odi":       "application/vnd.oasis.opendocument.image",
    ".odm":       "application/vnd.oasis.opendocument.text-master",
    ".odp":       "application/vnd.oasis.opendocument.presentation",
    ".ods":       "application/vnd.oasis.opendocument.spreadsheet",
    ".odt":       "application/vnd.oasis.opendocument.text",
    ".oga":       "audio/ogg",
    ".ogg":       "audio/ogg",
    ".ogv":       "video/ogg",
    ".omc":       "application/x-omc",
    ".omcd":      "application/x-omcdatamaker",
    ".omcr":      "application/x-omcregerator",
    ".otc":       "application/vnd.oasis.opendocument.chart-template",
    ".otf":       "application/vnd.oasis.opendocument.formula-template",
    ".otg":       "application/vnd.oasis.opendocument.graphics-template",
    ".oth":       "application/vnd.oasis.opendocument.text-web",
    ".oti":       "application/vnd.oasis.opendocument.image-template",
    ".otm":       "application/vnd.oasis.opendocument.text-master",
    ".otp":       "application/vnd.oasis.opendocument.presentation-template",
    ".ots":       "application/vnd.oasis.opendocument.spreadsheet-template",
    ".ott":       "application/vnd.oasis.opendocument.text-template",
    ".p10":       "application/pkcs10",
    ".p12":       "application/pkcs-12",
    ".p7a":       "application/x-pkcs7-signature",
    ".p7c":       "application/pkcs7-mime",
    ".p7m":       "application/pkcs7-mime",
    ".p7r":       "application/x-pkcs7-certreqresp",
    ".p7s":       "application/pkcs7-signature",
    ".p":         "text/x-pascal",
    ".part":      "application/pro_eng",
    ".pas":       "text/pascal",
    ".pbm":       "image/x-portable-bitmap",
    ".pcl":       "application/vndhp-pcl",
    ".pct":       "image/x-pict",
    ".pcx":       "image/x-pcx",
    ".pdb":       "chemical/x-pdb",
    ".pdf":       "application/pdf",
    ".pfunk":     "audio/make",
    ".pgm":       "image/x-portable-graymap",
    ".pic":       "image/pict",
    ".pict":      "image/pict",
    ".pkg":       "application/x-newton-compatible-pkg",
    ".pko":       "application/vndms-pkipko",
    ".pl":        "text/x-scriptperl",
    ".plx":       "application/x-pixclscript",
    ".pm4":       "application/x-pagemaker",
    ".pm5":       "application/x-pagemaker",
    ".pm":        "text/x-scriptperl-module",
    ".png":       "image/png",
    ".pnm":       "application/x-portable-anymap",
    ".pot":       "application/mspowerpoint",
    ".pov":       "model/x-pov",
    ".ppa":       "application/vndms-powerpoint",
    ".ppm":       "image/x-portable-pixmap",
    ".pps":       "application/mspowerpoint",
    ".ppt":       "application/mspowerpoint",
    ".ppz":       "application/mspowerpoint",
    ".pre":       "application/x-freelance",
    ".prt":       "application/pro_eng",
    ".ps":        "application/postscript",
    ".psd":       "application/octet-stream",
    ".pvu":       "paleovu/x-pv",
    ".pwz":       "application/vndms-powerpoint",
    ".py":        "text/x-scriptphyton",
    ".pyc":       "application/x-bytecodepython",
    ".qcp":       "audio/vndqcelp",
    ".qd3":       "x-world/x-3dmf",
    ".qd3d":      "x-world/x-3dmf",
    ".qif":       "image/x-quicktime",
    ".qt":        "video/quicktime",
    ".qtc":       "video/x-qtc",
    ".qti":       "image/x-quicktime",
    ".qtif":      "image/x-quicktime",
    ".ra":        "audio/x-pn-realaudio",
    ".ram":       "audio/x-pn-realaudio",
    ".rar":       "application/x-rar-compressed",
    ".ras":       "application/x-cmu-raster",
    ".rast":      "image/cmu-raster",
    ".rexx":      "text/x-scriptrexx",
    ".rf":        "image/vndrn-realflash",
    ".rgb":       "image/x-rgb",
    ".rm":        "application/vndrn-realmedia",
    ".rmi":       "audio/mid",
    ".rmm":       "audio/x-pn-realaudio",
    ".rmp":       "audio/x-pn-realaudio",
    ".rng":       "application/ringing-tones",
    ".rnx":       "application/vndrn-realplayer",
    ".roff":      "application/x-troff",
    ".rp":        "image/vndrn-realpix",
    ".rpm":       "audio/x-pn-realaudio-plugin",
    ".rt":        "text/vndrn-realtext",
    ".rtf":       "text/richtext",
    ".rtx":       "text/richtext",
    ".rv":        "video/vndrn-realvideo",
    ".s":         "text/x-asm",
    ".s3m":       "audio/s3m",
    ".s7z":       "application/x-7z-compressed",
    ".saveme":    "application/octet-stream",
    ".sbk":       "application/x-tbook",
    ".scm":       "text/x-scriptscheme",
    ".sdml":      "text/plain",
    ".sdp":       "application/sdp",
    ".sdr":       "application/sounder",
    ".sea":       "application/sea",
    ".set":       "application/set",
    ".sgm":       "text/x-sgml",
    ".sgml":      "text/x-sgml",
    ".sh":        "text/x-scriptsh",
    ".shar":      "application/x-bsh",
    ".shtml":     "text/x-server-parsed-html",
    ".sid":       "audio/x-psid",
    ".skd":       "application/x-koan",
    ".skm":       "application/x-koan",
    ".skp":       "application/x-koan",
    ".skt":       "application/x-koan",
    ".sit":       "application/x-stuffit",
    ".sitx":      "application/x-stuffitx",
    ".sl":        "application/x-seelogo",
    ".smi":       "application/smil",
    ".smil":      "application/smil",
    ".snd":       "audio/basic",
    ".sol":       "application/solids",
    ".spc":       "text/x-speech",
    ".spl":       "application/futuresplash",
    ".spr":       "application/x-sprite",
    ".sprite":    "application/x-sprite",
    ".spx":       "audio/ogg",
    ".src":       "application/x-wais-source",
    ".ssi":       "text/x-server-parsed-html",
    ".ssm":       "application/streamingmedia",
    ".sst":       "application/vndms-pkicertstore",
    ".step":      "application/step",
    ".stl":       "application/sla",
    ".stp":       "application/step",
    ".sv4cpio":   "application/x-sv4cpio",
    ".sv4crc":    "application/x-sv4crc",
    ".svf":       "image/vnddwg",
    ".svg":       "image/svg+xml",
    ".svr":       "application/x-world",
    ".swf":       "application/x-shockwave-flash",
    ".t":         "application/x-troff",
    ".talk":      "text/x-speech",
    ".tar":       "application/x-tar",
    ".tbk":       "application/toolbook",
    ".tcl":       "text/x-scripttcl",
    ".tcsh":      "text/x-scripttcsh",
    ".tex":       "application/x-tex",
    ".texi":      "application/x-texinfo",
    ".texinfo":   "application/x-texinfo",
    ".text":      "text/plain",
    ".tgz":       "application/gnutar",
    ".tif":       "image/tiff",
    ".tiff":      "image/tiff",
    ".tr":        "application/x-troff",
    ".tsi":       "audio/tsp-audio",
    ".tsp":       "application/dsptype",
    ".tsv":       "text/tab-separated-values",
    ".turbot":    "image/florian",
    ".txt":       "text/plain",
    ".uil":       "text/x-uil",
    ".uni":       "text/uri-list",
    ".unis":      "text/uri-list",
    ".unv":       "application/i-deas",
    ".uri":       "text/uri-list",
    ".uris":      "text/uri-list",
    ".ustar":     "application/x-ustar",
    ".uu":        "text/x-uuencode",
    ".uue":       "text/x-uuencode",
    ".vcd":       "application/x-cdlink",
    ".vcf":       "text/x-vcard",
    ".vcard":     "text/x-vcard",
    ".vcs":       "text/x-vcalendar",
    ".vda":       "application/vda",
    ".vdo":       "video/vdo",
    ".vew":       "application/groupwise",
    ".viv":       "video/vivo",
    ".vivo":      "video/vivo",
    ".vmd":       "application/vocaltec-media-desc",
    ".vmf":       "application/vocaltec-media-file",
    ".voc":       "audio/voc",
    ".vos":       "video/vosaic",
    ".vox":       "audio/voxware",
    ".vqe":       "audio/x-twinvq-plugin",
    ".vqf":       "audio/x-twinvq",
    ".vql":       "audio/x-twinvq-plugin",
    ".vrml":      "application/x-vrml",
    ".vrt":       "x-world/x-vrt",
    ".vsd":       "application/x-visio",
    ".vst":       "application/x-visio",
    ".vsw":       "application/x-visio",
    ".w60":       "application/wordperfect60",
    ".w61":       "application/wordperfect61",
    ".w6w":       "application/msword",
    ".wav":       "audio/wav",
    ".wb1":       "application/x-qpro",
    ".wbmp":      "image/vnd.wap.wbmp",
    ".web":       "application/vndxara",
    ".wiz":       "application/msword",
    ".wk1":       "application/x-123",
    ".wmf":       "windows/metafile",
    ".wml":       "text/vnd.wap.wml",
    ".wmlc":      "application/vnd.wap.wmlc",
    ".wmls":      "text/vnd.wap.wmlscript",
    ".wmlsc":     "application/vnd.wap.wmlscriptc",
    ".word":      "application/msword",
    ".wp5":       "application/wordperfect",
    ".wp6":       "application/wordperfect",
    ".wp":        "application/wordperfect",
    ".wpd":       "application/wordperfect",
    ".wq1":       "application/x-lotus",
    ".wri":       "application/mswrite",
    ".wrl":       "application/x-world",
    ".wrz":       "model/vrml",
    ".wsc":       "text/scriplet",
    ".wsrc":      "application/x-wais-source",
    ".wtk":       "application/x-wintalk",
    ".x-png":     "image/png",
    ".xbm":       "image/x-xbitmap",
    ".xdr":       "video/x-amt-demorun",
    ".xgz":       "xgl/drawing",
    ".xif":       "image/vndxiff",
    ".xl":        "application/excel",
    ".xla":       "application/excel",
    ".xlb":       "application/excel",
    ".xlc":       "application/excel",
    ".xld":       "application/excel",
    ".xlk":       "application/excel",
    ".xll":       "application/excel",
    ".xlm":       "application/excel",
    ".xls":       "application/excel",
    ".xlt":       "application/excel",
    ".xlv":       "application/excel",
    ".xlw":       "application/excel",
    ".xm":        "audio/xm",
    ".xml":       "text/xml",
    ".xmz":       "xgl/movie",
    ".xpix":      "application/x-vndls-xpix",
    ".xpm":       "image/x-xpixmap",
    ".xsr":       "video/x-amt-showrun",
    ".xwd":       "image/x-xwd",
    ".xyz":       "chemical/x-pdb",
    ".z":         "application/x-compress",
    ".zip":       "application/zip",
    ".zoo":       "application/octet-stream",
    ".zsh":       "text/x-scriptzsh",
    ".docx":      "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    ".docm":      "application/vnd.ms-word.document.macroEnabled.12",
    ".dotx":      "application/vnd.openxmlformats-officedocument.wordprocessingml.template",
    ".dotm":      "application/vnd.ms-word.template.macroEnabled.12",
    ".xlsx":      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    ".xlsm":      "application/vnd.ms-excel.sheet.macroEnabled.12",
    ".xltx":      "application/vnd.openxmlformats-officedocument.spreadsheetml.template",
    ".xltm":      "application/vnd.ms-excel.template.macroEnabled.12",
    ".xlsb":      "application/vnd.ms-excel.sheet.binary.macroEnabled.12",
    ".xlam":      "application/vnd.ms-excel.addin.macroEnabled.12",
    ".pptx":      "application/vnd.openxmlformats-officedocument.presentationml.presentation",
    ".pptm":      "application/vnd.ms-powerpoint.presentation.macroEnabled.12",
    ".ppsx":      "application/vnd.openxmlformats-officedocument.presentationml.slideshow",
    ".ppsm":      "application/vnd.ms-powerpoint.slideshow.macroEnabled.12",
    ".potx":      "application/vnd.openxmlformats-officedocument.presentationml.template",
    ".potm":      "application/vnd.ms-powerpoint.template.macroEnabled.12",
    ".ppam":      "application/vnd.ms-powerpoint.addin.macroEnabled.12",
    ".sldx":      "application/vnd.openxmlformats-officedocument.presentationml.slide",
    ".sldm":      "application/vnd.ms-powerpoint.slide.macroEnabled.12",
    ".thmx":      "application/vnd.ms-officetheme",
    ".onetoc":    "application/onenote",
    ".onetoc2":   "application/onenote",
    ".onetmp":    "application/onenote",
    ".onepkg":    "application/onenote",
    ".xpi":       "application/x-xpinstall",
}

func init() {
    for ext, typ := range types {
        // skip errors
        mime.AddExtensionType(ext, typ)
    }
}

// typeByExtension returns the MIME type associated with the file extension ext.
// The extension ext should begin with a leading dot, as in ".html".
// When ext has no associated type, typeByExtension returns "".
//
// Extensions are looked up first case-sensitively, then case-insensitively.
//
// The built-in table is small but on unix it is augmented by the local
// system's mime.types file(s) if available under one or more of these
// names:
//
//   /etc/mime.types
//   /etc/apache2/mime.types
//   /etc/apache/mime.types
//
// On Windows, MIME types are extracted from the registry.
//
// Text types have the charset parameter set to "utf-8" by default.
func TypeByExtension(fullfilename string) string {
    ext := filepath.Ext(fullfilename)
    typ := mime.TypeByExtension(ext)

    // mime.TypeByExtension returns as text/plain; | charset=utf-8 the static .js (not always)
    if ext == ".js" && (typ == "text/plain" || typ == "text/plain; charset=utf-8") {

        if ext == ".js" {
            typ = "application/javascript"
        }
    }
    return typ
}

Hope that helped you and other users, don't hesitate to post again if you have more questions!

Failed to load ApplicationContext from Unit Test: FileNotFound

For me, I was missing @ActiveProfile at my test class

@ActiveProfiles("sandbox")
class MyTestClass...

Why is it that "No HTTP resource was found that matches the request URI" here?

WebApiConfig.Register(GlobalConfiguration.Configuration); should be on top.

Open firewall port on CentOS 7

Fedora, did it via iptables

sudo iptables -I INPUT -p tcp --dport 3030 -j ACCEPT
sudo service iptables save

Seems to work

What exactly does the Access-Control-Allow-Credentials header do?

By default, CORS does not include cookies on cross-origin requests. This is different from other cross-origin techniques such as JSON-P. JSON-P always includes cookies with the request, and this behavior can lead to a class of vulnerabilities called cross-site request forgery, or CSRF.

In order to reduce the chance of CSRF vulnerabilities in CORS, CORS requires both the server and the client to acknowledge that it is ok to include cookies on requests. Doing this makes cookies an active decision, rather than something that happens passively without any control.

The client code must set the withCredentials property on the XMLHttpRequest to true in order to give permission.

However, this header alone is not enough. The server must respond with the Access-Control-Allow-Credentials header. Responding with this header to true means that the server allows cookies (or other user credentials) to be included on cross-origin requests.

You also need to make sure your browser isn't blocking third-party cookies if you want cross-origin credentialed requests to work.

Note that regardless of whether you are making same-origin or cross-origin requests, you need to protect your site from CSRF (especially if your request includes cookies).

How to tell 'PowerShell' Copy-Item to unconditionally copy files

From the documentation (help copy-item -full):

-force <SwitchParameter>
    Allows cmdlet to override restrictions such as renaming existing files as long as security is not compromised.

    Required?                    false
    Position?                    named
    Default value                False
    Accept pipeline input?       false
    Accept wildcard characters?  false

How to get the size of a string in Python?

Python 3:

user225312's answer is correct:

A. To count number of characters in str object, you can use len() function:

>>> print(len('please anwser my question'))
25

B. To get memory size in bytes allocated to store str object, you can use sys.getsizeof() function

>>> from sys import getsizeof
>>> print(getsizeof('please anwser my question'))
50

Python 2:

It gets complicated for Python 2.

A. The len() function in Python 2 returns count of bytes allocated to store encoded characters in a str object.

Sometimes it will be equal to character count:

>>> print(len('abc'))
3

But sometimes, it won't:

>>> print(len('???'))  # String contains Cyrillic symbols
6

That's because str can use variable-length encoding internally. So, to count characters in str you should know which encoding your str object is using. Then you can convert it to unicode object and get character count:

>>> print(len('???'.decode('utf8'))) #String contains Cyrillic symbols 
3

B. The sys.getsizeof() function does the same thing as in Python 3 - it returns count of bytes allocated to store the whole string object

>>> print(getsizeof('???'))
27
>>> print(getsizeof('???'.decode('utf8')))
32

unix - count of columns in file

Unless you're using spaces in there, you should be able to use | wc -w on the first line.

wc is "Word Count", which simply counts the words in the input file. If you send only one line, it'll tell you the amount of columns.

Using SVG as background image

Try placing it on your body

body {
    height: 100%;
    background-image: url(../img/bg.svg);
    background-size:100% 100%;
    -o-background-size: 100% 100%;
    -webkit-background-size: 100% 100%;
    background-size:cover;
}

Get random integer in range (x, y]?

How about:

Random generator = new Random();
int i = 10 - generator.nextInt(10);

AngularJS: ng-model not binding to ng-checked for checkboxes

You don't need ng-checked when you use ng-model. If you're performing CRUD on your HTML Form, just create a model for CREATE mode that is consistent with your EDIT mode during the data-binding:

CREATE Mode: Model with default values only

$scope.dataModel = {
   isItemSelected: true,
   isApproved: true,
   somethingElse: "Your default value"
}

EDIT Mode: Model from database

$scope.dataModel = getFromDatabaseWithSameStructure()

Then whether EDIT or CREATE mode, you can consistently make use of your ng-model to sync with your database.

HAProxy redirecting http to https (ssl)

frontend unsecured *:80
    mode http
    redirect location https://foo.bar.com

Updating version numbers of modules in a multi-module Maven project

I encourage you to read the Maven Book about multi-module (reactor) builds.

I meant in particular the following:

<parent>
    <artifactId>xyz-application</artifactId>
    <groupId>com.xyz</groupId>
    <version>2.50.0.g</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.xyz</groupId>
<artifactId>xyz-Library</artifactId>
<version>2.50.0.g</version>

should be changed into. Here take care about the not defined version only in parent part it is defined.

<modelVersion>4.0.0</modelVersion>

<parent>
    <artifactId>xyz-application</artifactId>
    <groupId>com.xyz</groupId>
    <version>2.50.0.g</version>
</parent>
<groupId>com.xyz</groupId>
<artifactId>xyz-Library</artifactId>

This is a better link.

how to return a char array from a function in C

Daniel is right: http://ideone.com/kgbo1C#view_edit_box

Change

test=substring(i,j,*s);

to

test=substring(i,j,s);  

Also, you need to forward declare substring:

char *substring(int i,int j,char *ch);

int main // ...

Add (insert) a column between two columns in a data.frame

You can use the append() function to insert items into vectors or lists (dataframes are lists). Simply:

df <- data.frame(a=c(1,2), b=c(3,4), c=c(5,6))

df <- as.data.frame(append(df, list(d=df$b+df$c), after=2))

Or, if you want to specify the position by name use which:

df <- as.data.frame(append(df, list(d=df$b+df$c), after=which(names(df)=="b")))

Android Drawing Separator/Divider Line in Layout?

It adds a horizontal divider to anywhere in your layout.

    <TextView
       style="?android:listSeparatorTextViewStyle"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"/>

jQuery: get data attribute

This works for me

$('.someclass').click(function() {
    $varName = $(this).data('fulltext');
    console.log($varName);
});

Is there an easy way to check the .NET Framework version?

If your machine is connected to the internet, going to smallestdotnet, downloading and executing the .NET Checker is probably the easiest way.

If you need the actual method to deterine the version look at its source on github, esp. the Constants.cs which will help you for .net 4.5 and later, where the Revision part is the relvant one:

                           { int.MinValue, "4.5" },
                           { 378389, "4.5" },
                           { 378675, "4.5.1" },
                           { 378758, "4.5.1" },
                           { 379893, "4.5.2" },
                           { 381029, "4.6 Preview" },
                           { 393273, "4.6 RC1" },
                           { 393292, "4.6 RC2" },
                           { 393295, "4.6" },
                           { 393297, "4.6" },
                           { 394254, "4.6.1" },
                           { 394271, "4.6.1" },
                           { 394747, "4.6.2 Preview" },
                           { 394748, "4.6.2 Preview" },
                           { 394757, "4.6.2 Preview" },
                           { 394802, "4.6.2" },
                           { 394806, "4.6.2" },

Is there a Max function in SQL Server that takes two values like Math.Max in .NET?

Why not try IIF function (requires SQL Server 2012 and later)

IIF(a>b, a, b)

That's it.

(Hint: be careful about either would be null, since the result of a>b will be false whenever either is null. So b will be the result in this case)

Register DLL file on Windows Server 2008 R2

Error 0x80040154 is COM's REGDB_E_CLASSNOTREG, which means "Class not registered". Basically, a COM class is not declared in the installation registry.

If you get this error when trying to register a DLL, it may be possible that the registration code for this DLL is trying to instantiate another COM server (DLL or EXE) which is missing or not registered on this installation.

If you don't have access to the original DLL source, I would suggest to use SysInternal's Process Monitor tool to track COM registry lookups (there use to be a more simple RegMon tool but it may not work any more).

You should put a filter on the working process (here: Regsvr32.exe) to only capture what's interesting. Then you should look for queries on HKEY_CLASSES_ROOT\[a progid, a string] that fail (with the NAME_NOT_FOUND error for example), or queries on HKEY_CLASSES_ROOT\CLSID\[a guid] that fail.

PS: Unfortunately, there may be many thing that seem to fail on a perfectly working Windows system, so you'll have to study all errors carefully. Good luck :-)

How do I wait for an asynchronously dispatched block to finish?

Generally don't use any of these answers, they often won't scale (there's exceptions here and there, sure)

These approaches are incompatible with how GCD is intended to work and will end up either causing deadlocks and/or killing the battery by nonstop polling.

In other words, rearrange your code so that there is no synchronous waiting for a result, but instead deal with a result being notified of change of state (eg callbacks/delegate protocols, being available, going away, errors, etc.). (These can be refactored into blocks if you don't like callback hell.) Because this is how to expose real behavior to the rest of the app than hide it behind a false façade.

Instead, use NSNotificationCenter, define a custom delegate protocol with callbacks for your class. And if you don't like mucking with delegate callbacks all over, wrap them into a concrete proxy class that implements the custom protocol and saves the various block in properties. Probably also provide convenience constructors as well.

The initial work is slightly more but it will reduce the number of awful race-conditions and battery-murdering polling in the long-run.

(Don't ask for an example, because it's trivial and we had to invest the time to learn objective-c basics too.)

Distribution certificate / private key not installed

Click on Manage Certificates->Apple Distribution->Done

How to move a git repository into another directory and make that directory a git repository?

It's very simple. Git doesn't care about what's the name of its directory. It only cares what's inside. So you can simply do:

# copy the directory into newrepo dir that exists already (else create it)
$ cp -r gitrepo1 newrepo

# remove .git from old repo to delete all history and anything git from it
$ rm -rf gitrepo1/.git

Note that the copy is quite expensive if the repository is large and with a long history. You can avoid it easily too:

# move the directory instead
$ mv gitrepo1 newrepo

# make a copy of the latest version
# Either:
$ mkdir gitrepo1; cp -r newrepo/* gitrepo1/  # doesn't copy .gitignore (and other hidden files)

# Or:
$ git clone --depth 1 newrepo gitrepo1; rm -rf gitrepo1/.git

# Or (look further here: http://stackoverflow.com/q/1209999/912144)
$ git archive --format=tar --remote=<repository URL> HEAD | tar xf -

Once you create newrepo, the destination to put gitrepo1 could be anywhere, even inside newrepo if you want it. It doesn't change the procedure, just the path you are writing gitrepo1 back.

How to pass arguments within docker-compose?

This can now be done as of docker-compose v2+ as part of the build object;

docker-compose.yml

version: '2'
services:
    my_image_name:
        build:
            context: . #current dir as build context
            args:
                var1: 1
                var2: c

See the docker compose docs.

In the above example "var1" and "var2" will be sent to the build environment.

Note: any env variables (specified by using the environment block) which have the same name as args variable(s) will override that variable.

Clear back stack using fragments

I just wanted to add :--

Popping out from backstack using following

fragmentManager.popBackStack()

is just about removing the fragments from the transaction, no way it is going to remove the fragment from the screen. So ideally, it may not be visible to you but there may be two or three fragments stacked over each other, and on back key press the UI may look cluttered,stacked.

Just taking a simple example:-

Suppose you have a fragmentA which loads Fragmnet B using fragmentmanager.replace() and then we do addToBackStack, to save this transaction. So the flow is :--

STEP 1 -> FragmentA->FragmentB (we moved to FragmentB, but Fragment A is in background, not visible).

Now You do some work in fragmentB and press the Save button—which after saving should go back to fragmentA.

STEP 2-> On save of FragmentB, we go back to FragmentA.

STEP 3 ->So common mistake would be... in Fragment B,we will do fragment Manager.replace() fragmentB with fragmentA.

But what actually is happenening, we are loading Fragment A again, replacing FragmentB . So now there are two FragmentA (one from STEP-1, and one from this STEP-3).

Two instances of FragmentsA are stacked over each other, which may not be visible , but it is there.

So even if we do clear the backstack by above methods, the transaction is cleared but not the actual fragments. So ideally in such a particular case, on press of save button you simply need to go back to fragmentA by simply doing fm.popBackStack() or fm.popBackImmediate().

So correct Step3-> fm.popBackStack() go back to fragmentA, which is already in memory.

Initialise numpy array of unknown length

You can do this:

a = np.array([])
for x in y:
    a = np.append(a, x)

Run JavaScript in Visual Studio Code

I would suggest you to use a simple and easy plugin called as Quokka which is very popular these days and helps you debug your code on the go. Quokka.js. One biggest advantage in using this plugin is that you save a lot of time to go on web browser and evaluate your code, with help of this you can see everything happening in VS code, which saves a lot of time.

How to build jars from IntelliJ properly?

Some of the other answers are useless because as soon as you re-import the IntelliJ IDEA project from the maven project, all changes will be lost.

The building of the jar needs to be triggered by a run/debug configuration, not by the project settings.

Jetbrains has a nice description of how you can accomplish this here:

https://www.jetbrains.com/help/idea/maven.html

Scroll down to the section called "Configuring triggers for Maven goals".

(The only disadvantage of their description is that their screenshots are in the default black-on-white color scheme instead of the super-awesome darcula theme. Ugh!)

So, basically, what you do is that you open the "Maven Projects" panel, you find the project of interest, (in your case, the project that builds your jar,) underneath it you find the maven goal that you want to execute, (usually the "package" goal creates jars,) you open up the context menu on it, (right-click on a Windows machine,) and there will be an "Execute before Run/Debug..." option that you can select and it will take you by the hand from there. Really easy.

How do I write output in same place on the console?

You can also use the carriage return:

sys.stdout.write("Download progress: %d%%   \r" % (progress) )
sys.stdout.flush()

submit form on click event using jquery

Using jQuery button click

$('#button_id').on('click',function(){
     $('#form_id').submit();
 });

Bootstrap Element 100% Width

The following answer is not exactly optimal by any measure, but I needed something that maintains its position within the container whilst it stretches the inner div fully.

https://jsfiddle.net/fah5axm5/

$(function() {
    $(window).on('load resize', ppaFullWidth);

    function ppaFullWidth() {
        var $elements = $('[data-ppa-full-width="true"]');
        $.each( $elements, function( key, item ) {
            var $el = $(this);
            var $container = $el.closest('.container');
            var margin = parseInt($container.css('margin-left'), 10);
            var padding = parseInt($container.css('padding-left'), 10)
            var offset = margin + padding;

            $el.css({
                position: "relative",
                left: -offset,
                "box-sizing": "border-box",
                width: $(window).width(),
                "padding-left": offset + "px",
                "padding-right": offset + "px"
            });
        });
    }
});

What is the default Precision and Scale for a Number in Oracle?

I expand on spectra‘s answer so people don’t have to try it for themselves.

This was done on Oracle Database 11g Express Edition Release 11.2.0.2.0 - Production.

CREATE TABLE CUSTOMERS
(
  CUSTOMER_ID NUMBER NOT NULL,
  FOO FLOAT NOT NULL,
  JOIN_DATE DATE NOT NULL,
  CUSTOMER_STATUS VARCHAR2(8) NOT NULL,
  CUSTOMER_NAME VARCHAR2(20) NOT NULL,
  CREDITRATING VARCHAR2(10)
);

select column_name, data_type, nullable, data_length, data_precision, data_scale
from user_tab_columns where table_name ='CUSTOMERS'; 

Which yields

COLUMN_NAME      DATA_TYPE  NULLABLE DATA_LENGTH DATA_PRECISION DATA_SCALE
CUSTOMER_ID      NUMBER     N        22        
FOO              FLOAT      N        22          126    
JOIN_DATE        DATE       N        7        
CUSTOMER_STATUS  VARCHAR2   N        8        
CUSTOMER_NAME    VARCHAR2   N        20        
CREDITRATING     VARCHAR2   Y        10    

UILabel with text of two different colors

Since iOS 6, UIKit supports drawing attributed strings, so no extension or replacement is needed.

From UILabel:

@property(nonatomic, copy) NSAttributedString *attributedText;

You just need to build up your NSAttributedString. There are basically two ways:

  1. Append chunks of text with the same attributes - for each part create one NSAttributedString instance and append them to one NSMutableAttributedString

  2. Create attributed text from plain string and then add attributed for given ranges – find the range of your number (or whatever) and apply different color attribute on that.

sed whole word search and replace

In one of my machine, delimiting the word with "\b" (without the quotes) did not work. The solution was to use "\<" for starting delimiter and "\>" for ending delimiter.

To explain with Joakim Lundberg's example:

$ echo "bar embarassment" | sed "s/\<bar\>/no bar/g"
no bar embarassment

Extract data from log file in specified range of time

You can use this for getting current and log times:

#!/bin/bash

log="log_file_name"
while read line
do
  current_hours=`date | awk 'BEGIN{FS="[ :]+"}; {print $4}'`
  current_minutes=`date | awk 'BEGIN{FS="[ :]+"}; {print $5}'`
  current_seconds=`date | awk 'BEGIN{FS="[ :]+"}; {print $6}'`

  log_file_hours=`echo $line | awk 'BEGIN{FS="[ [/:]+"}; {print  $7}'`
  log_file_minutes=`echo $line | awk 'BEGIN{FS="[ [/:]+"}; {print  $8}'`
  log_file_seconds=`echo $line | awk 'BEGIN{FS="[ [/:]+"}; {print  $9}'`    
done < $log

And compare log_file_* and current_* variables.

Subprocess check_output returned non-zero exit status 1

The word check_ in the name means that if the command (the shell in this case that returns the exit status of the last command (yum in this case)) returns non-zero status then it raises CalledProcessError exception. It is by design. If the command that you want to run may return non-zero status on success then either catch this exception or don't use check_ methods. You could use subprocess.call in your case because you are ignoring the captured output, e.g.:

import subprocess

rc = subprocess.call(['grep', 'pattern', 'file'],
                     stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
if rc == 0: # found
   ...
elif rc == 1: # not found
   ...
elif rc > 1: # error
   ...

You don't need shell=True to run the commands from your question.

How do I get Bin Path?

Path.GetDirectoryName(Application.ExecutablePath)

eg. value:

C:\Projects\ConsoleApplication1\bin\Debug

Connecting to remote URL which requires authentication using Java

There's a native and less intrusive alternative, which works only for your call.

URL url = new URL(“location address”);
URLConnection uc = url.openConnection();
String userpass = username + ":" + password;
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
uc.setRequestProperty ("Authorization", basicAuth);
InputStream in = uc.getInputStream();

Is a LINQ statement faster than a 'foreach' loop?

It should probably be noted that the for loop is faster than the foreach. So for the original post, if you are worried about performance on a critical component like a renderer, use a for loop.

Reference: In .NET, which loop runs faster, 'for' or 'foreach'?

How to get input text value from inside td

I'm having a hard time figuring out what exactly you're looking for here, so hope I'm not way off base.

I'm assuming what you mean is that when a keyup event occurs on the input with class "start" you want to get the values of all the inputs in neighbouring <td>s:

    $('.start').keyup(function() {
        var otherInputs = $(this).parents('td').siblings().find('input');

        for(var i = 0; i < otherInputs.length; i++) {
            alert($(otherInputs[i]).val());
        }
        return false;
    });

Stopping Excel Macro executution when pressing Esc won't work

I forgot to comment out a line with a MsgBox before executing my macro. Meaning I'd have to click OK over a hundred thousand times. The ESC key was just escaping the message box but not stopping the execution of the macro. Holding the ESC key continuously for a few seconds helped me stop the execution of the code.

PostgreSQL: Drop PostgreSQL database through command line

Try this. Note there's no database specified - it just runs "on the server"

psql -U postgres -c "drop database databasename"

If that doesn't work, I have seen a problem with postgres holding onto orphaned prepared statements.
To clean them up, do this:

SELECT * FROM pg_prepared_xacts;

then for every id you see, run this:

ROLLBACK PREPARED '<id>';

How do I get the type of a variable?

#include <typeinfo>

...
string s = typeid(YourClass).name()

Best practices for Storyboard login screen, handling clearing of data upon logout

I use this to check for first launch:

- (NSInteger) checkForFirstLaunch
{
    NSInteger result = 0; //no first launch

    // Get current version ("Bundle Version") from the default Info.plist file
    NSString *currentVersion = (NSString*)[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
    NSArray *prevStartupVersions = [[NSUserDefaults standardUserDefaults] arrayForKey:@"prevStartupVersions"];
    if (prevStartupVersions == nil)
    {
        // Starting up for first time with NO pre-existing installs (e.g., fresh
        // install of some version)
        [[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObject:currentVersion] forKey:@"prevStartupVersions"];
        result = 1; //first launch of the app
    } else {
        if (![prevStartupVersions containsObject:currentVersion])
        {
            // Starting up for first time with this version of the app. This
            // means a different version of the app was alread installed once
            // and started.
            NSMutableArray *updatedPrevStartVersions = [NSMutableArray arrayWithArray:prevStartupVersions];
            [updatedPrevStartVersions addObject:currentVersion];
            [[NSUserDefaults standardUserDefaults] setObject:updatedPrevStartVersions forKey:@"prevStartupVersions"];
            result = 2; //first launch of this version of the app
        }
    }

    // Save changes to disk
    [[NSUserDefaults standardUserDefaults] synchronize];

    return result;
}

(if the user deletes the app and re-installs it, it counts like a first launch)

In the AppDelegate I check for first launch and create a navigation-controller with the login screens (login and register), which I put on top of the current main window:

[self.window makeKeyAndVisible];

if (firstLaunch == 1) {
    UINavigationController *_login = [[UINavigationController alloc] initWithRootViewController:loginController];
    [self.window.rootViewController presentViewController:_login animated:NO completion:nil];
}

As this is on top of the regular view controller it's independent from the rest of your app and you can just dismiss the view controller, if you don't need it anymore. And you can also present the view this way, if the user presses a button manually.

BTW: I save the login-data from my users like this:

KeychainItemWrapper *keychainItem = [[KeychainItemWrapper alloc] initWithIdentifier:@"com.youridentifier" accessGroup:nil];
[keychainItem setObject:password forKey:(__bridge id)(kSecValueData)];
[keychainItem setObject:email forKey:(__bridge id)(kSecAttrAccount)];

For the logout: I switched away from CoreData (too slow) and use NSArrays and NSDictionaries to manage my data now. Logout just means to empty those arrays and dictionaries. Plus I make sure to set my data in viewWillAppear.

That's it.

Resizing UITableView to fit content

Swift Solution

Follow these steps:

  1. Set the height constraint for the table from the storyboard.

  2. Drag the height constraint from the storyboard and create @IBOutlet for it in the view controller file.

    @IBOutlet var tableHeight: NSLayoutConstraint!
    
  3. Then you can change the height for the table dynamicaly using this code:

    override func viewWillLayoutSubviews() {
        super.updateViewConstraints()
        self.tableHeight?.constant = self.table.contentSize.height
    }
    

If the last row is cut off, try to call viewWillLayoutSubviews() in willDisplay cell function:

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    self.viewWillLayoutSubviews()
}

Capturing standard out and error with Start-Process

I also had this issue and ended up using Andy's code to create a function to clean things up when multiple commands need to be run.

It'll return stderr, stdout, and exit codes as objects. One thing to note: the function won't accept .\ in the path; full paths must be used.

Function Execute-Command ($commandTitle, $commandPath, $commandArguments)
{
    $pinfo = New-Object System.Diagnostics.ProcessStartInfo
    $pinfo.FileName = $commandPath
    $pinfo.RedirectStandardError = $true
    $pinfo.RedirectStandardOutput = $true
    $pinfo.UseShellExecute = $false
    $pinfo.Arguments = $commandArguments
    $p = New-Object System.Diagnostics.Process
    $p.StartInfo = $pinfo
    $p.Start() | Out-Null
    $p.WaitForExit()
    [pscustomobject]@{
        commandTitle = $commandTitle
        stdout = $p.StandardOutput.ReadToEnd()
        stderr = $p.StandardError.ReadToEnd()
        ExitCode = $p.ExitCode
    }
}

Here's how to use it:

$DisableACMonitorTimeOut = Execute-Command -commandTitle "Disable Monitor Timeout" -commandPath "C:\Windows\System32\powercfg.exe" -commandArguments " -x monitor-timeout-ac 0"

Remove legend ggplot 2.2

As the question and user3490026's answer are a top search hit, I have made a reproducible example and a brief illustration of the suggestions made so far, together with a solution that explicitly addresses the OP's question.

One of the things that ggplot2 does and which can be confusing is that it automatically blends certain legends when they are associated with the same variable. For instance, factor(gear) appears twice, once for linetype and once for fill, resulting in a combined legend. By contrast, gear has its own legend entry as it is not treated as the same as factor(gear). The solutions offered so far usually work well. But occasionally, you may need to override the guides. See my last example at the bottom.

# reproducible example:
library(ggplot2)
p <- ggplot(data = mtcars, aes(x = mpg, y = disp, group = gear)) +
geom_point(aes(color = vs)) +
geom_point(aes(shape = factor(cyl))) +
geom_line(aes(linetype = factor(gear))) +
geom_smooth(aes(fill = factor(gear), color = gear)) + 
theme_bw() 

enter image description here

Remove all legends: @user3490026

p + theme(legend.position = "none")

Remove all legends: @duhaime

p + guides(fill = FALSE, color = FALSE, linetype = FALSE, shape = FALSE)

Turn off legends: @Tjebo

ggplot(data = mtcars, aes(x = mpg, y = disp, group = gear)) +
geom_point(aes(color = vs), show.legend = FALSE) +
geom_point(aes(shape = factor(cyl)), show.legend = FALSE) +
geom_line(aes(linetype = factor(gear)), show.legend = FALSE) +
geom_smooth(aes(fill = factor(gear), color = gear), show.legend = FALSE) + 
theme_bw() 

Remove fill so that linetype becomes visible

p + guides(fill = FALSE)

Same as above via the scale_fill_ function:

p + scale_fill_discrete(guide = FALSE)

And now one possible answer to the OP's request

"to keep the legend of one layer (smooth) and remove the legend of the other (point)"

Turn some on some off ad-hoc post-hoc

p + guides(fill = guide_legend(override.aes = list(color = NA)), 
           color = FALSE, 
           shape = FALSE)  

enter image description here

jquery can't get data attribute value

Changing the casing to all lowercases worked for me.

How to get UTF-8 working in Java webapps?

I think you summed it up quite well in your own answer.

In the process of UTF-8-ing(?) from end to end you might also want to make sure java itself is using UTF-8. Use -Dfile.encoding=utf-8 as parameter to the JVM (can be configured in catalina.bat).

Check if element found in array c++

You would just do the same thing, looping through the array to search for the term you want. Of course if it's a sorted array this would be much faster, so something similar to prehaps:

for(int i = 0; i < arraySize; i++){
     if(array[i] == itemToFind){
         break;
     }
}

Log exception with traceback

You can log all uncaught exceptions on the main thread by assigning a handler to sys.excepthook, perhaps using the exc_info parameter of Python's logging functions:

import sys
import logging

logging.basicConfig(filename='/tmp/foobar.log')

def exception_hook(exc_type, exc_value, exc_traceback):
    logging.error(
        "Uncaught exception",
        exc_info=(exc_type, exc_value, exc_traceback)
    )

sys.excepthook = exception_hook

raise Exception('Boom')

If your program uses threads, however, then note that threads created using threading.Thread will not trigger sys.excepthook when an uncaught exception occurs inside them, as noted in Issue 1230540 on Python's issue tracker. Some hacks have been suggested there to work around this limitation, like monkey-patching Thread.__init__ to overwrite self.run with an alternative run method that wraps the original in a try block and calls sys.excepthook from inside the except block. Alternatively, you could just manually wrap the entry point for each of your threads in try/except yourself.

Changing the maximum length of a varchar column?

In Oracle SQL Developer

ALTER TABLE car_details MODIFY torque VARCHAR(100);

Get last n lines of a file, similar to tail

Update @papercrane solution to python3. Open the file with open(filename, 'rb') and:

def tail(f, window=20):
    """Returns the last `window` lines of file `f` as a list.
    """
    if window == 0:
        return []

    BUFSIZ = 1024
    f.seek(0, 2)
    remaining_bytes = f.tell()
    size = window + 1
    block = -1
    data = []

    while size > 0 and remaining_bytes > 0:
        if remaining_bytes - BUFSIZ > 0:
            # Seek back one whole BUFSIZ
            f.seek(block * BUFSIZ, 2)
            # read BUFFER
            bunch = f.read(BUFSIZ)
        else:
            # file too small, start from beginning
            f.seek(0, 0)
            # only read what was not read
            bunch = f.read(remaining_bytes)

        bunch = bunch.decode('utf-8')
        data.insert(0, bunch)
        size -= bunch.count('\n')
        remaining_bytes -= BUFSIZ
        block -= 1

    return ''.join(data).splitlines()[-window:]

Laravel Eloquent groupBy() AND also return count of each group

This is working for me:

$user_info = DB::table('usermetas')
                 ->select('browser', DB::raw('count(*) as total'))
                 ->groupBy('browser')
                 ->get();

PHP - Extracting a property from an array of objects

function extract_ids($cats){
    $res = array();
    foreach($cats as $k=>$v) {
        $res[]= $v->id;
    }
    return $res
}

and use it in one line:

$ids = extract_ids($cats);

Measuring function execution time in R

You can use Sys.time(). However, when you record the time difference in a table or a csv file, you cannot simply say end - start. Instead, you should define the unit:

f_name <- function (args*){
start <- Sys.time()
""" You codes here """
end <- Sys.time()
total_time <- as.numeric (end - start, units = "mins") # or secs ... 
}

Then you can use total_time which has a proper format.

How to download a file from a URL in C#?

Include this namespace

using System.Net;

Download Asynchronously and put a ProgressBar to show the status of the download within the UI Thread Itself

private void BtnDownload_Click(object sender, RoutedEventArgs e)
{
    using (WebClient wc = new WebClient())
    {
        wc.DownloadProgressChanged += wc_DownloadProgressChanged;
        wc.DownloadFileAsync (
            // Param1 = Link of file
            new System.Uri("http://www.sayka.com/downloads/front_view.jpg"),
            // Param2 = Path to save
            "D:\\Images\\front_view.jpg"
        );
    }
}
// Event to track the progress
void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    progressBar.Value = e.ProgressPercentage;
}

Why is String immutable in Java?

String class is FINAL it mean you can't create any class to inherit it and change the basic structure and make the Sting mutable.

Another thing instance variable and methods of String class that are provided are such that you can't change String object once created.

The reason what you have added doesn't make the String immutable at all.This all says how the String is stored in heap.Also string pool make the huge difference in performance

How to get text box value in JavaScript



The problem is that you made a Tiny mistake!

This is the JS code I use:

var jobName = document.getElementById("txtJob").value;

You should not use name="". instead use id="".

Apache is not running from XAMPP Control Panel ( Error: Apache shutdown unexpectedly. This may be due to a blocked port)

Even if you've configured Apache to listen on another port, you will still get this error if another program is using the default SSL port 443.

What you also need to edit is the http-ssl.conf file and alter the line Listen 443 and change the port number there.

How to evaluate a boolean variable in an if block in bash?

Note that the if $myVar; then ... ;fi construct has a security problem you might want to avoid with

case $myvar in
  (true)    echo "is true";;
  (false)   echo "is false";;
  (rm -rf*) echo "I just dodged a bullet";;
esac

You might also want to rethink why if [ "$myvar" = "true" ] appears awkward to you. It's a shell string comparison that beats possibly forking a process just to obtain an exit status. A fork is a heavy and expensive operation, while a string comparison is dead cheap. Think a few CPU cycles versus several thousand. My case solution is also handled without forks.

What's a simple way to get a text input popup dialog box on an iPhone

UIAlertview *alt = [[UIAlertView alloc]initWithTitle:@"\n\n\n" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];

UILabel *lbl1 = [[UILabel alloc]initWithFrame:CGRectMake(25,17, 100, 30)];
lbl1.text=@"User Name";

UILabel *lbl2 = [[UILabel alloc]initWithFrame:CGRectMake(25, 60, 80, 30)];
lbl2.text = @"Password";

UITextField *username=[[UITextField alloc]initWithFrame:CGRectMake(130, 17, 130, 30)];
UITextField *password=[[UITextField alloc]initWithFrame:CGRectMake(130, 60, 130, 30)];

lbl1.textColor = [UIColor whiteColor];
lbl2.textColor = [UIColor whiteColor];

[lbl1 setBackgroundColor:[UIColor clearColor]];
[lbl2 setBackgroundColor:[UIColor clearColor]];

username.borderStyle = UITextBorderStyleRoundedRect;
password.borderStyle = UITextBorderStyleRoundedRect;

[alt addSubview:lbl1];
[alt addSubview:lbl2];
[alt addSubview:username];
[alt addSubview:password];

[alt show];

Command output redirect to file and terminal

In case somebody needs to append the output and not overriding, it is possible to use "-a" or "--append" option of "tee" command :

ls 2>&1 | tee -a /tmp/ls.txt
ls 2>&1 | tee --append /tmp/ls.txt

Table and Index size in SQL Server

--Gets the size of each index for the specified table
DECLARE @TableName sysname = N'SomeTable';

SELECT i.name AS IndexName
      ,8 * SUM(s.used_page_count) AS IndexSizeKB
FROM sys.indexes AS i
    INNER JOIN sys.dm_db_partition_stats AS s 
        ON i.[object_id] = s.[object_id] AND i.index_id = s.index_id
WHERE s.[object_id] = OBJECT_ID(@TableName, N'U')
GROUP BY i.name
ORDER BY i.name;

SELECT i.name AS IndexName
      ,8 * SUM(a.used_pages) AS IndexSizeKB
FROM sys.indexes AS i
    INNER JOIN sys.partitions AS p 
        ON i.[object_id]  = p.[object_id] AND i.index_id = p.index_id
    INNER JOIN sys.allocation_units AS a 
        ON p.partition_id = a.container_id
WHERE i.[object_id] = OBJECT_ID(@TableName, N'U')
GROUP BY i.name
ORDER BY i.name;

Prevent scrolling of parent element when inner element scroll position reaches top/bottom?

M.K. offered a great plugin in his answer. Plugin can be found here. However, for the sake of completion, I thought it'd be a good idea to put it together in one answer for AngularJS.

  1. Start by injecting the bower or npm (whichever is preferred)

    bower install jquery-scrollLock --save
    npm install jquery-scroll-lock --save
    
  2. Add the following directive. I am choosing to add it as an attribute

    (function() {
       'use strict';
    
        angular
           .module('app')
           .directive('isolateScrolling', isolateScrolling);
    
           function isolateScrolling() {
               return {
                   restrict: 'A',
                   link: function(sc, elem, attrs) {
                      $('.scroll-container').scrollLock();
                   }
               }
           }
    })();
    
  3. And the important piece the plugin fails to document in their website is the HTML structure that it must follow.

    <div class="scroll-container locked">
        <div class="scrollable" isolate-scrolling>
             ... whatever ...
        </div>
    </div>
    

The attribute isolate-scrolling must contain the scrollable class and it all needs to be inside the scroll-container class or whatever class you choose and the locked class must be cascaded.

Rotating videos with FFmpeg

Since ffmpeg transpose command is very slow, use the command below to rotate a video by 90 degrees clockwise.

Fast command (Without encoding)-

ffmpeg -i input.mp4 -c copy -metadata:s:v:0 rotate=270 output.mp4

For full video encoding (Slow command, does encoding)

ffmpeg -i inputFile -vf "transpose=1" -c:a copy outputFile

'was not declared in this scope' error

#include <iostream>
using namespace std;
class matrix
{
    int a[10][10],b[10][10],c[10][10],x,y,i,j;
    public :
        void degerler();
        void ters();
};
void matrix::degerler()
{
    cout << "Satirlari giriniz: "; cin >> x;
    cout << "Sütunlari giriniz: "; cin >> y;
    cout << "Ilk matris elamanlarini giriniz:\n\n";
    for (i=1; i<=x; i++)
    {
        for (j=1; j<=y; j++)
        {
            cin >> a[i][j];
        }
    }
    cout << "Ikinci matris elamanlarini giriniz:\n\n";
    for (i=1; i<=x; i++)
    {
        for (j=1; j<=y; j++)
        {
            cin >> b[i][j];
        }
    }
}

void matrix::ters()
{
    cout << "matrisin tersi\n";
    for (i=1; i<=x; i++)
    {
        for (j=1; j<=y; j++)
        {
    if(i==j)
    {
    b[i][j]=1;
    }
    else
    b[i][j]=0;
    }
}
float d,k;
    for (i=1; i<=x; i++)
    {
    d=a[i][j];
        for (j=1; j<=y; j++)
        {
    a[i][j]=a[i][j]/d;
            b[i][j]=b[i][j]/d;
    }
        for (int h=0; h<x; h++)
        {
            if(h!=i)
    {
       k=a[h][j];
               for (j=1; j<=y; j++)
               {
                    a[h][j]=a[h][j]-(a[i][j]*k);
                    b[h][j]=b[h][j]-(b[i][j]*k);
               }
    }
    count << a[i][j] << "";
    }
    count << endl;
}  
}
int main()
{
    int secim;
    char ch;    
    matrix m;
    m.degerler();
    do
     {
    cout << "seçiminizi giriniz\n";
    cout << " 1. matrisin tersi\n";
    cin >> secim;
    switch (secim)
    {
        case 1:
            m.ters();
            break;
    }
    cout << "\nBaska bir sey yap/n?";
    cin >> ch;
    }
    while (ch!= 'n');
    cout << "\n";
    return 0;
}

How do I create a constant in Python?

Edit: Added sample code for Python 3

Note: this other answer looks like it provides a much more complete implementation similar to the following (with more features).

First, make a metaclass:

class MetaConst(type):
    def __getattr__(cls, key):
        return cls[key]

    def __setattr__(cls, key, value):
        raise TypeError

This prevents statics properties from being changed. Then make another class that uses that metaclass:

class Const(object):
    __metaclass__ = MetaConst

    def __getattr__(self, name):
        return self[name]

    def __setattr__(self, name, value):
        raise TypeError

Or, if you're using Python 3:

class Const(object, metaclass=MetaConst):
    def __getattr__(self, name):
        return self[name]

    def __setattr__(self, name, value):
        raise TypeError

This should prevent instance props from being changed. To use it, inherit:

class MyConst(Const):
    A = 1
    B = 2

Now the props, accessed directly or via an instance, should be constant:

MyConst.A
# 1
my_const = MyConst()
my_const.A
# 1

MyConst.A = 'changed'
# TypeError
my_const.A = 'changed'
# TypeError

Here's an example of above in action. Here's another example for Python 3.

How to change default language for SQL Server?

Please try below:

DECLARE @Today DATETIME;  
SET @Today = '12/5/2007';  

SET LANGUAGE Italian;  
SELECT DATENAME(month, @Today) AS 'Month Name';  

SET LANGUAGE us_english;  
SELECT DATENAME(month, @Today) AS 'Month Name' ;  
GO  

Reference:

https://docs.microsoft.com/en-us/sql/t-sql/statements/set-language-transact-sql

ORA-12154: TNS:could not resolve the connect identifier specified (PLSQL Developer)

The answer was simply moving the PLSQL Developer folder from the "Program Files (x86) into the "Program Files" folder - weird!

How to split a dataframe string column into two columns?

You can use str.split by whitespace (default separator) and parameter expand=True for DataFrame with assign to new columns:

df = pd.DataFrame({'row': ['00000 UNITED STATES', '01000 ALABAMA', 
                           '01001 Autauga County, AL', '01003 Baldwin County, AL', 
                           '01005 Barbour County, AL']})
print (df)
                        row
0       00000 UNITED STATES
1             01000 ALABAMA
2  01001 Autauga County, AL
3  01003 Baldwin County, AL
4  01005 Barbour County, AL



df[['a','b']] = df['row'].str.split(n=1, expand=True)
print (df)
                        row      a                   b
0       00000 UNITED STATES  00000       UNITED STATES
1             01000 ALABAMA  01000             ALABAMA
2  01001 Autauga County, AL  01001  Autauga County, AL
3  01003 Baldwin County, AL  01003  Baldwin County, AL
4  01005 Barbour County, AL  01005  Barbour County, AL

Modification if need remove original column with DataFrame.pop

df[['a','b']] = df.pop('row').str.split(n=1, expand=True)
print (df)
       a                   b
0  00000       UNITED STATES
1  01000             ALABAMA
2  01001  Autauga County, AL
3  01003  Baldwin County, AL
4  01005  Barbour County, AL

What is same like:

df[['a','b']] = df['row'].str.split(n=1, expand=True)
df = df.drop('row', axis=1)
print (df)

       a                   b
0  00000       UNITED STATES
1  01000             ALABAMA
2  01001  Autauga County, AL
3  01003  Baldwin County, AL
4  01005  Barbour County, AL

If get error:

#remove n=1 for split by all whitespaces
df[['a','b']] = df['row'].str.split(expand=True)

ValueError: Columns must be same length as key

You can check and it return 4 column DataFrame, not only 2:

print (df['row'].str.split(expand=True))
       0        1        2     3
0  00000   UNITED   STATES  None
1  01000  ALABAMA     None  None
2  01001  Autauga  County,    AL
3  01003  Baldwin  County,    AL
4  01005  Barbour  County,    AL

Then solution is append new DataFrame by join:

df = pd.DataFrame({'row': ['00000 UNITED STATES', '01000 ALABAMA', 
                           '01001 Autauga County, AL', '01003 Baldwin County, AL', 
                           '01005 Barbour County, AL'],
                    'a':range(5)})
print (df)
   a                       row
0  0       00000 UNITED STATES
1  1             01000 ALABAMA
2  2  01001 Autauga County, AL
3  3  01003 Baldwin County, AL
4  4  01005 Barbour County, AL

df = df.join(df['row'].str.split(expand=True))
print (df)

   a                       row      0        1        2     3
0  0       00000 UNITED STATES  00000   UNITED   STATES  None
1  1             01000 ALABAMA  01000  ALABAMA     None  None
2  2  01001 Autauga County, AL  01001  Autauga  County,    AL
3  3  01003 Baldwin County, AL  01003  Baldwin  County,    AL
4  4  01005 Barbour County, AL  01005  Barbour  County,    AL

With remove original column (if there are also another columns):

df = df.join(df.pop('row').str.split(expand=True))
print (df)
   a      0        1        2     3
0  0  00000   UNITED   STATES  None
1  1  01000  ALABAMA     None  None
2  2  01001  Autauga  County,    AL
3  3  01003  Baldwin  County,    AL
4  4  01005  Barbour  County,    AL   

How to hide html source & disable right click and text copy?

You can't.

ANYTHING that can be read by the browser can also be read by humans. If you want something hidden, don't send it to the user's browser.

You can add all sorts of gimmicks and tricks to disable right-click and disable ctrl+U

All a user has to do is add view-source: to the url and they will see the source right away.

Example

view-source:https://stackoverflow.com

How do I escape double and single quotes in sed?

You can use %

sed -i "s%http://www.fubar.com%URL_FUBAR%g"

FFMPEG mp4 from http live streaming m3u8 file?

Your command is completely incorrect. The output format is not rawvideo and you don't need the bitstream filter h264_mp4toannexb which is used when you want to convert the h264 contained in an mp4 to the Annex B format used by MPEG-TS for example. What you want to use instead is the aac_adtstoasc for the AAC streams.

ffmpeg -i http://.../playlist.m3u8 -c copy -bsf:a aac_adtstoasc output.mp4

How does Trello access the user's clipboard?

Daniel LeCheminant's code didn't work for me after converting it from CoffeeScript to JavaScript (js2coffee). It kept bombing out on the _.defer() line.

I assumed this was something to do with jQuery deferreds, so I changed it to $.Deferred() and it's working now. I tested it in Internet Explorer 11, Firefox 35, and Chrome 39 with jQuery 2.1.1. The usage is the same as described in Daniel's post.

var TrelloClipboard;

TrelloClipboard = new ((function () {
    function _Class() {
        this.value = "";
        $(document).keydown((function (_this) {
            return function (e) {
                var _ref, _ref1;
                if (!_this.value || !(e.ctrlKey || e.metaKey)) {
                    return;
                }
                if ($(e.target).is("input:visible,textarea:visible")) {
                    return;
                }
                if (typeof window.getSelection === "function" ? (_ref = window.getSelection()) != null ? _ref.toString() : void 0 : void 0) {
                    return;
                }
                if ((_ref1 = document.selection) != null ? _ref1.createRange().text : void 0) {
                    return;
                }
                return $.Deferred(function () {
                    var $clipboardContainer;
                    $clipboardContainer = $("#clipboard-container");
                    $clipboardContainer.empty().show();
                    return $("<textarea id='clipboard'></textarea>").val(_this.value).appendTo($clipboardContainer).focus().select();
                });
            };
        })(this));

        $(document).keyup(function (e) {
            if ($(e.target).is("#clipboard")) {
                return $("#clipboard-container").empty().hide();
            }
        });
    }

    _Class.prototype.set = function (value) {
        this.value = value;
    };

    return _Class;

})());

Curl setting Content-Type incorrectly

I think you want to specify

-H "Content-Type:text/xml"

with a colon, not an equals.

AJAX POST and Plus Sign ( + ) -- How to Encode?

To make it more interesting and to hopefully enable less hair pulling for someone else. Using python, built dictionary for a device which we can use curl to configure.

Problem: {"timezone":"+5"} //throws an error " 5"

Solution: {"timezone":"%2B"+"5"} //Works

So, in a nutshell:

var = {"timezone":"%2B"+"5"}
json = JSONEncoder().encode(var)
subprocess.call(["curl",ipaddress,"-XPUT","-d","data="+json])

Thanks to this post!

Including all the jars in a directory within the Java classpath

We get around this problem by deploying a main jar file myapp.jar which contains a manifest (Manifest.mf) file specifying a classpath with the other required jars, which are then deployed alongside it. In this case, you only need to declare java -jar myapp.jar when running the code.

So if you deploy the main jar into some directory, and then put the dependent jars into a lib folder beneath that, the manifest looks like:

Manifest-Version: 1.0
Implementation-Title: myapp
Implementation-Version: 1.0.1
Class-Path: lib/dep1.jar lib/dep2.jar

NB: this is platform-independent - we can use the same jars to launch on a UNIX server or on a Windows PC.

Space between Column's children in Flutter

There are many answers here but I will put here the most important one which everyone should use.

1. Column

 Column(
          children: <Widget>[
            Text('Widget A'), //Can be any widget
            SizedBox(height: 20,), //height is space betweeen your top and bottom widget
            Text('Widget B'), //Can be any widget
          ],
        ),

2. Wrap

     Wrap(
          direction: Axis.vertical, // We have to declare Axis.vertical, otherwise by default widget are drawn in horizontal order
            spacing: 20, // Add spacing one time which is same for all other widgets in the children list
            children: <Widget>[
              Text('Widget A'), // Can be any widget
              Text('Widget B'), // Can be any widget
            ]
        )

Bootstrap tab activation with JQuery

<div class="tabbable">
<ul class="nav nav-tabs">
    <li class="active"><a href="#aaa" data-toggle="tab">AAA</a></li>
    <li><a href="#bbb" data-toggle="tab">BBB</a></li>
    <li><a href="#ccc" data-toggle="tab">CCC</a></li>
</ul>
<div class="tab-content" id="tabs">
    <div class="tab-pane fade active in" id="aaa">...Content...</div>
    <div class="tab-pane" id="bbb">...Content...</div>
    <div class="tab-pane" id="ccc">...Content...</div>
</div>
</div>   

Add active class to any li element you want to be active after page load. And also adding active class to content div is needed ,fade in classes are useful for a smooth transition.

Detect application heap size in Android

Some operations are quicker than java heap space manager. Delaying operations for some time can free memory space. You can use this method to escape heap size error:

waitForGarbageCollector(new Runnable() {
  @Override
  public void run() {
    // Your operations.
  }
});

/**
 * Measure used memory and give garbage collector time to free up some
 * of the space.
 *
 * @param callback Callback operations to be done when memory is free.
 */
public static void waitForGarbageCollector(final Runnable callback) {

  Runtime runtime;
  long maxMemory;
  long usedMemory;
  double availableMemoryPercentage = 1.0;
  final double MIN_AVAILABLE_MEMORY_PERCENTAGE = 0.1;
  final int DELAY_TIME = 5 * 1000;

  runtime =
    Runtime.getRuntime();

  maxMemory =
    runtime.maxMemory();

  usedMemory =
    runtime.totalMemory() -
    runtime.freeMemory();

  availableMemoryPercentage =
    1 -
    (double) usedMemory /
    maxMemory;

  if (availableMemoryPercentage < MIN_AVAILABLE_MEMORY_PERCENTAGE) {
    try {
      Thread.sleep(DELAY_TIME);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    waitForGarbageCollector(
      callback);
  } else {
    // Memory resources are available, go to next operation:
    callback.run();
  }
}

How do I split a string with multiple separators in JavaScript?

Pass in a regexp as the parameter:

js> "Hello awesome, world!".split(/[\s,]+/)
Hello,awesome,world!

Edited to add:

You can get the last element by selecting the length of the array minus 1:

>>> bits = "Hello awesome, world!".split(/[\s,]+/)
["Hello", "awesome", "world!"]
>>> bit = bits[bits.length - 1]
"world!"

... and if the pattern doesn't match:

>>> bits = "Hello awesome, world!".split(/foo/)
["Hello awesome, world!"]
>>> bits[bits.length - 1]
"Hello awesome, world!"

Undo a Git merge that hasn't been pushed yet

If your merge and the corresponding commits were not pushed yet, you can always switch to another branch, delete the original one and re-create it.

For example, I accidentally merged a develop branch into master and wanted to undo that. Using the following steps:

git checkout develop
git branch -D master
git branch -t master origin/master

Voila! Master is at the same stage as origin, and your mis-merged state is erased.

CORS with spring-boot and angularjs not working

For me the only thing that worked 100% when spring security is used was to skip all the additional fluff of extra filters and beans and whatever indirect "magic" people kept suggesting that worked for them but not for me.

Instead just force it to write the headers you need with a plain StaticHeadersWriter:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
            // your security config here
            .authorizeRequests()
            .antMatchers(HttpMethod.TRACE, "/**").denyAll()
            .antMatchers("/admin/**").authenticated()
            .anyRequest().permitAll()
            .and().httpBasic()
            .and().headers().frameOptions().disable()
            .and().csrf().disable()
            .headers()
            // the headers you want here. This solved all my CORS problems! 
            .addHeaderWriter(new StaticHeadersWriter("Access-Control-Allow-Origin", "*"))
            .addHeaderWriter(new StaticHeadersWriter("Access-Control-Allow-Methods", "POST, GET"))
            .addHeaderWriter(new StaticHeadersWriter("Access-Control-Max-Age", "3600"))
            .addHeaderWriter(new StaticHeadersWriter("Access-Control-Allow-Credentials", "true"))
            .addHeaderWriter(new StaticHeadersWriter("Access-Control-Allow-Headers", "Origin,Accept,X-Requested-With,Content-Type,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization"));
    }
}

This is the most direct and explicit way I found to do it. Hope it helps someone.

How to detect incoming calls, in an Android device?

UPDATE: The really awesome code posted by Gabe Sechan no longer works unless you explicitly request the user to grant the necessary permissions. Here is some code that you can place in your main activity to request these permissions:

    if (getApplicationContext().checkSelfPermission(Manifest.permission.READ_PHONE_STATE)
            != PackageManager.PERMISSION_GRANTED) {
        // Permission has not been granted, therefore prompt the user to grant permission
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.READ_PHONE_STATE},
                MY_PERMISSIONS_REQUEST_READ_PHONE_STATE);
    }

    if (getApplicationContext().checkSelfPermission(Manifest.permission.PROCESS_OUTGOING_CALLS)
            != PackageManager.PERMISSION_GRANTED) {
        // Permission has not been granted, therefore prompt the user to grant permission
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.PROCESS_OUTGOING_CALLS},
                MY_PERMISSIONS_REQUEST_PROCESS_OUTGOING_CALLS);
    }

ALSO: As someone mentioned in a comment below Gabe's post, you have to add a little snippet of code, android:enabled="true, to the receiver in order to detect incoming calls when the app is not currently running in the foreground:

    <!--This part is inside the application-->
    <receiver android:name=".CallReceiver" android:enabled="true">
        <intent-filter>
            <action android:name="android.intent.action.PHONE_STATE" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.NEW_OUTGOING_CALL" />
        </intent-filter>
    </receiver>

bodyParser is deprecated express 4

Want zero warnings? Use it like this:

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));

Explanation: The default value of the extended option has been deprecated, meaning you need to explicitly pass true or false value.

How to use Scanner to accept only valid int as input

Try this:

    public static void main(String[] args)
    {
        Pattern p = Pattern.compile("^\\d+$");
        Scanner kb = new Scanner(System.in);
        int num1;
        int num2 = 0;
        String temp;
        Matcher numberMatcher;
        System.out.print("Enter number 1: ");
        try
        {
            num1 = kb.nextInt();
        }

        catch (java.util.InputMismatchException e)
        {
            System.out.println("Invalid Input");
            //
            return;
        }
        while(num2<num1)
        {
            System.out.print("Enter number 2: ");
            temp = kb.next();
            numberMatcher = p.matcher(temp);
            if (numberMatcher.matches())
            {
                num2 = Integer.parseInt(temp);
            }

            else
            {
                System.out.println("Invalid Number");
            }
        }
    }

You could try to parse the string into an int as well, but usually people try to avoid throwing exceptions.

What I have done is that I have defined a regular expression that defines a number, \d means a numeric digit. The + sign means that there has to be one or more numeric digits. The extra \ in front of the \d is because in java, the \ is a special character, so it has to be escaped.

What is __init__.py for?

In addition to labeling a directory as a Python package and defining __all__, __init__.py allows you to define any variable at the package level. Doing so is often convenient if a package defines something that will be imported frequently, in an API-like fashion. This pattern promotes adherence to the Pythonic "flat is better than nested" philosophy.

An example

Here is an example from one of my projects, in which I frequently import a sessionmaker called Session to interact with my database. I wrote a "database" package with a few modules:

database/
    __init__.py
    schema.py
    insertions.py
    queries.py

My __init__.py contains the following code:

import os

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine

engine = create_engine(os.environ['DATABASE_URL'])
Session = sessionmaker(bind=engine)

Since I define Session here, I can start a new session using the syntax below. This code would be the same executed from inside or outside of the "database" package directory.

from database import Session
session = Session()

Of course, this is a small convenience -- the alternative would be to define Session in a new file like "create_session.py" in my database package, and start new sessions using:

from database.create_session import Session
session = Session()

Further reading

There is a pretty interesting reddit thread covering appropriate uses of __init__.py here:

http://www.reddit.com/r/Python/comments/1bbbwk/whats_your_opinion_on_what_to_include_in_init_py/

The majority opinion seems to be that __init__.py files should be very thin to avoid violating the "explicit is better than implicit" philosophy.

How to get scrollbar position with Javascript?

if you care for the whole page. you can use this:

_x000D_
_x000D_
document.body.getBoundingClientRect().top
_x000D_
_x000D_
_x000D_

Copying one structure to another

If the structures are of compatible types, yes, you can, with something like:

memcpy (dest_struct, source_struct, sizeof (*dest_struct));

The only thing you need to be aware of is that this is a shallow copy. In other words, if you have a char * pointing to a specific string, both structures will point to the same string.

And changing the contents of one of those string fields (the data that the char * points to, not the char * itself) will change the other as well.

If you want a easy copy without having to manually do each field but with the added bonus of non-shallow string copies, use strdup:

memcpy (dest_struct, source_struct, sizeof (*dest_struct));
dest_struct->strptr = strdup (source_struct->strptr);

This will copy the entire contents of the structure, then deep-copy the string, effectively giving a separate string to each structure.

And, if your C implementation doesn't have a strdup (it's not part of the ISO standard), get one from here.

Read int values from a text file in C

A simple solution using fscanf:

void read_ints (const char* file_name)
{
  FILE* file = fopen (file_name, "r");
  int i = 0;

  fscanf (file, "%d", &i);    
  while (!feof (file))
    {  
      printf ("%d ", i);
      fscanf (file, "%d", &i);      
    }
  fclose (file);        
}

How to change date format in JavaScript

Try -

var monthNames = [ "January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December" ];

var newDate = new Date(form.startDate.value);
var formattedDate = monthNames[newDate.getMonth()] + ' ' + newDate.getFullYear();

SVN Error: Commit blocked by pre-commit hook (exit code 1) with output: Error: n/a (6)

I have encounter the same issue and found that i have forgot to prefix the commit message with project identifier. Project identifier is must in our case followed by the commit message. So at the server end it doesn't found the prefix and raised the issue.

Comparing two arrays of objects, and exclude the elements who match values into new array in JS

well, this using lodash or vanilla javascript it depends on the situation.

but for just return the array that contains the duplicates it can be achieved by the following, offcourse it was taken from @1983

var result = result1.filter(function (o1) {
    return result2.some(function (o2) {
        return o1.id === o2.id; // return the ones with equal id
   });
});
// if you want to be more clever...
let result = result1.filter(o1 => result2.some(o2 => o1.id === o2.id));

PHP: How can I determine if a variable has a value that is between two distinct constant values?

Try This

if (($val >= 1 && $val <= 10) || ($val >= 20 && $val <= 40))

This will return the value between 1 to 10 & 20 to 40.

Count number of columns in a table row

You could do

alert(document.getElementById('table1').rows[0].cells.length)

fiddle here http://jsfiddle.net/TEZ73/

How to rename a table column in Oracle 10g

alter table table_name rename column oldColumn to newColumn;

Find a private field with Reflection?

One thing that you need to be aware of when reflecting on private members is that if your application is running in medium trust (as, for instance, when you are running on a shared hosting environment), it won't find them -- the BindingFlags.NonPublic option will simply be ignored.

Promise.all().then() resolve?

Your return data approach is correct, that's an example of promise chaining. If you return a promise from your .then() callback, JavaScript will resolve that promise and pass the data to the next then() callback.

Just be careful and make sure you handle errors with .catch(). Promise.all() rejects as soon as one of the promises in the array rejects.

Image steganography that could survive jpeg compression

Quite a few applications seem to implement Steganography on JPEG, so it's feasible:

http://www.jjtc.com/Steganography/toolmatrix.htm

Here's an article regarding a relevant algorithm (PM1) to get you started:

http://link.springer.com/article/10.1007%2Fs00500-008-0327-7#page-1

Find the smallest positive integer that does not occur in a given sequence

I figured an easy way to do this was to use a BitSet.

  • just add all the positive numbers to the BitSet.
  • when finished, return the index of the first clear bit after bit 0.
public static int find(int[] arr) {
    BitSet b = new BitSet();
    for (int i : arr) {
        if (i > 0) {
            b.set(i);
        }
    }
    return b.nextClearBit(1);
}

Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?

Subtyping is invariant for parameterized types. Even tough the class Dog is a subtype of Animal, the parameterized type List<Dog> is not a subtype of List<Animal>. In contrast, covariant subtyping is used by arrays, so the array type Dog[] is a subtype of Animal[].

Invariant subtyping ensures that the type constraints enforced by Java are not violated. Consider the following code given by @Jon Skeet:

List<Dog> dogs = new ArrayList<Dog>(1);
List<Animal> animals = dogs;
animals.add(new Cat()); // compile-time error
Dog dog = dogs.get(0);

As stated by @Jon Skeet, this code is illegal, because otherwise it would violate the type constraints by returning a cat when a dog expected.

It is instructive to compare the above to analogous code for arrays.

Dog[] dogs = new Dog[1];
Object[] animals = dogs;
animals[0] = new Cat(); // run-time error
Dog dog = dogs[0];

The code is legal. However, throws an array store exception. An array carries its type at run-time this way JVM can enforce type safety of covariant subtyping.

To understand this further let's look at the bytecode generated by javap of the class below:

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

public class Demonstration {
    public void normal() {
        List normal = new ArrayList(1);
        normal.add("lorem ipsum");
    }

    public void parameterized() {
        List<String> parameterized = new ArrayList<>(1);
        parameterized.add("lorem ipsum");
    }
}

Using the command javap -c Demonstration, this shows the following Java bytecode:

Compiled from "Demonstration.java"
public class Demonstration {
  public Demonstration();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  public void normal();
    Code:
       0: new           #2                  // class java/util/ArrayList
       3: dup
       4: iconst_1
       5: invokespecial #3                  // Method java/util/ArrayList."<init>":(I)V
       8: astore_1
       9: aload_1
      10: ldc           #4                  // String lorem ipsum
      12: invokeinterface #5,  2            // InterfaceMethod java/util/List.add:(Ljava/lang/Object;)Z
      17: pop
      18: return

  public void parameterized();
    Code:
       0: new           #2                  // class java/util/ArrayList
       3: dup
       4: iconst_1
       5: invokespecial #3                  // Method java/util/ArrayList."<init>":(I)V
       8: astore_1
       9: aload_1
      10: ldc           #4                  // String lorem ipsum
      12: invokeinterface #5,  2            // InterfaceMethod java/util/List.add:(Ljava/lang/Object;)Z
      17: pop
      18: return
}

Observe that the translated code of method bodies are identical. Compiler replaced each parameterized type by its erasure. This property is crucial meaning that it did not break backwards compatibility.

In conclusion, run-time safety is not possible for parameterized types, since compiler replaces each parameterized type by its erasure. This makes parameterized types are nothing more than syntactic sugar.

OSX El Capitan: sudo pip install OSError: [Errno: 1] Operation not permitted

TL;DR $PATH fix

  1. Use pip install --user package_name to install a package that should include CLI executables.
  2. Launch a python shell and import package_name
  3. Find where lib/python/... occurs in the output and replace it all with bin
  4. It's likely to be $HOME/Library/Python/2.7/bin

Details

Because of the new System Integrity Protection in macOS 10.11 El Capitan, you can no longer sudo pip install. We won't debate the merits of that here.

Another answer explains that you should pip install --user which is correct. But they sent you to the back alleys to figure out what to do about your $PATH so that you could get access to installed executables. Luckily, I've already solved a similar need for an unrelated question.

Here is a transcript of how I solved the problem on one of my systems. I'm including it all rather just than the $PATH that worked for me, because your system may be different from mine. This process should work for everybody.

$ pip install --user jp
Collecting jp
  Downloading jp-0.2.4.tar.gz
Installing collected packages: jp
  Running setup.py install for jp ... done
Successfully installed jp-0.2.4

$ python -c 'import jp; print jp'
<module 'jp' from '/Users/bbronosky/Library/Python/2.7/lib/python/site-packages/jp/__init__.pyc'>

$ find /Users/bbronosky/Library/Python -type f -perm -100
/Users/bbronosky/Library/Python/2.7/bin/jp

$ which jp

$ echo -e '\n''export PATH=$HOME/Library/Python/2.7/bin:$PATH' >> ~/.bashrc

$ bash # starting a new bash process for demo, but you should open a new terminal

$ which jp
/Users/bbronosky/Library/Python/2.7/bin/jp

$ jp
usage: jp <expression> <filepath>

Adding n hours to a date in Java?

by using Java 8 classes. we can manipulate date and time very easily as below.

LocalDateTime today = LocalDateTime.now();
LocalDateTime minusHours = today.minusHours(24);
LocalDateTime minusMinutes = minusHours.minusMinutes(30);
LocalDate localDate = LocalDate.from(minusMinutes);

Changing background color of selected item in recyclerview

I was able to change the selected view color like this. I think this is the SIMPLE WAY (because you don't have to create instance of layouts and variables.

MAKE SURE YOU DONT GIVE ANY BACKGROUND COLOR INSIDE YOUR RECYCLER VIEW's TAG.

holder.itemView.setBackgroundColor(Color.parseColor("#8DFFFFFF"));

onBindViewHolder() method is given below

@Override
public void onBindViewHolder(@NonNull final MyViewHolder holder, final int position) {

        holder.item_1.setText(list_items.get(position).item_1);
        holder.item_2.setText(list_items.get(position).item_2);
        holder.select_cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if (isChecked){

                    holder.itemView.setBackgroundColor(Color.parseColor("#8DFFFFFF"));
                }else {

                    holder.itemView.setBackgroundColor(Color.parseColor("#FFFFFF"));
                }
            }
        });
}

OpenCV - DLL missing, but it's not?

Copy all .dll from /bin in System32

SQLAlchemy ORDER BY DESCENDING?

Just as an FYI, you can also specify those things as column attributes. For instance, I might have done:

.order_by(model.Entry.amount.desc())

This is handy since it avoids an import, and you can use it on other places such as in a relation definition, etc.

For more information, you can refer this

Change the Value of h1 Element within a Form with JavaScript

You can also use this

document.querySelector('yourId').innerHTML = 'Content';

Regular expression: zero or more occurrences of optional character /

/*

If your delimiters are slash-based, escape it:

\/*

* means "0 or more of the previous repeatable pattern", which can be a single character, a character class or a group.

ValueError: unconverted data remains: 02:05

Best answer is to use the from dateutil import parser.

usage:

from dateutil import parser
datetime_obj = parser.parse('2018-02-06T13:12:18.1278015Z')
print datetime_obj
# output: datetime.datetime(2018, 2, 6, 13, 12, 18, 127801, tzinfo=tzutc())

Server unable to read htaccess file, denying access to be safe

"Server unable to read htaccess file" means just that. Make sure that the permissions on your .htaccess file are world-readable.

PHP Create and Save a txt file to root directory

fopen() will open a resource in the same directory as the file executing the command. In other words, if you're just running the file ~/test.php, your script will create ~/myText.txt.

This can get a little confusing if you're using any URL rewriting (such as in an MVC framework) as it will likely create the new file in whatever the directory contains the root index.php file.

Also, you must have correct permissions set and may want to test before writing to the file. The following would help you debug:

$fp = fopen("myText.txt","wb");
if( $fp == false ){
    //do debugging or logging here
}else{
    fwrite($fp,$content);
    fclose($fp);
}

jQuery input button click event listener

First thing first, button() is a jQuery ui function to create a button widget which has nothing to do with jQuery core, it just styles the button.
So if you want to use the widget add jQuery ui's javascript and CSS files or alternatively remove it, like this:

$("#filter").click(function(){
    alert('clicked!');
});

Another thing that might have caused you the problem is if you didn't wait for the input to be rendered and wrote the code before the input. jQuery has the ready function, or it's alias $(func) which execute the callback once the DOM is ready.
Usage:

$(function(){
    $("#filter").click(function(){
        alert('clicked!');
    });
});

So even if the order is this it will work:

$(function(){
    $("#filter").click(function(){
        alert('clicked!');
    });
});

<input type="button" id="filter" name="filter" value="Filter" />

DEMO

How to prevent downloading images and video files from my website?

As many have said, you can't stop someone from downloading content. You just can't.

But you can make it harder.

You can overlay images with a transparent div, which will prevent people from right clicking on them (or, setting the background of a div to the image will have the same effect).

If you're worried about cross-linking (ie, other people linking to your images, you can check the HTTP referrer and redirect requests which come from a domain which isn't yours to "something else".

Changing nav-bar color after scrolling?

_x000D_
_x000D_
$(window).on('activate.bs.scrollspy', function (e,obj) {_x000D_
_x000D_
  if ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight) {_x000D_
    return;_x000D_
  }_x000D_
  _x000D_
  var isBGLight = $(obj.relatedTarget).hasClass('nav_white');_x000D_
  var isBGDark = $(obj.relatedTarget).hasClass('nav_blue');_x000D_
  $('.menu').removeClass('nav_white');_x000D_
  $('.menu').removeClass('nav_blue');_x000D_
  if(isBGDark)_x000D_
  {_x000D_
    $('.menu').addClass('nav_white');_x000D_
  }else if(isBGLight)_x000D_
  {_x000D_
    $('.menu').addClass('nav_blue');_x000D_
  }_x000D_
  /*var isScrolled = $(document).scrollTop() > 1;_x000D_
    $('.menu').toggleClass('scrolled', isScrolled);_x000D_
    $(".demos").toggleClass("demo");_x000D_
    $(".demos").toggleClass("demo1");_x000D_
  var posicionActual = $(document).scrollTop();_x000D_
  $.each($('.nav_transparent'),function(){_x000D_
    if ($(this).position().top < posicionActual){_x000D_
      $("nav.menu").removeClass("nav_white");_x000D_
      $("nav.menu").removeClass("nav_blue");_x000D_
      $("nav.menu").addClass("nav_transparent");_x000D_
      $(".demos").removeClass("demo");_x000D_
      $(".demos").addClass("demo1");_x000D_
      $(".cls").removeClass("cls2");_x000D_
      $(".cls").addClass("cls1");_x000D_
      $(".cl").removeClass("cl2");_x000D_
      $(".cl").addClass("cl1");_x000D_
      $(".hamb-bottom").css({"background-color": "#fff"});_x000D_
      $(".hamb-middle").css({"background-color": "#fff"});_x000D_
      $(".hamb-top").css({"background-color": "#fff"});_x000D_
    }_x000D_
  });_x000D_
  $.each($('.nav_blue'),function(){_x000D_
    if ($(this).position().top <= posicionActual){_x000D_
      $("nav.menu").removeClass("nav_transparent");_x000D_
      $("nav.menu").removeClass("nav_white");_x000D_
      $("nav.menu").addClass("nav_blue");_x000D_
      $(".demos").removeClass("demo1");_x000D_
      $(".demos").addClass("demo");_x000D_
      $(".cls").removeClass("cls2");_x000D_
      $(".cls").addClass("cls1");_x000D_
      $(".cl").removeClass("cl2");_x000D_
      $(".cl").addClass("cl1");_x000D_
      $(".hamb-bottom").css({"background-color": "#fff"});_x000D_
      $(".hamb-middle").css({"background-color": "#fff"});_x000D_
      $(".hamb-top").css({"background-color": "#fff"});_x000D_
    }_x000D_
  });_x000D_
  $.each($('.nav_white'),function(){_x000D_
    if ($(this).position().top <= posicionActual){_x000D_
      $("nav.menu").removeClass("nav_blue");_x000D_
      $("nav.menu").removeClass("nav_transparent");_x000D_
      $("nav.menu").addClass("nav_white");_x000D_
      $(".demos").removeClass("demo");_x000D_
      $(".demos").addClass("demo1");_x000D_
      $(".cls").removeClass("cls1");_x000D_
      $(".cls").addClass("cls2");_x000D_
      $(".cl").removeClass("cl1");_x000D_
      $(".cl").addClass("cl2");_x000D_
      $(".hamb-bottom").css({"background-color": "#4285f4"});_x000D_
      $(".hamb-middle").css({"background-color": "#4285f4"});_x000D_
      $(".hamb-top").css({"background-color": "#4285f4"});_x000D_
    }_x000D_
  });*/_x000D_
});_x000D_
$(window).on("scroll", function(){_x000D_
  if($(document).scrollTop() < 10)_x000D_
    {_x000D_
      $('.nav').removeClass('nav_white');_x000D_
      $('.nav').removeClass('nav_blue');_x000D_
      $('.nav').removeClass('nav_transparent');_x000D_
      $('.nav').addClass('nav_transparent');_x000D_
  }_x000D_
});
_x000D_
_x000D_
_x000D_

the solutions, maybe

How to get the xml node value in string

You should use .Load and not .LoadXML

MSDN Link

"The LoadXml method is for loading an XML string directly. You want to use the Load method instead."

ref : Link

Display PDF within web browser

I recently needed to provide a more mobile-friendly, responsive version of a .pdf document, because narrow phone screens required scrolling right and left a lot. To allow just vertical scrolling and avoid horizontal scrolling, the following steps worked for me:

  • Open the .pdf in Chrome browser
  • Click Open with Google Docs
  • Click File > Download > Web Page
  • Click on the downloaded document to unzip it
  • Click on the unzipped HTML document to open it in Chrome browser
  • Press fn F12 to open Chrome Dev Tools
  • Paste copy(document.documentElement.outerHTML.replace(/padding:72pt 72pt 72pt 72pt;/, '').replace(/margin-right:.*?pt/g, '')) into the Console, and press Enter to copy the tweaked document to the clipboard
  • Open a text editor (e.g., Notepad), or in my case VSCode, paste, and save with a .html extension.

The result looked good and was usable in both desktop and mobile environments.

Is it possible to access an SQLite database from JavaScript?

One of the most interesting features in HTML5 is the ability to store data locally and to allow the application to run offline. There are three different APIs that deal with these features and choosing one depends on what exactly you want to do with the data you're planning to store locally:

  1. Web storage: For basic local storage with key/value pairs
  2. Offline storage: Uses a manifest to cache entire files for offline use
  3. Web database: For relational database storage

For more reference see Introducing the HTML5 storage APIs

And how to use

http://cookbooks.adobe.com/post_Store_data_in_the_HTML5_SQLite_database-19115.html

Add a reference column migration in Rails 4

if you like another alternate approach with up and down method try this:

  def up
    change_table :uploads do |t|
      t.references :user, index: true
    end
  end

  def down
    change_table :uploads do |t|
      t.remove_references :user, index: true
    end
  end

Update date + one year in mysql

This post helped me today, but I had to experiment to do what I needed. Here is what I found.

Should you want to add more complex time periods, for example 1 year and 15 days, you can use

UPDATE tablename SET datefieldname = curdate() + INTERVAL 15 DAY + INTERVAL 1 YEAR;

I found that using DATE_ADD doesn't allow for adding more than one interval. And there is no YEAR_DAYS interval keyword, though there are others that combine time periods. If you are adding times, use now() rather than curdate().

Python JSON dump / append to .txt with each variable on new line

To avoid confusion, paraphrasing both question and answer. I am assuming that user who posted this question wanted to save dictionary type object in JSON file format but when the user used json.dump, this method dumped all its content in one line. Instead, he wanted to record each dictionary entry on a new line. To achieve this use:

with g as outfile:
  json.dump(hostDict, outfile,indent=2)

Using indent = 2 helped me to dump each dictionary entry on a new line. Thank you @agf. Rewriting this answer to avoid confusion.

Accuracy Score ValueError: Can't Handle mix of binary and continuous target

The error is because difference in datatypes of y_pred and y_true. y_true might be dataframe and y_pred is arraylist. If you convert both to arrays, then issue will get resolved.

Unknown SSL protocol error in connection

According to bitbucket knowledgebase it may also be caused by the owner of the repository being over the plan limit.

If you look further down the page it seems to also be possible to trig this error by using a too old git version (1.7 is needed at the moment).

Could not reliably determine the server's fully qualified domain name

Another option is to ensure that the full qualified host name (FQDN) is listed in /etc/hosts. This worked for me on Ubuntu v11.10 without having to change the default Apache configuration.

Property 'value' does not exist on type 'Readonly<{}>'

I suggest to use

for string only state values

export default class Home extends React.Component<{}, { [key: string]: string }> { }

for string key and any type of state values

export default class Home extends React.Component<{}, { [key: string]: any}> { }

for any key / any values

export default class Home extends React.Component<{}, { [key: any]: any}> {}

Swift Modal View Controller with transparent background

You can do it like this:

In your main view controller:

func showModal() {
    let modalViewController = ModalViewController()
    modalViewController.modalPresentationStyle = .overCurrentContext
    presentViewController(modalViewController, animated: true, completion: nil)
}

In your modal view controller:

class ModalViewController: UIViewController {
    override func viewDidLoad() {
        view.backgroundColor = UIColor.clearColor()
        view.opaque = false
    }
}

If you are working with a storyboard:

Just add a Storyboard Segue with Kind set to Present Modally to your modal view controller and on this view controller set the following values:

  • Background = Clear Color
  • Drawing = Uncheck the Opaque checkbox
  • Presentation = Over Current Context

As Crashalot pointed out in his comment: Make sure the segue only uses Default for both Presentation and Transition. Using Current Context for Presentation makes the modal turn black instead of remaining transparent.

Changing ViewPager to enable infinite page scrolling

For infinite scrolling with days it's important you have the good fragment in the pager therefore I wrote my answer on this on page (Viewpager in Android to switch between days endlessly)

It's working very well! Above answers did not work for me as I wanted it to work.

How do I use a custom deleter with a std::unique_ptr member?

You just need to create a deleter class:

struct BarDeleter {
  void operator()(Bar* b) { destroy(b); }
};

and provide it as the template argument of unique_ptr. You'll still have to initialize the unique_ptr in your constructors:

class Foo {
  public:
    Foo() : bar(create()), ... { ... }

  private:
    std::unique_ptr<Bar, BarDeleter> bar;
    ...
};

As far as I know, all the popular c++ libraries implement this correctly; since BarDeleter doesn't actually have any state, it does not need to occupy any space in the unique_ptr.

javac option to compile all java files under a given directory recursively

find . -name "*.java" -print | xargs javac 

Kinda brutal, but works like hell. (Use only on small programs, it's absolutely not efficient)

Getting the button into the top right corner inside the div box

Just add position:absolute; top:0; right:0; to the CSS for your button.

 #button {
     line-height: 12px;
     width: 18px;
     font-size: 8pt;
     font-family: tahoma;
     margin-top: 1px;
     margin-right: 2px;
     position:absolute;
     top:0;
     right:0;
 }

jsFiddle example

How could I put a border on my grid control in WPF?

I think your problem is that the margin should be specified in the border tag and not in the grid.

Add class to <html> with Javascript?

With Jquery... You can add class to html elements like this:

$(".divclass").find("p,h1,h2,h3,figure,span,a").addClass('nameclassorid');

nameclassorid no point or # at the beginning

How should I escape strings in JSON?

org.json.simple.JSONObject.escape() escapes quotes,\, /, \r, \n, \b, \f, \t and other control characters. It can be used to escape JavaScript codes.

import org.json.simple.JSONObject;
String test =  JSONObject.escape("your string");

Check if decimal value is null

decimal is a value type in .NET. And value types can't be null. But if you use nullable type for your decimal, then you can check your decimal is null or not. Like myDecimal?

Nullable types are instances of the System.Nullable struct. A nullable type can represent the normal range of values for its underlying value type, plus an additional null value.

if (myDecimal.HasValue)

But I think in your database, if this column contains nullable values, then it shouldn't be type of decimal.

How do I read text from the clipboard?

The most upvoted answer above is weird in a way that it simply clears the Clipboard and then gets the content (which is then empty). One could clear the clipboard to be sure that some clipboard content type like "formated text" does not "cover" your plain text content you want to save in the clipboard.

The following piece of code replaces all newlines in the clipboard by spaces, then removes all double spaces and finally saves the content back to the clipboard:

import win32clipboard

win32clipboard.OpenClipboard()
c = win32clipboard.GetClipboardData()
win32clipboard.EmptyClipboard()
c = c.replace('\n', ' ')
c = c.replace('\r', ' ')
while c.find('  ') != -1:
    c = c.replace('  ', ' ')
win32clipboard.SetClipboardText(c)
win32clipboard.CloseClipboard()

How to enable directory listing in apache web server

Once I changed Options -Index to Options +Index in my conf file, I removed the welcome page and restarted services.

$ sudo rm -f /etc/httpd/conf.d/welcome.conf
$ sudo service httpd restart

I was able to see directory listings after that.

Resize svg when window is resized in d3.js

_x000D_
_x000D_
d3.select("div#chartId")
   .append("div")
   // Container class to make it responsive.
   .classed("svg-container", true) 
   .append("svg")
   // Responsive SVG needs these 2 attributes and no width and height attr.
   .attr("preserveAspectRatio", "xMinYMin meet")
   .attr("viewBox", "0 0 600 400")
   // Class to make it responsive.
   .classed("svg-content-responsive", true)
   // Fill with a rectangle for visualization.
   .append("rect")
   .classed("rect", true)
   .attr("width", 600)
   .attr("height", 400);
_x000D_
.svg-container {
  display: inline-block;
  position: relative;
  width: 100%;
  padding-bottom: 100%; /* aspect ratio */
  vertical-align: top;
  overflow: hidden;
}
.svg-content-responsive {
  display: inline-block;
  position: absolute;
  top: 10px;
  left: 0;
}

svg .rect {
  fill: gold;
  stroke: steelblue;
  stroke-width: 5px;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

<div id="chartId"></div>
_x000D_
_x000D_
_x000D_

Call to getLayoutInflater() in places not in activity

LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );

Use this instead!

How to get rid of the "No bootable medium found!" error in Virtual Box?

FIX 1:

Step1: Go to settings > then select the following configuration(Disable Floppy)

Config

Alternatively, you can press F12 while booting the Guest OS and select CD from there, this is a one time setting, good enough for the installation.

Step 2: Place your Existing Guest OS bootable CD in the Disk Drive and start the Guest OS.

FIX 2:

Go to Settings > And Perform the following:

Config1

FIX 3:

Try Fix 1 & 2 together..

SQL Query to find the last day of the month

SQL Server 2012 introduces the eomonth function:

select eomonth('2013-05-31 00:00:00:000')
-->
2013-05-31

How do I execute a string containing Python code in Python?

You accomplish executing code using exec, as with the following IDLE session:

>>> kw = {}
>>> exec( "ret = 4" ) in kw
>>> kw['ret']

4

Release generating .pdb files, why?

Actually without PDB files and symbolic information they have it would be impossible to create a successful crash report (memory dump files) and Microsoft would not have the complete picture what caused the problem.

And so having PDB improves crash reporting.

How can I remove leading and trailing quotes in SQL Server?

The following script removes quotation marks only from around the column value if table is called [Messages] and the column is called [Description].

-- If the content is in the form of "anything" (LIKE '"%"')
-- Then take the whole text without the first and last characters 
-- (from the 2nd character and the LEN([Description]) - 2th character)

UPDATE [Messages]
SET [Description] = SUBSTRING([Description], 2, LEN([Description]) - 2)
WHERE [Description] LIKE '"%"'

How to filter wireshark to see only dns queries that are sent/received from/by my computer?

use this filter:

(dns.flags.response == 0) and (ip.src == 159.25.78.7)

what this query does is it only gives dns queries originated from your ip

Non greedy (reluctant) regex matching in sed?

Here is something you can do with a two step approach and awk:

A=http://www.suepearson.co.uk/product/174/71/3816/  
echo $A|awk '  
{  
  var=gensub(///,"||",3,$0) ;  
  sub(/\|\|.*/,"",var);  
  print var  
}'  

Output: http://www.suepearson.co.uk

Hope that helps!

PHP: merge two arrays while keeping keys instead of reindexing?

Try array_replace_recursive or array_replace functions

$a = array('userID' => 1, 'username'=> 2);
array (
  userID => 1,
  username => 2
)
$b = array('userID' => 1, 'companyID' => 3);
array (
  'userID' => 1,
  'companyID' => 3
)
$c = array_replace_recursive($a,$b);
array (
  userID => 1,
  username => 2,
  companyID => 3
)

http://php.net/manual/en/function.array-replace-recursive.php

Intersect Two Lists in C#

You need to first transform data1, in your case by calling ToString() on each element.

Use this if you want to return strings.

List<int> data1 = new List<int> {1,2,3,4,5};
List<string> data2 = new List<string>{"6","3"};

var newData = data1.Select(i => i.ToString()).Intersect(data2);

Use this if you want to return integers.

List<int> data1 = new List<int> {1,2,3,4,5};
List<string> data2 = new List<string>{"6","3"};

var newData = data1.Intersect(data2.Select(s => int.Parse(s));

Note that this will throw an exception if not all strings are numbers. So you could do the following first to check:

int temp;
if(data2.All(s => int.TryParse(s, out temp)))
{
    // All data2 strings are int's
}

Print string to text file

If you are using Python3.

then you can use Print Function :

your_data = {"Purchase Amount": 'TotalAmount'}
print(your_data,  file=open('D:\log.txt', 'w'))

For python2

this is the example of Python Print String To Text File

def my_func():
    """
    this function return some value
    :return:
    """
    return 25.256


def write_file(data):
    """
    this function write data to file
    :param data:
    :return:
    """
    file_name = r'D:\log.txt'
    with open(file_name, 'w') as x_file:
        x_file.write('{} TotalAmount'.format(data))


def run():
    data = my_func()
    write_file(data)


run()

Remove specific commit

git revert --strategy resolve if commit is a merge: use git revert --strategy resolve -m 1

Syntax error near unexpected token 'fi'

"Then" is a command in bash, thus it needs a ";" or a newline before it.

#!/bin/bash
echo "start\n"
for f in *.jpg
do
  fname=$(basename "$f")
  echo "fname is $fname\n"
  fname="${filename%.*}"
  echo "fname is $fname\n"
  if [$[fname%2] -eq 1 ]
  then
    echo "removing $fname\n"
    rm $f
  fi
done

Can I scale a div's height proportionally to its width using CSS?

For anyone looking for a scalable solution: I wrote a small helper utility in SASS to generate responsive proportional rectangles for different breakpoints. Take a look at SASS Proportions

Hope it helps anybody!

Warnings Your Apk Is Using Permissions That Require A Privacy Policy: (android.permission.READ_PHONE_STATE)

Currently some people are facing the same issue because of using 12.0.0 version of AdMob lib.

Update it to 12.0.1. This should fix it. You can read more here

Python interpreter error, x takes no arguments (1 given)

I have been puzzled a lot with this problem, since I am relively new in Python. I cannot apply the solution to the code given by the questioned, since it's not self executable. So I bring a very simple code:

from turtle import *

ts = Screen(); tu = Turtle()

def move(x,y):
  print "move()"
  tu.goto(100,100)

ts.listen();
ts.onclick(move)

done()

As you can see, the solution consists in using two (dummy) arguments, even if they are not used either by the function itself or in calling it! It sounds crazy, but I believe there must be a reason for it (hidden from the novice!).

I have tried a lot of other ways ('self' included). It's the only one that works (for me, at least).

Convert Dictionary<string,string> to semicolon separated string in c#

Another option is to use the Aggregate extension rather than Join:

String s = myDict.Select(x => x.Key + "=" + x.Value).Aggregate((s1, s2) => s1 + ";" + s2);

How to set margin of ImageView using code, not xml

If you want to change imageview margin but leave all other margins intact.

  1. Get MarginLayoutParameters of your image view in this case: myImageView

     MarginLayoutParams marginParams = (MarginLayoutParams) myImageView.getLayoutParams();
    
  2. Now just change the margin you want to change but leave the others as they are:

     marginParams.setMargins(marginParams.leftMargin, 
                             marginParams.topMargin, 
                             150, //notice only changing right margin
                             marginParams.bottomMargin); 
    

How to slice a Pandas Data Frame by position?

df.ix[10,:] gives you all the columns from the 10th row. In your case you want everything up to the 10th row which is df.ix[:9,:]. Note that the right end of the slice range is inclusive: http://pandas.sourceforge.net/gotchas.html#endpoints-are-inclusive

Regular expression for not allowing spaces in the input field

Use + plus sign (Match one or more of the previous items),

var regexp = /^\S+$/

How to check if a process is running via a batch script

TrueY's answer seemed the most elegant solution, however, I had to do some messing around because I didn't understand what exactly was going on. Let me clear things up to hopefully save some time for the next person.

TrueY's modified Answer:

::Change the name of notepad.exe to the process .exe that you're trying to track
::Process names are CASE SENSITIVE, so notepad.exe works but Notepad.exe does NOT
::Do not change IMAGENAME
::You can Copy and Paste this into an empty batch file and change the name of
::notepad.exe to the process you'd like to track
::Also, some large programs take a while to no longer show as not running, so
::give this batch a few seconds timer to avoid a false result!!

@echo off
SETLOCAL EnableExtensions

set EXE=notepad.exe

FOR /F %%x IN ('tasklist /NH /FI "IMAGENAME eq %EXE%"') DO IF %%x == %EXE% goto ProcessFound

goto ProcessNotFound

:ProcessFound

echo %EXE% is running
goto END
:ProcessNotFound
echo %EXE% is not running
goto END
:END
echo Finished!

Anyway, I hope that helps. I know sometimes reading batch/command-line can be kind of confusing sometimes if you're kind of a newbie, like me.

How to consume a webApi from asp.net Web API to store result in database?

In this tutorial is explained how to consume a web api with C#, in this example a console application is used, but you can also use another web api to consume of course.

http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client

You should have a look at the HttpClient

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost/yourwebapi");

Make sure your requests ask for the response in JSON using the Accept header like this:

client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));

Now comes the part that differs from the tutorial, make sure you have the same objects as the other WEB API, if not, then you have to map the objects to your own objects. ASP.NET will convert the JSON you receive to the object you want it to be.

HttpResponseMessage response = client.GetAsync("api/yourcustomobjects").Result;
if (response.IsSuccessStatusCode)
{
    var yourcustomobjects = response.Content.ReadAsAsync<IEnumerable<YourCustomObject>>().Result;
    foreach (var x in yourcustomobjects)
    {
        //Call your store method and pass in your own object
        SaveCustomObjectToDB(x);
    }
}
else
{
    //Something has gone wrong, handle it here
}

please note that I use .Result for the case of the example. You should consider using the async await pattern here.

How to empty a list?

You could try:

alist[:] = []

Which means: Splice in the list [] (0 elements) at the location [:] (all indexes from start to finish)

The [:] is the slice operator. See this question for more information.

How to printf uint64_t? Fails with: "spurious trailing ‘%’ in format"

The ISO C99 standard specifies that these macros must only be defined if explicitly requested.

#define __STDC_FORMAT_MACROS
#include <inttypes.h>

... now PRIu64 will work

Execute SQL script from command line

If you want to run the script file then use below in cmd

sqlcmd -U user -P pass  -S servername -d databasename -i "G:\Hiren\Lab_Prodution.sql"

Python Inverse of a Matrix

You should have a look at numpy if you do matrix manipulation. This is a module mainly written in C, which will be much faster than programming in pure python. Here is an example of how to invert a matrix, and do other matrix manipulation.

from numpy import matrix
from numpy import linalg
A = matrix( [[1,2,3],[11,12,13],[21,22,23]]) # Creates a matrix.
x = matrix( [[1],[2],[3]] )                  # Creates a matrix (like a column vector).
y = matrix( [[1,2,3]] )                      # Creates a matrix (like a row vector).
print A.T                                    # Transpose of A.
print A*x                                    # Matrix multiplication of A and x.
print A.I                                    # Inverse of A.
print linalg.solve(A, x)     # Solve the linear equation system.

You can also have a look at the array module, which is a much more efficient implementation of lists when you have to deal with only one data type.

make an html svg object also a clickable link

Would like to take credit for this but I found a solution here:

https://teamtreehouse.com/forum/how-do-you-make-a-svg-clickable

add the following to the css for the anchor:

a.svg {
  position: relative;
  display: inline-block; 
}
a.svg:after {
  content: ""; 
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left:0;
}


<a href="#" class="svg">
  <object data="random.svg" type="image/svg+xml">
    <img src="random.jpg" />
  </object>
</a>

Link works on the svg and on the fallback.

How to do date/time comparison

The following solved my problem of converting string into date

package main

import (
    "fmt"
    "time"
)

func main() {
    value  := "Thu, 05/19/11, 10:47PM"
    // Writing down the way the standard time would look like formatted our way
    layout := "Mon, 01/02/06, 03:04PM"
    t, _ := time.Parse(layout, value)
    fmt.Println(t)
}

// => "Thu May 19 22:47:00 +0000 2011"

Thanks to paul adam smith

How to handle ETIMEDOUT error?

This is caused when your request response is not received in given time(by timeout request module option).

Basically to catch that error first, you need to register a handler on error, so the unhandled error won't be thrown anymore: out.on('error', function (err) { /* handle errors here */ }). Some more explanation here.

In the handler you can check if the error is ETIMEDOUT and apply your own logic: if (err.message.code === 'ETIMEDOUT') { /* apply logic */ }.

If you want to request for the file again, I suggest using node-retry or node-backoff modules. It makes things much simpler.

If you want to wait longer, you can set timeout option of request yourself. You can set it to 0 for no timeout.

How can I check whether a numpy array is empty or not?

http://www.scipy.org/Tentative_NumPy_Tutorial#head-6a1bc005bd80e1b19f812e1e64e0d25d50f99fe2

NumPy's main object is the homogeneous multidimensional array. In Numpy dimensions are called axes. The number of axes is rank. Numpy's array class is called ndarray. It is also known by the alias array. The more important attributes of an ndarray object are:

ndarray.ndim
the number of axes (dimensions) of the array. In the Python world, the number of dimensions is referred to as rank.

ndarray.shape
the dimensions of the array. This is a tuple of integers indicating the size of the array in each dimension. For a matrix with n rows and m columns, shape will be (n,m). The length of the shape tuple is therefore the rank, or number of dimensions, ndim.

ndarray.size
the total number of elements of the array. This is equal to the product of the elements of shape.

submit the form using ajax

Nobody has actually given a pure javascript answer (as requested by OP), so here it is:

function postAsync(url2get, sendstr)    {
    var req;
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        }
    if (req != undefined) {
        // req.overrideMimeType("application/json"); // if request result is JSON
        try {
            req.open("POST", url2get, false); // 3rd param is whether "async"
            }
        catch(err) {
            alert("couldnt complete request. Is JS enabled for that domain?\\n\\n" + err.message);
            return false;
            }
        req.send(sendstr); // param string only used for POST

        if (req.readyState == 4) { // only if req is "loaded"
            if (req.status == 200)  // only if "OK"
                { return req.responseText ; }
            else    { return "XHR error: " + req.status +" "+req.statusText; }
            }
        }
    alert("req for getAsync is undefined");
}

var var_str = "var1=" + var1  + "&var2=" + var2;
var ret = postAsync(url, var_str) ;
    // hint: encodeURIComponent()

if (ret.match(/^XHR error/)) {
    console.log(ret);
    return;
    }

In your case:

var var_str = "video_time=" + document.getElementById('video_time').value 
     + "&video_id=" + document.getElementById('video_id').value;

Swift convert unix time to date and time

It's simple to convert the Unix timestamp into the desired format. Lets suppose _ts is the Unix timestamp in long

let date = NSDate(timeIntervalSince1970: _ts)

let dayTimePeriodFormatter = NSDateFormatter()
dayTimePeriodFormatter.dateFormat = "MMM dd YYYY hh:mm a"

 let dateString = dayTimePeriodFormatter.stringFromDate(date)

  print( " _ts value is \(_ts)")
  print( " _ts value is \(dateString)")

How to generate a Dockerfile from an image?

To understand how a docker image was built, use the docker history --no-trunc command.

You can build a docker file from an image, but it will not contain everything you would want to fully understand how the image was generated. Reasonably what you can extract is the MAINTAINER, ENV, EXPOSE, VOLUME, WORKDIR, ENTRYPOINT, CMD, and ONBUILD parts of the dockerfile.

The following script should work for you:

#!/bin/bash
docker history --no-trunc "$1" | \
sed -n -e 's,.*/bin/sh -c #(nop) \(MAINTAINER .*[^ ]\) *0 B,\1,p' | \
head -1
docker inspect --format='{{range $e := .Config.Env}}
ENV {{$e}}
{{end}}{{range $e,$v := .Config.ExposedPorts}}
EXPOSE {{$e}}
{{end}}{{range $e,$v := .Config.Volumes}}
VOLUME {{$e}}
{{end}}{{with .Config.User}}USER {{.}}{{end}}
{{with .Config.WorkingDir}}WORKDIR {{.}}{{end}}
{{with .Config.Entrypoint}}ENTRYPOINT {{json .}}{{end}}
{{with .Config.Cmd}}CMD {{json .}}{{end}}
{{with .Config.OnBuild}}ONBUILD {{json .}}{{end}}' "$1"

I use this as part of a script to rebuild running containers as images: https://github.com/docbill/docker-scripts/blob/master/docker-rebase

The Dockerfile is mainly useful if you want to be able to repackage an image.

The thing to keep in mind, is a docker image can actually just be the tar backup of a real or virtual machine. I have made several docker images this way. Even the build history shows me importing a huge tar file as the first step in creating the image...

How to launch another aspx web page upon button click?

Use an html button and javascript? in javascript, window.location is used to change the url location of the current window, while window.open will open a new one

<input type="button" onclick="window.open('newPage.aspx', 'newPage');" />

Edit: Ah, just found this: If the ID of your form tag is form1, set this attribute in your asp button

OnClientClick="form1.target ='_blank';"

NGINX - No input file specified. - php Fast/CGI

I had the same Error and my Problem was, that I had my php-file in my encrypted home-directory. And I run my fpm with the www-data user and this user can't read the php-files even if the permissions on the file were right. The solutioin was that I run fpm with the user who owns the home-directory. This can be changed in folowing file:

/etc/php5/fpm/pool.d/www.conf

hope this will help you :)

How to detect window.print() finish

This Actually worked for me in chrome. I was pretty suprised.

jQuery(document).bind("keyup keydown", function(e){
    if(e.ctrlKey && e.keyCode == 80){
         Print(); e.preventDefault();
    }
});

Where Print is a function I wrote that calls window.print(); It also works as a pure blocker if you disable Print();

As noted here by user3017502

window.print() will pause so you can add an onPrintFinish or onPrintBegin like this

function Print(){
    onPrintBegin
    window.print();
    onPrintFinish(); 
}

Java Array Sort descending?

You could use this to sort all kind of Objects

sort(T[] a, Comparator<? super T> c) 

Arrays.sort(a, Collections.reverseOrder());

Arrays.sort() cannot be used directly to sort primitive arrays in descending order. If you try to call the Arrays.sort() method by passing reverse Comparator defined by Collections.reverseOrder() , it will throw the error

no suitable method found for sort(int[],comparator)

That will work fine with 'Array of Objects' such as Integer array but will not work with a primitive array such as int array.

The only way to sort a primitive array in descending order is, first sort the array in ascending order and then reverse the array in place. This is also true for two-dimensional primitive arrays.

What is Android's file system?

Johan is close - it depends on the hardware manufacturer. For example, Samsung Galaxy S phones uses Samsung RFS (proprietary). However, the Nexus S (also made by Samsung) with Android 2.3 uses Ext4 (presumably because Google told them to - the Nexus S is the current Google experience phone). Many community developers have also started moving to Ext4 because of this shift.

reCAPTCHA ERROR: Invalid domain for site key

I ran into this issue also and my solution was to verify I was integrating the appropriate client code for the version I had selected.

In my case, I had selected reCAPTCHA v3 but was taking client integration code for v2.

V3 looks like this:

<script src="https://www.google.com/recaptcha/api.js?render=reCAPTCHA_site_key"></script>
<script>
  grecaptcha.ready(function() {
      grecaptcha.execute('reCAPTCHA_site_key', {action: 'homepage'}).then(function(token) {
         ...
      });
  });
</script>

V2 code looks like this:

<html>
  <head>
    <title>reCAPTCHA demo: Simple page</title>
     <script src="https://www.google.com/recaptcha/api.js" async defer></script>
  </head>
  <body>
    <form action="?" method="POST">
      <div class="g-recaptcha" data-sitekey="your_site_key"></div>
      <br/>
      <input type="submit" value="Submit">
    </form>
  </body>
</html>

As for which version you have, this will be what you decided at the start of your reCAPTCHA account setup. enter image description here

How to change font size in a textbox in html

Here are some ways to edit the text and the size of the box:

rows="insertNumber"
cols="insertNumber"
style="font-size:12pt"

Example:

<textarea rows="5" cols="30" style="font-size: 12pt" id="myText">Enter 
Text Here</textarea>

How can I make my own event in C#?

You can declare an event with the following code:

public event EventHandler MyOwnEvent;

A custom delegate type instead of EventHandler can be used if needed.

You can find detailed information/tutorials on the use of events in .NET in the article Events Tutorial (MSDN).

JavaScript override methods

_x000D_
_x000D_
function A() {_x000D_
    var c = new C();_x000D_
 c.modify = function(){_x000D_
  c.x = 123;_x000D_
  c.y = 333;_x000D_
 }_x000D_
 c.sum();_x000D_
}_x000D_
_x000D_
function B() {_x000D_
    var c = new C();_x000D_
 c.modify = function(){_x000D_
  c.x = 999;_x000D_
  c.y = 333;_x000D_
 }_x000D_
 c.sum();_x000D_
}_x000D_
_x000D_
_x000D_
C = function () {_x000D_
   this.x = 10;_x000D_
   this.y = 20;_x000D_
_x000D_
   this.modify = function() {_x000D_
      this.x = 30;_x000D_
      this.y = 40;_x000D_
   };_x000D_
   _x000D_
   this.sum = function(){_x000D_
 this.modify();_x000D_
 console.log("The sum is: " + (this.x+this.y));_x000D_
   }_x000D_
}_x000D_
_x000D_
A();_x000D_
B();
_x000D_
_x000D_
_x000D_

Why is setState in reactjs Async instead of Sync?

Yes, setState() is asynchronous.

From the link: https://reactjs.org/docs/react-component.html#setstate

  • React does not guarantee that the state changes are applied immediately.
  • setState() does not always immediately update the component.
  • Think of setState() as a request rather than an immediate command to update the component.

Because they think
From the link: https://github.com/facebook/react/issues/11527#issuecomment-360199710

... we agree that setState() re-rendering synchronously would be inefficient in many cases

Asynchronous setState() makes life very difficult for those getting started and even experienced unfortunately:
- unexpected rendering issues: delayed rendering or no rendering (based on program logic)
- passing parameters is a big deal
among other issues.

Below example helped:

// call doMyTask1 - here we set state
// then after state is updated...
//     call to doMyTask2 to proceed further in program

constructor(props) {
    // ..

    // This binding is necessary to make `this` work in the callback
    this.doMyTask1 = this.doMyTask1.bind(this);
    this.doMyTask2 = this.doMyTask2.bind(this);
}

function doMyTask1(myparam1) {
    // ..

    this.setState(
        {
            mystate1: 'myvalue1',
            mystate2: 'myvalue2'
            // ...
        },    
        () => {
            this.doMyTask2(myparam1); 
        }
    );
}

function doMyTask2(myparam2) {
    // ..
}

Hope that helps.

How can I modify a saved Microsoft Access 2007 or 2010 Import Specification?

I used Mike Hansen's solution, it is great. I modified his solution in one point, instead of replacing parts of the string I modified the XML-attribute. Maybe it is too much of an effort when you can modify the string but anyway, here is my solution for that. This could easily be further modified to change the table etc. too, which is very nice imho.

What was helpful for me was a helper sub to write the XML to a file so I could check the structure and content of it:

Sub writeStringToFile(strPath As String, strText As String)
    '#### writes a given string into a given filePath, overwriting a document if it already exists
        Dim objStream
        
        Set objStream = CreateObject("ADODB.Stream")
        objStream.Charset = "utf-8"
        objStream.Open
        objStream.WriteText strText
        objStream.SaveToFile strPath, 2
    End Sub

The XML of an/my ImportExportSpecification for a table with 2 columns looks like this:

<?xml version="1.0"?>
<ImportExportSpecification Path="mypath\mydocument.xlsx" xmlns="urn:www.microsoft.com/office/access/imexspec">
    <ImportExcel FirstRowHasNames="true" AppendToTable="myTableName" Range="myExcelWorksheetName">
        <Columns PrimaryKey="{Auto}">
            <Column Name="Col1" FieldName="SomeFieldName" Indexed="NO" SkipColumn="false" DataType="Double"/>
            <Column Name="Col2" FieldName="SomeFieldName" Indexed="NO" SkipColumn="false" DataType="Text"/>
        </Columns>
    </ImportExcel>
</ImportExportSpecification>

Then I wrote a function to modify the path. I left out error-handling here:

Function modifyDataSourcePath(strNewPath As String, strXMLSpec As String) As String
'#### Changes the path-name of an import-export specification
    Dim xDoc As MSXML2.DOMDocument60
    Dim childNodes As IXMLDOMNodeList
    Dim nodeImExSpec As MSXML2.IXMLDOMNode
    Dim childNode As MSXML2.IXMLDOMNode
    Dim attributesImExSpec As IXMLDOMNamedNodeMap
    Dim attributeImExSpec As IXMLDOMAttribute

    
    Set xDoc = New MSXML2.DOMDocument60
    xDoc.async = False: xDoc.validateOnParse = False
    xDoc.LoadXML (strXMLSpec)
    Set childNodes = xDoc.childNodes
 
    For Each childNode In childNodes
           If childNode.nodeName = "ImportExportSpecification" Then
                Set nodeImExSpec = childNode
                Exit For
            End If
    Next childNode
    
    Set attributesImExSpec = nodeImExSpec.Attributes
    
    For Each attributeImExSpec In attributesImExSpec
        If attributeImExSpec.nodeName = "Path" Then
            attributeImExSpec.Value = strNewPath
            Exit For
        End If
    Next attributeImExSpec
    
    modifyDataSourcePath = xDoc.XML
End Function

I use this in Mike's code before the newSpec is executed and instead of the replace statement. Also I write the XML-string into an XML-file in a location relative to the database but that line is optional:

Set myNewSpec = CurrentProject.ImportExportSpecifications.item("TemporaryImport")
    myNewSpec.XML = modifyDataSourcePath(myPath, myNewSpec.XML)
    Call writeStringToFile(Application.CurrentProject.Path & "\impExpSpec.xml", myNewSpec.XML)
    myNewSpec.Execute

How to set a CheckBox by default Checked in ASP.Net MVC

@Html.CheckBox("yourId", true, new { value = Model.Ischecked })

This will certainly work

Google map V3 Set Center to specific Marker

To build upon @6twenty's answer...I prefer panTo(LatLng) over setCenter(LatLng) as panTo animates for smoother transition to center "if the change is less than both the width and height of the map". https://developers.google.com/maps/documentation/javascript/reference#Map

The below uses Google Maps API v3.

var marker = new google.maps.Marker({
    position: new google.maps.LatLng(latitude, longitude),
    title: markerTitle,
    map: map,
});
google.maps.event.addListener(marker, 'click', function () {
    map.panTo(marker.getPosition());
    //map.setCenter(marker.getPosition()); // sets center without animation
});

Merge trunk to branch in Subversion

It is “old-fashioned” way to specify ranges of revisions you wish to merge. With 1.5+ you can use:

svn merge HEAD url/of/trunk path/to/branch/wc

open link of google play store in mobile version android

You can use Android Intents library for opening your application page at Google Play like that:

Intent intent = IntentUtils.openPlayStore(getApplicationContext());
startActivity(intent);

Ruby on Rails form_for select field with class

Try this way:

<%= f.select(:object_field, ['Item 1', ...], {}, { :class => 'my_style_class' }) %>

select helper takes two options hashes, one for select, and the second for html options. So all you need is to give default empty options as first param after list of items and then add your class to html_options.

http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-select

What difference does .AsNoTracking() make?

see this page Entity Framework and AsNoTracking

What AsNoTracking Does

Entity Framework exposes a number of performance tuning options to help you optimise the performance of your applications. One of these tuning options is .AsNoTracking(). This optimisation allows you to tell Entity Framework not to track the results of a query. This means that Entity Framework performs no additional processing or storage of the entities which are returned by the query. However, it also means that you can't update these entities without reattaching them to the tracking graph.

there are significant performance gains to be had by using AsNoTracking

JSchException: Algorithm negotiation fail

add KexAlgorithms diffie-hellman-group1-sha1,diffie-hellman-group-exchange-sha??1 to your sshd_config on the server.

This worked, but make sure you restart sshd: sudo service sshd restart

What does `set -x` do?

-u: disabled by default. When activated, an error message is displayed when using an unconfigured variable.

-v: inactive by default. After activation, the original content of the information will be displayed (without variable resolution) before the information is output.

-x: inactive by default. If activated, the command content will be displayed before the command is run (after variable resolution, there is a ++ symbol).

Compare the following differences:

/ # set -v && echo $HOME
/root
/ # set +v && echo $HOME
set +v && echo $HOME
/root

/ # set -x && echo $HOME
+ echo /root
/root
/ # set +x && echo $HOME
+ set +x
/root

/ # set -u && echo $NOSET
/bin/sh: NOSET: parameter not set
/ # set +u && echo $NOSET

Undefined function mysql_connect()

Well, this is your chance! It looks like PDO is ready; use that instead.

Try checking to see if the PHP MySQL extension module is being loaded:

<?php
    phpinfo();
?>

If it's not there, add the following to the php.ini file:

extension=php_mysql.dll

Header and footer in CodeIgniter

Using This Helper For Dynamic Template Loading

//  get  Template 
    function get_template($template_name, $vars = array(), $return = FALSE) {
        $CI = & get_instance();

        $content = "";
        $last = $CI - > uri - > total_segments();

        if ($CI - > uri - > segment($last) != 'tab') {
            $content = $CI - > load - > view('Header', $vars, $return);
            $content. = $CI - > load - > view('Sidebar', $vars, $return);
        }

        $content. = $CI - > load - > view($template_name, $vars, $return);

        if ($CI - > uri - > segment($last) != 'tab') {
            $content. = $CI - > load - > view('Footer', $vars, $return);
        }

        if ($return) {
            return $content;
        }
    }

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

in map.jsx or map.js file, if you exporting as default like:

export default MapComponent;

then you can import it like

import MapComponent from './map'

but if you do not export it as default like this one here

export const MapComponent = () => { ...whatever }

you need to import in inside curly braces like

import { MapComponent } from './map'

Here we get into your problem: --- sometimes in our project (most of the time that I work with react) we need to import our styles in our javascript files to use it. in such cases we can use that syntax because in such cases, we have a blunder like webpack that that takes care of it, then later on, when we want to bundle our app, webpack is going to extract our CSS files and put it in a separate (for example) app.css file. in those situations, we can use such syntax to import our CSS files into our javascript modules.

like below:

import './css/app.css'

if you are using sass all you need to do is just use sass loader with webpack!

Is it possible to display inline images from html in an Android TextView?

KOTLIN

There is also the possibility to use sufficientlysecure.htmltextview.HtmlTextView

Use like below in gradle files:

Project gradle file:

repositories {
    jcenter()
}

App gradle file:

dependencies {
implementation 'org.sufficientlysecure:html-textview:3.9'
}

Inside xml file replace your textView with:

<org.sufficientlysecure.htmltextview.HtmlTextView
      android:id="@+id/allNewsBlockTextView"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_margin="2dp"
      android:textColor="#000"
      android:textSize="18sp"
      app:htmlToString="@{detailsViewModel.selectedText}" />

Last line above is if you use Binding adapters where the code will be like:

@BindingAdapter("htmlToString")
fun bindTextViewHtml(textView: HtmlTextView, htmlValue: String) {

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    textView.setHtml(
        htmlValue,
        HtmlHttpImageGetter(textView, "n", true)
    );
    } else {
        textView.setHtml(
        htmlValue,
        HtmlHttpImageGetter(textView, "n", true)
        );
    }
}

More info from github page and a big thank you to the authors!!!!!

Double free or corruption after queue::push

The problem is that your class contains a managed RAW pointer but does not implement the rule of three (five in C++11). As a result you are getting (expectedly) a double delete because of copying.

If you are learning you should learn how to implement the rule of three (five). But that is not the correct solution to this problem. You should be using standard container objects rather than try to manage your own internal container. The exact container will depend on what you are trying to do but std::vector is a good default (and you can change afterwords if it is not opimal).

#include <queue>
#include <vector>

class Test{
    std::vector<int> myArray;

    public:
    Test(): myArray(10){
    }    
};

int main(){
    queue<Test> q
    Test t;
    q.push(t);
}

The reason you should use a standard container is the separation of concerns. Your class should be concerned with either business logic or resource management (not both). Assuming Test is some class you are using to maintain some state about your program then it is business logic and it should not be doing resource management. If on the other hand Test is supposed to manage an array then you probably need to learn more about what is available inside the standard library.

How to suppress Update Links warning?

I've found a temporary solution that will at least let me process this job. I wrote a short AutoIt script that waits for the "Update Links" window to appear, then clicks the "Don't Update" button. Code is as follows:

while 1
if winexists("Microsoft Excel","This workbook contains links to other data sources.") Then
   controlclick("Microsoft Excel","This workbook contains links to other data sources.",2)
EndIf
WEnd

So far this seems to be working. I'd really like to find a solution that's entirely VBA, however, so that I can make this a standalone application.

How do I disable TextBox using JavaScript?

Here was my solution:

Markup:

<div id="name" disabled="disabled">

Javascript:

document.getElementById("name").disabled = true;

This the best solution for my applications - hope this helps!

Change window location Jquery

you can use the new push/pop state functions in the history manipulation API.

What does file:///android_asset/www/index.html mean?

The URI "file:///android_asset/" points to YourProject/app/src/main/assets/.

Note: android_asset/ uses the singular (asset) and src/main/assets uses the plural (assets).

Suppose you have a file YourProject/app/src/main/assets/web_thing.html that you would like to display in a WebView. You can refer to it like this:

WebView webViewer = (WebView) findViewById(R.id.webViewer);
webView.loadUrl("file:///android_asset/web_thing.html");

The snippet above could be located in your Activity class, possibly in the onCreate method.

Here is a guide to the overall directory structure of an android project, that helped me figure out this answer.

JavaScript for handling Tab Key press

You should be able to do this with the keyup event. To be specific, event.target should point at the selected element and event.target.href will give you the href-value of that element. See mdn for more information.

The following code is jQuery, but apart from the boilerplate code, the rest is the same in pure javascript. This is a keyup handler that is bound to every link tag.

$('a').on( 'keyup', function( e ) {
    if( e.which == 9 ) {
        console.log( e.target.href );
    }
} );

jsFiddle: http://jsfiddle.net/4PqUF/

Timestamp to human readable format

getDay() returns the day of the week. To get the date, use date.getDate(). getMonth() retrieves the month, but month is zero based, so using getMonth()+1 should give you the right month. Time value seems to be ok here, albeit the hour is 23 here (GMT+1). If you want universal values, add UTC to the methods (e.g. date.getUTCFullYear(), date.getUTCHours())

var timestamp = 1301090400,
date = new Date(timestamp * 1000),
datevalues = [
   date.getFullYear(),
   date.getMonth()+1,
   date.getDate(),
   date.getHours(),
   date.getMinutes(),
   date.getSeconds(),
];
alert(datevalues); //=> [2011, 3, 25, 23, 0, 0]

Inline style to act as :hover in CSS

If that <p> tag is created from JavaScript, then you do have another option: use JSS to programmatically insert stylesheets into the document head. It does support '&:hover'. https://cssinjs.org/

What's the difference between ISO 8601 and RFC 3339 Date Formats?

RFC 3339 is mostly a profile of ISO 8601, but is actually inconsistent with it in borrowing the "-00:00" timezone specification from RFC 2822. This is described in the Wikipedia article.

Is it possible to delete an object's property in PHP?

This also works if you are looping over an object.

unset($object->$key);

No need to use brackets.