Programs & Examples On #Solution

A solution (.sln file) is a structure for organizing projects in Visual Studio. It groups one or more projects that work together to create an application.

R : how to simply repeat a command?

You could use replicate or sapply:

R> colMeans(replicate(10000, sample(100, size=815, replace=TRUE, prob=NULL))) R> sapply(seq_len(10000), function(...) mean(sample(100, size=815, replace=TRUE, prob=NULL))) 

replicate is a wrapper for the common use of sapply for repeated evaluation of an expression (which will usually involve random number generation).

programming a servo thru a barometer

You could define a mapping of air pressure to servo angle, for example:

def calc_angle(pressure, min_p=1000, max_p=1200):     return 360 * ((pressure - min_p) / float(max_p - min_p))  angle = calc_angle(pressure) 

This will linearly convert pressure values between min_p and max_p to angles between 0 and 360 (you could include min_a and max_a to constrain the angle, too).

To pick a data structure, I wouldn't use a list but you could look up values in a dictionary:

d = {1000:0, 1001: 1.8, ...}  angle = d[pressure] 

but this would be rather time-consuming to type out!

Microsoft Advertising SDK doesn't deliverer ads

I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.

Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled

Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is

  1. Remove the XAML for the ad
  2. Remove the xmlns declaration (usually at the top of the page, but sometimes will be declared in the ad itself)
  3. Remove the bad DLL (the one ending in .SDK )
  4. Do a Clean and then Build (clean out anything remaining from the DLL)
  5. Add the xmlns reference (actual reference is below)
  6. Add the ad to the page (example below)

Here is the xmlns reference:

xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI" 

Then the ad itself:

<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480"                    AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/> 

How to implement a simple scenario the OO way

The approach I would take is: when reading the chapters from the database, instead of a collection of chapters, use a collection of books. This will have your chapters organised into books and you'll be able to use information from both classes to present the information to the user (you can even present it in a hierarchical way easily when using this approach).

Better solution without exluding fields from Binding

You should not use your domain models in your views. ViewModels are the correct way to do it.

You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.

If you never heard of viewmodels, take a look at this.

Why my regexp for hyphenated words doesn't work?

This regex should do it.

\b[a-z]+-[a-z]+\b 

\b indicates a word-boundary.

OS X Sprite Kit Game Optimal Default Window Size

You should target the smallest, not the largest, supported pixel resolution by the devices your app can run on.

Say if there's an actual Mac computer that can run OS X 10.9 and has a native screen resolution of only 1280x720 then that's the resolution you should focus on. Any higher and your game won't correctly run on this device and you could as well remove that device from your supported devices list.

You can rely on upscaling to match larger screen sizes, but you can't rely on downscaling to preserve possibly important image details such as text or smaller game objects.

The next most important step is to pick a fitting aspect ratio, be it 4:3 or 16:9 or 16:10, that ideally is the native aspect ratio on most of the supported devices. Make sure your game only scales to fit on devices with a different aspect ratio.

You could scale to fill but then you must ensure that on all devices the cropped areas will not negatively impact gameplay or the use of the app in general (ie text or buttons outside the visible screen area). This will be harder to test as you'd actually have to have one of those devices or create a custom build that crops the view accordingly.

Alternatively you can design multiple versions of your game for specific and very common screen resolutions to provide the best game experience from 13" through 27" displays. Optimized designs for iMac (desktop) and a Macbook (notebook) devices make the most sense, it'll be harder to justify making optimized versions for 13" and 15" plus 21" and 27" screens.

But of course this depends a lot on the game. For example a tile-based world game could simply provide a larger viewing area onto the world on larger screen resolutions rather than scaling the view up. Provided that this does not alter gameplay, like giving the player an unfair advantage (specifically in multiplayer).

You should provide @2x images for the Retina Macbook Pro and future Retina Macs.

Warp \ bend effect on a UIView?

What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.

I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)

Read input from a JOptionPane.showInputDialog box

Your problem is that, if the user clicks cancel, operationType is null and thus throws a NullPointerException. I would suggest that you move

if (operationType.equalsIgnoreCase("Q")) 

to the beginning of the group of if statements, and then change it to

if(operationType==null||operationType.equalsIgnoreCase("Q")). 

This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.

Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.

SyntaxError: Cannot use import statement outside a module

First we'll install @babel/cli, @babel/core and @babel/preset-env.

$ npm install --save-dev @babel/cli @babel/core @babel/preset-env

Then we'll create a .babelrc file for configuring babel.

$ touch .babelrc

This will host any options we might want to configure babel with.

{
  "presets": ["@babel/preset-env"]
}

With recent changes to babel, you will need to transpile your ES6 before node can run it.

So, we'll add our first script, build, in package.json.

"scripts": {
  "build": "babel index.js -d dist"
}

Then we'll add our start script in package.json.

"scripts": {
  "build": "babel index.js -d dist", // replace index.js with your filename
  "start": "npm run build && node dist/index.js"
}

Now let's start our server.

$ npm start

How to prevent Google Colab from disconnecting?

The above answers with the help of some scripts maybe work well. I have a solution(or a kind of trick) for that annoying disconnection without scripts, especially when your program must read data from your google drive, like training a deep learning network model, where using scripts to do reconnect operation is of no use because once you disconnect with your colab, the program is just dead, you should manually connect to your google drive again to make your model able to read dataset again, but the scripts will not do that thing.
I've already test it many times and it works well.
When you run a program on the colab page with a browser(I use Chrome), just remember that don't do any operation to your browser once your program starts running, like: switch to other webpages, open or close another webpage, and so on, just just leave it alone there and waiting for your program finish running, you can switch to another software, like pycharm to keep writing your codes but not switch to another webpage. I don't know why open or close or switch to other pages will cause the connection problem of the google colab page, but each time I try to bothered my browser, like do some search job, my connection to colab will soon break down.

Understanding esModuleInterop in tsconfig file

esModuleInterop generates the helpers outlined in the docs. Looking at the generated code, we can see exactly what these do:

//ts 
import React from 'react'
//js 
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = __importDefault(require("react"));

__importDefault: If the module is not an es module then what is returned by require becomes the default. This means that if you use default import on a commonjs module, the whole module is actually the default.

__importStar is best described in this PR:

TypeScript treats a namespace import (i.e. import * as foo from "foo") as equivalent to const foo = require("foo"). Things are simple here, but they don't work out if the primary object being imported is a primitive or a value with call/construct signatures. ECMAScript basically says a namespace record is a plain object.

Babel first requires in the module, and checks for a property named __esModule. If __esModule is set to true, then the behavior is the same as that of TypeScript, but otherwise, it synthesizes a namespace record where:

  1. All properties are plucked off of the require'd module and made available as named imports.
  2. The originally require'd module is made available as a default import.

So we get this:

// ts
import * as React from 'react'

// emitted js
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var React = __importStar(require("react"));

allowSyntheticDefaultImports is the companion to all of this, setting this to false will not change the emitted helpers (both of them will still look the same). But it will raise a typescript error if you are using default import for a commonjs module. So this import React from 'react' will raise the error Module '".../node_modules/@types/react/index"' has no default export. if allowSyntheticDefaultImports is false.

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

If you aren't using fetchBusinesses method anywhere apart from the effect, you could simply move it into the effect and avoid the warning

useEffect(() => {
    const fetchBusinesses = () => {
       return fetch("theURL", {method: "GET"}
    )
      .then(res => normalizeResponseErrors(res))
      .then(res => {
        return res.json();
      })
      .then(rcvdBusinesses => {
        // some stuff
      })
      .catch(err => {
        // some error handling
      });
  };
  fetchBusinesses();
}, []);

If however you are using fetchBusinesses outside of render, you must note two things

  1. Is there any issue with you not passing fetchBusinesses as a method when it's used during mount with its enclosing closure?
  2. Does your method depend on some variables which it receives from its enclosing closure? This is not the case for you.
  3. On every render, fetchBusinesses will be re-created and hence passing it to useEffect will cause issues. So first you must memoize fetchBusinesses if you were to pass it to the dependency array.

To sum it up I would say that if you are using fetchBusinesses outside of useEffect you can disable the rule using // eslint-disable-next-line react-hooks/exhaustive-deps otherwise you can move the method inside of useEffect

To disable the rule you would write it like

useEffect(() => {
   // other code
   ...

   // eslint-disable-next-line react-hooks/exhaustive-deps
}, []) 

How to Install pip for python 3.7 on Ubuntu 18?

The following steps can be used:


sudo apt-get -y update
---------
sudo apt-get install python3.7
--------------
 python3.7
-------------
 curl -O https://bootstrap.pypa.io/get-pip.py
-----------------
sudo apt install python3-pip
-----------------
sudo apt install python3.7-venv
-----------------
 python3.7 -m venv /home/ubuntu/app
-------------
 cd app   
----------------
 source bin/activate

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

I upgraded my IntelliJ Version from 2018.1 to 2018.3.6. It works !

ping: google.com: Temporary failure in name resolution

If you get the IP address from a DHCP server, you can also set the server to send a DNS server. Or add the nameserver 8.8.8.8 into /etc/resolvconf/resolv.conf.d/base file. The information in this file is included in the resolver configuration file even when no interfaces are configured.

How to compare oldValues and newValues on React Hooks useEffect?

Incase anybody is looking for a TypeScript version of usePrevious:

In a .tsx module:

import { useEffect, useRef } from "react";

const usePrevious = <T extends unknown>(value: T): T | undefined => {
  const ref = useRef<T>();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
};

Or in a .ts module:

import { useEffect, useRef } from "react";

const usePrevious = <T>(value: T): T | undefined => {
  const ref = useRef<T>();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
};

Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed

Make sure that both the chromedriver and google-chrome executable have execute permissions

sudo chmod -x "/usr/bin/chromedriver"

sudo chmod -x "/usr/bin/google-chrome"

pod has unbound PersistentVolumeClaims

You have to define a PersistentVolume providing disc space to be consumed by the PersistentVolumeClaim.

When using storageClass Kubernetes is going to enable "Dynamic Volume Provisioning" which is not working with the local file system.


To solve your issue:

  • Provide a PersistentVolume fulfilling the constraints of the claim (a size >= 100Mi)
  • Remove the storageClass-line from the PersistentVolumeClaim
  • Remove the StorageClass from your cluster

How do these pieces play together?

At creation of the deployment state-description it is usually known which kind (amount, speed, ...) of storage that application will need.
To make a deployment versatile you'd like to avoid a hard dependency on storage. Kubernetes' volume-abstraction allows you to provide and consume storage in a standardized way.

The PersistentVolumeClaim is used to provide a storage-constraint alongside the deployment of an application.

The PersistentVolume offers cluster-wide volume-instances ready to be consumed ("bound"). One PersistentVolume will be bound to one claim. But since multiple instances of that claim may be run on multiple nodes, that volume may be accessed by multiple nodes.

A PersistentVolume without StorageClass is considered to be static.

"Dynamic Volume Provisioning" alongside with a StorageClass allows the cluster to provision PersistentVolumes on demand. In order to make that work, the given storage provider must support provisioning - this allows the cluster to request the provisioning of a "new" PersistentVolume when an unsatisfied PersistentVolumeClaim pops up.


Example PersistentVolume

In order to find how to specify things you're best advised to take a look at the API for your Kubernetes version, so the following example is build from the API-Reference of K8S 1.17:

apiVersion: v1
kind: PersistentVolume
metadata:
  name: ckan-pv-home
  labels:
    type: local
spec:
  capacity:
    storage: 100Mi
  hostPath:
    path: "/mnt/data/ckan"

The PersistentVolumeSpec allows us to define multiple attributes. I chose a hostPath volume which maps a local directory as content for the volume. The capacity allows the resource scheduler to recognize this volume as applicable in terms of resource needs.


Additional Resources:

IntelliJ can't recognize JavaFX 11 with OpenJDK 11

Quick summary, you can do either:

  1. Include the JavaFX modules via --module-path and --add-modules like in José's answer.

    OR

  2. Once you have JavaFX libraries added to your project (either manually or via maven/gradle import), add the module-info.java file similar to the one specified in this answer. (Note that this solution makes your app modular, so if you use other libraries, you will also need to add statements to require their modules inside the module-info.java file).


This answer is a supplement to Jose's answer.

The situation is this:

  1. You are using a recent Java version, e.g. 13.
  2. You have a JavaFX application as a Maven project.
  3. In your Maven project you have the JavaFX plugin configured and JavaFX dependencies setup as per Jose's answer.
  4. You go to the source code of your main class which extends Application, you right-click on it and try to run it.
  5. You get an IllegalAccessError involving an "unnamed module" when trying to launch the app.

Excerpt for a stack trace generating an IllegalAccessError when trying to run a JavaFX app from Intellij Idea:

Exception in Application start method
java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
    at java.base/java.lang.Thread.run(Thread.java:830)
Caused by: java.lang.IllegalAccessError: class com.sun.javafx.fxml.FXMLLoaderHelper (in unnamed module @0x45069d0e) cannot access class com.sun.javafx.util.Utils (in module javafx.graphics) because module javafx.graphics does not export com.sun.javafx.util to unnamed module @0x45069d0e
    at com.sun.javafx.fxml.FXMLLoaderHelper.<clinit>(FXMLLoaderHelper.java:38)
    at javafx.fxml.FXMLLoader.<clinit>(FXMLLoader.java:2056)
    at org.jewelsea.demo.javafx.springboot.Main.start(Main.java:13)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
    at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
Exception running application org.jewelsea.demo.javafx.springboot.Main

OK, now you are kind of stuck and have no clue what is going on.

What has actually happened is this:

  1. Maven has successfully downloaded the JavaFX dependencies for your application, so you don't need to separately download the dependencies or install a JavaFX SDK or module distribution or anything like that.
  2. Idea has successfully imported the modules as dependencies to your project, so everything compiles OK and all of the code completion and everything works fine.

So it seems everything should be OK. BUT, when you run your application, the code in the JavaFX modules is failing when trying to use reflection to instantiate instances of your application class (when you invoke launch) and your FXML controller classes (when you load FXML). Without some help, this use of reflection can fail in some cases, generating the obscure IllegalAccessError. This is due to a Java module system security feature which does not allow code from other modules to use reflection on your classes unless you explicitly allow it (and the JavaFX application launcher and FXMLLoader both require reflection in their current implementation in order for them to function correctly).

This is where some of the other answers to this question, which reference module-info.java, come into the picture.

So let's take a crash course in Java modules:

The key part is this:

4.9. Opens

If we need to allow reflection of private types, but we don't want all of our code exposed, we can use the opens directive to expose specific packages.

But remember, this will open the package up to the entire world, so make sure that is what you want:

module my.module { opens com.my.package; }

So, perhaps you don't want to open your package to the entire world, then you can do:

4.10. Opens … To

Okay, so reflection is great sometimes, but we still want as much security as we can get from encapsulation. We can selectively open our packages to a pre-approved list of modules, in this case, using the opens…to directive:

module my.module { opens com.my.package to moduleOne, moduleTwo, etc.; }

So, you end up creating a src/main/java/module-info.java class which looks like this:

module org.jewelsea.demo.javafx.springboot {
    requires javafx.fxml;
    requires javafx.controls;
    requires javafx.graphics;
    opens org.jewelsea.demo.javafx.springboot to javafx.graphics,javafx.fxml;
}

Where, org.jewelsea.demo.javafx.springboot is the name of the package which contains the JavaFX Application class and JavaFX Controller classes (replace this with the appropriate package name for your application). This tells the Java runtime that it is OK for classes in the javafx.graphics and javafx.fxml to invoke reflection on the classes in your org.jewelsea.demo.javafx.springboot package. Once this is done, and the application is compiled and re-run things will work fine and the IllegalAccessError generated by JavaFX's use of reflection will no longer occur.

But what if you don't want to create a module-info.java file

If instead of using the the Run button in the top toolbar of IDE to run your application class directly, you instead:

  1. Went to the Maven window in the side of the IDE.
  2. Chose the javafx maven plugin target javafx.run.
  3. Right-clicked on that and chose either Run Maven Build or Debug....

Then the app will run without the module-info.java file. I guess this is because the maven plugin is smart enough to dynamically include some kind of settings which allows the app to be reflected on by the JavaFX classes even without a module-info.java file, though I don't know how this is accomplished.

To get that setting transferred to the Run button in the top toolbar, right-click on the javafx.run Maven target and choose the option to Create Run/Debug Configuration for the target. Then you can just choose Run from the top toolbar to execute the Maven target.

Xcode 10: A valid provisioning profile for this executable was not found

I was struggling with the same issue and the solution in my case was to log in to the developer account(s). After updating to Xcode 10 all accounts were logged out.

Use the menu "Xcode -> Preferences ... -> Accounts" and make sure all accounts you use are logged in so the provisioning profiles are accessible.

How to convert string to boolean in typescript Angular 4

In your scenario, converting a string to a boolean can be done via something like someString === 'true' (as was already answered).

However, let me try to address your main issue: dealing with the local storage.

The local storage only supports strings as values; a good way of using it would thus be to always serialise your data as a string before storing it in the storage, and reversing the process when fetching it.

A possibly decent format for serialising your data in is JSON, since it is very easy to deal with in JavaScript.

The following functions could thus be used to interact with local storage, provided that your data can be serialised into JSON.

function setItemInStorage(key, item) {
  localStorage.setItem(key, JSON.stringify(item));
}

function getItemFromStorage(key) {
  return JSON.parse(localStorage.getItem(key));
}

Your example could then be rewritten as:

setItemInStorage('CheckOutPageReload', [this.btnLoginNumOne, this.btnLoginEdit]);

And:

if (getItemFromStorage('CheckOutPageReload')) {
  const pageLoadParams = getItemFromStorage('CheckOutPageReload');
  this.btnLoginNumOne = pageLoadParams[0];
  this.btnLoginEdit = pageLoadParams[1];
}

Find the smallest positive integer that does not occur in a given sequence

100% result solution in Javascript:

function solution(A) {
 let N,i=1;
    A = [...new Set(A)]; // remove duplicated numbers form the Array
    A = A.filter(x => x >= 1).sort((a, b) => a - b); //  remove negative numbers & sort array
    while(!N){ // do not stop untel N get a value
      if(A[i-1] != i){N=i} 
      i++;
    }
    return N;
}

How to resolve TypeError: can only concatenate str (not "int") to str

Python working a bit differently to JavaScript for example, the value you are concatenating needs to be same type, both int or str...

So for example the code below throw an error:

print( "Alireza" + 1980)

like this:

Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    print( "Alireza" + 1980)
TypeError: can only concatenate str (not "int") to str

To solve the issue, just add str to your number or value like:

print( "Alireza" + str(1980))

And the result as:

Alireza1980

How do you change the value inside of a textfield flutter?

Simply change the text property

    TextField(
      controller: txt,
    ),
    RaisedButton(onPressed: () {
        txt.text = "My Stringt";
    }),

while txt is just a TextEditingController

  var txt = TextEditingController();

How can I install a previous version of Python 3 in macOS using homebrew?

What I did was first I installed python 3.7

brew install python3
brew unlink python

then I installed python 3.6.5 using above link

brew install --ignore-dependencies https://raw.githubusercontent.com/Homebrew/homebrew-core/f2a764ef944b1080be64bd88dca9a1d80130c558/Formula/python.rb --ignore-dependencies

After that I ran brew link --overwrite python. Now I have all pythons in the system to create the virtual environments.

mian@tdowrick2~ $ python --version
Python 2.7.10
mian@tdowrick2~ $ python3.7 --version
Python 3.7.1
mian@tdowrick2~ $ python3.6 --version
Python 3.6.5

To create Python 3.7 virtual environment.

mian@tdowrick2~ $ virtualenv -p python3.7 env
Already using interpreter /Library/Frameworks/Python.framework/Versions/3.7/bin/python3.7
Using base prefix '/Library/Frameworks/Python.framework/Versions/3.7'
New python executable in /Users/mian/env/bin/python3.7
Also creating executable in /Users/mian/env/bin/python
Installing setuptools, pip, wheel...
done.
mian@tdowrick2~ $ source env/bin/activate
(env) mian@tdowrick2~ $ python --version
Python 3.7.1
(env) mian@tdowrick2~ $ deactivate

To create Python 3.6 virtual environment

mian@tdowrick2~ $ virtualenv -p python3.6 env
Running virtualenv with interpreter /usr/local/bin/python3.6
Using base prefix '/usr/local/Cellar/python/3.6.5_1/Frameworks/Python.framework/Versions/3.6'
New python executable in /Users/mian/env/bin/python3.6
Not overwriting existing python script /Users/mian/env/bin/python (you must use /Users/mian/env/bin/python3.6)
Installing setuptools, pip, wheel...
done.
mian@tdowrick2~ $ source env/bin/activate
(env) mian@tdowrick2~ $ python --version
Python 3.6.5
(env) mian@tdowrick2~ $ 

installation app blocked by play protect

There are three options to get rid of this warning:

  1. You need to disable Play Protect in Play Store -> Play Protect -> Settings Icon -> Scan Device for security threats
  2. Publish app at Google Play Store
  3. Submit an Appeal to the Play Protect.

Dart/Flutter : Converting timestamp

Full code for anyone who needs it:

String readTimestamp(int timestamp) {
    var now = DateTime.now();
    var format = DateFormat('HH:mm a');
    var date = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);
    var diff = now.difference(date);
    var time = '';

    if (diff.inSeconds <= 0 || diff.inSeconds > 0 && diff.inMinutes == 0 || diff.inMinutes > 0 && diff.inHours == 0 || diff.inHours > 0 && diff.inDays == 0) {
      time = format.format(date);
    } else if (diff.inDays > 0 && diff.inDays < 7) {
      if (diff.inDays == 1) {
        time = diff.inDays.toString() + ' DAY AGO';
      } else {
        time = diff.inDays.toString() + ' DAYS AGO';
      }
    } else {
      if (diff.inDays == 7) {
        time = (diff.inDays / 7).floor().toString() + ' WEEK AGO';
      } else {

        time = (diff.inDays / 7).floor().toString() + ' WEEKS AGO';
      }
    }

    return time;
  }

Thank you Alex Haslam for the help!

Python Pandas User Warning: Sorting because non-concatenation axis is not aligned

jezrael's answer is good, but did not answer a question I had: Will getting the "sort" flag wrong mess up my data in any way? The answer is apparently "no", you are fine either way.

from pandas import DataFrame, concat

a = DataFrame([{'a':1,      'c':2,'d':3      }])
b = DataFrame([{'a':4,'b':5,      'd':6,'e':7}])

>>> concat([a,b],sort=False)
   a    c  d    b    e
0  1  2.0  3  NaN  NaN
0  4  NaN  6  5.0  7.0

>>> concat([a,b],sort=True)
   a    b    c  d    e
0  1  NaN  2.0  3  NaN
0  4  5.0  NaN  6  7.0

java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion

Do any of the following:

1- Update the play-services-maps library to the latest version:

com.google.android.gms:play-services-maps:16.1.0

2- Or include the following declaration within the <application> element of AndroidManifest.xml.

<uses-library
      android:name="org.apache.http.legacy"
      android:required="false" />

Scraping: SSL: CERTIFICATE_VERIFY_FAILED error for http://en.wikipedia.org

Use requests library. Try this solution, or just add https:// before the URL:

import requests
from bs4 import BeautifulSoup
import re

pages = set()
def getLinks(pageUrl):
    global pages
    html = requests.get("http://en.wikipedia.org"+pageUrl, verify=False).text
    bsObj = BeautifulSoup(html)
    for link in bsObj.findAll("a", href=re.compile("^(/wiki/)")):
        if 'href' in link.attrs:
            if link.attrs['href'] not in pages:
                #We have encountered a new page
                newPage = link.attrs['href']
                print(newPage)
                pages.add(newPage)
                getLinks(newPage)
getLinks("")

Check if this works for you

virtualbox Raw-mode is unavailable courtesy of Hyper-V windows 10

You may need to disable the hypervisor.

So, follow the next steps:

1) Open command prompt as Administrator

2) Run bcdedit to check hypervisor status:

bcdedit

3) Check hypervisor launch type:

image showing command output with 'hypervisorlaunchtype Auto' marked

4) If is set to auto then disable it:

bcdedit /set hypervisorlaunchtype off

5) Reboot host machine and launch VirtualBox again

Axios handling errors

If I understand correctly you want then of the request function to be called only if request is successful, and you want to ignore errors. To do that you can create a new promise resolve it when axios request is successful and never reject it in case of failure.

Updated code would look something like this:

export function request(method, uri, body, headers) {
  let config = {
    method: method.toLowerCase(),
    url: uri,
    baseURL: API_URL,
    headers: { 'Authorization': 'Bearer ' + getToken() },
    validateStatus: function (status) {
      return status >= 200 && status < 400
    }
  }


  return new Promise(function(resolve, reject) {
    axios(config).then(
      function (response) {
        resolve(response.data)
      }
    ).catch(
      function (error) {
        console.log('Show error notification!')
      }
    )
  });

}

What could cause an error related to npm not being able to find a file? No contents in my node_modules subfolder. Why is that?

It might be related to corruption in Angular Packages or incompatibility of packages.

Please follow the below steps to solve the issue.

Update

ASP.NET Boilerplate suggests here to use yarn because npm has some problems. It is slow and can not consistently resolve dependencies, yarn solves those problems and it is compatible to npm as well.

docker: Error response from daemon: Get https://registry-1.docker.io/v2/: Service Unavailable. IN DOCKER , MAC

I tried running on Windows, and got this problem after an update. I tried restarting the docker service as well as my pc, but nothing worked.

When running:

curl https://registry-1.docker.io/v2/ && echo Works

I got back:

{"errors":[{"code":"UNAUTHORIZED","message":"authentication required","detail":null}]}
Works

Eventually, I tried: https://github.com/moby/moby/issues/22635#issuecomment-284956961

By changing the fixed address to 8.8.8.8: enter image description here

Which worked for me! I still got the unauthorized message for curl https://registry-1.docker.io/v2/ but I managed to pull images from docker hub.

Getting "TypeError: failed to fetch" when the request hasn't actually failed

I understand this question might have a React-specific cause, but it shows up first in search results for "Typeerror: Failed to fetch" and I wanted to lay out all possible causes here.

The Fetch spec lists times when you throw a TypeError from the Fetch API: https://fetch.spec.whatwg.org/#fetch-api

Relevant passages as of January 2021 are below. These are excerpts from the text.

4.6 HTTP-network fetch

To perform an HTTP-network fetch using request with an optional credentials flag, run these steps:
...
16. Run these steps in parallel:
...
2. If aborted, then:
...
3. Otherwise, if stream is readable, error stream with a TypeError.

To append a name/value name/value pair to a Headers object (headers), run these steps:

  1. Normalize value.
  2. If name is not a name or value is not a value, then throw a TypeError.
  3. If headers’s guard is "immutable", then throw a TypeError.

Filling Headers object headers with a given object object:

To fill a Headers object headers with a given object object, run these steps:

  1. If object is a sequence, then for each header in object:
    1. If header does not contain exactly two items, then throw a TypeError.

Method steps sometimes throw TypeError:

The delete(name) method steps are:

  1. If name is not a name, then throw a TypeError.
  2. If this’s guard is "immutable", then throw a TypeError.

The get(name) method steps are:

  1. If name is not a name, then throw a TypeError.
  2. Return the result of getting name from this’s header list.

The has(name) method steps are:

  1. If name is not a name, then throw a TypeError.

The set(name, value) method steps are:

  1. Normalize value.
  2. If name is not a name or value is not a value, then throw a TypeError.
  3. If this’s guard is "immutable", then throw a TypeError.

To extract a body and a Content-Type value from object, with an optional boolean keepalive (default false), run these steps:
...
5. Switch on object:
...
ReadableStream
If keepalive is true, then throw a TypeError.
If object is disturbed or locked, then throw a TypeError.

In the section "Body mixin" if you are using FormData there are several ways to throw a TypeError. I haven't listed them here because it would make this answer very long. Relevant passages: https://fetch.spec.whatwg.org/#body-mixin

In the section "Request Class" the new Request(input, init) constructor is a minefield of potential TypeErrors:

The new Request(input, init) constructor steps are:
...
6. If input is a string, then:
...
2. If parsedURL is a failure, then throw a TypeError.
3. IF parsedURL includes credentials, then throw a TypeError.
...
11. If init["window"] exists and is non-null, then throw a TypeError.
...
15. If init["referrer" exists, then:
...
1. Let referrer be init["referrer"].
2. If referrer is the empty string, then set request’s referrer to "no-referrer".
3. Otherwise:
1. Let parsedReferrer be the result of parsing referrer with baseURL.
2. If parsedReferrer is failure, then throw a TypeError.
...
18. If mode is "navigate", then throw a TypeError.
...
23. If request's cache mode is "only-if-cached" and request's mode is not "same-origin" then throw a TypeError.
...
27. If init["method"] exists, then:
...
2. If method is not a method or method is a forbidden method, then throw a TypeError.
...
32. If this’s request’s mode is "no-cors", then:
1. If this’s request’s method is not a CORS-safelisted method, then throw a TypeError.
...
35. If either init["body"] exists and is non-null or inputBody is non-null, and request’s method is GET or HEAD, then throw a TypeError.
...
38. If body is non-null and body's source is null, then:
1. If this’s request’s mode is neither "same-origin" nor "cors", then throw a TypeError.
...
39. If inputBody is body and input is disturbed or locked, then throw a TypeError.

The clone() method steps are:

  1. If this is disturbed or locked, then throw a TypeError.

In the Response class:

The new Response(body, init) constructor steps are:
...
2. If init["statusText"] does not match the reason-phrase token production, then throw a TypeError.
...
8. If body is non-null, then:
1. If init["status"] is a null body status, then throw a TypeError.
...

The static redirect(url, status) method steps are:
...
2. If parsedURL is failure, then throw a TypeError.

The clone() method steps are:

  1. If this is disturbed or locked, then throw a TypeError.

In section "The Fetch method"

The fetch(input, init) method steps are:
...
9. Run the following in parallel:
To process response for response, run these substeps:
...
3. If response is a network error, then reject p with a TypeError and terminate these substeps.

In addition to these potential problems, there are some browser-specific behaviors which can throw a TypeError. For instance, if you set keepalive to true and have a payload > 64 KB you'll get a TypeError on Chrome, but the same request can work in Firefox. These behaviors aren't documented in the spec, but you can find information about them by Googling for limitations for each option you're setting in fetch.

Authentication plugin 'caching_sha2_password' cannot be loaded

For Windows 10,

  1. Modify my.ini file in C:\ProgramData\MySQL\MySQL Server 8.0\

    [mysqld]
    default_authentication_plugin=mysql_native_password
    
  2. Restart the MySQL Service.

  3. Login to MySQL on the command line, and execute the following commands in MySQL:

    • Create a new user.

      CREATE USER 'user'@'localhost' IDENTIFIED BY 'password';
      
    • Grant all privileges.

      GRANT ALL PRIVILEGES ON * .* TO 'user'@'localhost';
      
  4. Open MySQL workbench, and open a new connection using the new user credentials.

I was facing the same issue and this worked.

Error - Android resource linking failed (AAPT2 27.0.3 Daemon #0)

Had exactly the same problem. Solved it by doing the following: Searching for and replacing com.android.support:support-v4:+ with com.android.support:support-v4:27.1.0 in the platform/android directory.

Also I had to add the following code to the platforms/android/app/build.gradle and platforms/android/build.gradle files:

configurations.all {
resolutionStrategy {
    force 'com.android.support:support-v4:27.1.0'
}}

Edited to answer "Where is this com.android.support:support-v4:+ setting ?" ...

The setting will probably(in this case) be in one of your plugin's .gradle file in the platform/android/ directory, for example in my case it was the starter-barcodescanner plugin so just go through all your plugins .gradle files :

enter image description here

Double check the platforms/android/build.gradle file.

Hope this helps.

After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

I also read the Spring docs, as lapkritinis suggested - and luckily this brought me on the right path! But I don´t think, that the Spring docs explain this good right now. At least for me, they aren´t consistent IMHO.

The original problem/question is on what to do, if you upgrade an existing Spring Boot 1.5.x application to 2.0.x, which is using PostgreSQL/Hibernate. The main reason, you get your described error, is that Spring Boot 2.0.x uses HikariCP instead of Tomcat JDBC pooling DataSource as a default - and Hikari´s DataSource doesn´t know the spring.datasource.url property, instead it want´s to have spring.datasource.jdbc-url (lapkritinis also pointed that out).

So far so good. BUT the docs also suggest - and that´s the problem here - that Spring Boot uses spring.datasource.url to determine, if the - often locally used - embedded Database like H2 has to back off and instead use a production Database:

You should at least specify the URL by setting the spring.datasource.url property. Otherwise, Spring Boot tries to auto-configure an embedded database.

You may see the dilemma. If you want to have your embedded DataBase like you´re used to, you have to switch back to Tomcat JDBC. This is also much more minimally invasive to existing applications, as you don´t have to change source code! To get your existing application working after the Spring Boot 1.5.x --> 2.0.x upgrade with PostgreSQL, just add tomcat-jdbc as a dependency to your pom.xml:

    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-jdbc</artifactId>
    </dependency>

And then configure Spring Boot to use it accordingly inside application.properties:

spring.datasource.type=org.apache.tomcat.jdbc.pool.DataSource

Hope to help some folks with this, was quite a time consuming problem. I also hope my beloved Spring folks update the docs - and the way new Hikari pool is configured - to get a more consistent Spring Boot user experience :)

flutter run: No connected devices

I am facing the same issue with Flutter. But I found another way to work i.e.

  1. First run Android Emulator
  2. Then go to your Flutter Console
  3. Run the command flutter doctor & check whether your emulator is showing under connected devices tag e.g. enter image description here

  4. Now move to your Flutter project path via Flutter console e.g. for me it is D:\FlutterWorkspace\flutter_demo

  5. Then run flutter run command. e.g.

enter image description here

Wait for few moments you will see your app running into Android Emulator. enter image description here

Angular 5, HTML, boolean on checkbox is checked

Hope this will help somebody to develop custom checkbox component with custom styles. This solution can use with forms too.

HTML

<label class="lbl">

  <input #inputEl type="checkbox" [name]="label" [(ngModel)]="isChecked" (change)="onChange(inputEl.checked)"
   *ngIf="isChecked" checked>
  <input #inputEl type="checkbox" [name]="label" [(ngModel)]="isChecked" (change)="onChange(inputEl.checked)"
   *ngIf="!isChecked" >
  <span class="chk-box {{isChecked ? 'chk':''}}"></span>
  <span class="lbl-txt" *ngIf="label" >{{label}}</span>
</label>

checkbox.component.ts

    import { Component, Input, EventEmitter, Output, forwardRef, HostListener } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

const noop = () => {
};

export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => CheckboxComponent),
  multi: true
};

/** Custom check box  */
@Component({
  selector: 'app-checkbox',
  templateUrl: './checkbox.component.html',
  styleUrls: ['./checkbox.component.scss'],
  providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
})
export class CheckboxComponent implements ControlValueAccessor {


  @Input() label: string;
  @Input() isChecked = false;
  @Input() disabled = false;
  @Output() getChange = new EventEmitter();
  @Input() className: string;

  // get accessor
  get value(): any {
    return this.isChecked;
  }

  // set accessor including call the onchange callback
  set value(value: any) {
    this.isChecked = value;
  }

  private onTouchedCallback: () => void = noop;
  private onChangeCallback: (_: any) => void = noop;


  writeValue(value: any): void {
    if (value !== this.isChecked) {
      this.isChecked = value;
    }
  }

  onChange(isChecked) {
    this.value = isChecked;
    this.getChange.emit(this.isChecked);
    this.onChangeCallback(this.value);
  }

  // From ControlValueAccessor interface
  registerOnChange(fn: any) {
    this.onChangeCallback = fn;
  }

  // From ControlValueAccessor interface
  registerOnTouched(fn: any) {
    this.onTouchedCallback = fn;
  }

  setDisabledState?(isDisabled: boolean): void {

  }

}

checkbox.component.scss

   @import "../../../assets/scss/_variables";
/* CHECKBOX */

.lbl {
    font-size: 12px;
    color: #282828;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    cursor: pointer;
    &.checked {
        font-weight: 600;
    }
    &.focus {
      .chk-box{
        border: 1px solid #a8a8a8;
        &.chk{
          border: none;
        }
      }
    }
    input {
        display: none;
    }

    /* checkbox icon */
    .chk-box {
        display: block;
        min-width: 15px;
        min-height: 15px;
        background: url('/assets/i/checkbox-not-selected.svg');
        background-size: 15px 15px;
        margin-right: 10px;
    }
    input:checked+.chk-box {
        background: url('/assets/i/checkbox-selected.svg');
        background-size: 15px 15px;
    }
    .lbl-txt {
        margin-top: 0px;
    } 

}

Usage

Outside forms

<app-checkbox [label]="'Example'" [isChecked]="true"></app-checkbox>

Inside forms

<app-checkbox [label]="'Type 0'" formControlName="Type1"></app-checkbox>

ERROR Source option 1.5 is no longer supported. Use 1.6 or later

This error might be also for plugin versions. You can fix it in the .POM file like the followings:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.1</version>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
            </configuration>
        </plugin>
    </plugins>
</build>

Docker error: invalid reference format: repository name must be lowercase

Let me emphasise that Docker doesn't even allow mixed characters.

Good: docker build -t myfirstechoimage:0.1 .

Bad: docker build -t myFirstEchoImage:0.1 .

PackagesNotFoundError: The following packages are not available from current channels:

Try adding the conda-forge channel to your list of channels with this command:
conda config --append channels conda-forge. It tells conda to also look on the conda-forge channel when you search for packages. You can then simply install the two packages with conda install slycot control.

Channels are basically servers for people to host packages on and the community-driven conda-forge is usually a good place to start when packages are not available via the standard channels. I checked and both slycot and control seem to be available there.

How to view instagram profile picture in full-size?

You can even set the prof. pic size to its high resolution that is '1080x1080'

replace "150x150" with 1080x1080 and remove /vp/ from the link.

Assets file project.assets.json not found. Run a NuGet package restore

It was mentioned earlier but I just wanted to re-emphasize the importance of not have space anywhere in your pathing! This is what was getting me. You've been warned.

Issue in installing php7.2-mcrypt

As an alternative, you can install 7.1 version of mcrypt and create a symbolic link to it:

Install php7.1-mcrypt:

sudo apt install php7.1-mcrypt

Create a symbolic link:

sudo ln -s /etc/php/7.1/mods-available/mcrypt.ini /etc/php/7.2/mods-available

After enabling mcrypt by sudo phpenmod mcrypt, it gets available.

Execution failed for task ':app:compileDebugJavaWithJavac' Android Studio 3.1 Update

Go to preferences(settings) : click on Build,Execution,Deployment .....then select : Instant Run ......and uncheck its topmost checkbox (i.e Disable Instant Run)

NullInjectorError: No provider for AngularFirestore

I had same issue and below is resolved.

Old Service Code:

@Injectable()

Updated working Service Code:

@Injectable({
  providedIn: 'root'
})

INSTALL_FAILED_USER_RESTRICTED : android studio using redmi 4 device

To turn on "Install via USB" and "USB Debugging(Security changes)" need to sign in to xiaomi account then these 2 can be turned on and work with redmi as developer

Note:When turning on USB Debugging(Security changes) few security alerts will be poped up all need to be accepted to work on developer mode

Android Studio 3.0 Execution failed for task: unable to merge dex

I also got the similar error.

Problem :

enter image description here

Solution :

Main root cause for this issue ismultiDex is not enabled. So in the Project/android/app/build.gradle, enable the multiDex

For further information refer the documentation: https://developer.android.com/studio/build/multidex#mdex-gradle

enter image description here

Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?'

This command did the trick from @Aniket Sinha's answer above:

pip install mysqlclient

Ajax LARAVEL 419 POST error

You don't have any data that you're submitting! Try adding this line to your ajax:

data: $('form').serialize(),

Make sure you change the name to match!

Also your data should be submitted inside of a form submit function.

Your code should look something like this:

_x000D_
_x000D_
<script>_x000D_
 $(function () {_x000D_
  $('form').on('submit', function (e) {_x000D_
   e.preventDefault();_x000D_
   $.ajax({_x000D_
    type: 'post',_x000D_
    url: 'company.php',_x000D_
    data: $('form').serialize(),_x000D_
    success: function () {_x000D_
     alert('form was submitted');_x000D_
    }_x000D_
   });_x000D_
  });_x000D_
 });_x000D_
</script>
_x000D_
_x000D_
_x000D_

ERROR in ./node_modules/css-loader?

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

OR

npm install node-sass


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

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

Enable/disable buttons with Angular

    <div class="col-md-12">
      <p style="color: #28a745; font-weight: bold; font-size:25px; text-align: right " >Total Productos a pagar= {{ getTotal() }} {{ getResult() | currency }}
      <button class="btn btn-success" type="submit" [disabled]="!getResult()" (click)="onSubmit()">
        Ver Pedido
      </button>
     </p>
    </div>

How to view Plugin Manager in Notepad++

Follow the steps given below:

  1. Download Plugin Manager from here.

    • You can find the most updated version in the release section in the Git repository:
  2. Extract the contents of zip file under "C:\Program Files\Notepad++"

  3. Restart Notepad++

That's it !!

git clone error: RPC failed; curl 56 OpenSSL SSL_read: SSL_ERROR_SYSCALL, errno 10054

you need to increase the buffer size (it's due to the large repository size), so you have to increase it

git config http.postBuffer 524288000

Althought you must have an initializd repository, just porceed as the following

git init
git config http.postBuffer 524288000
git remote add origin <REPO URL>
git pull origin master
...

Extract a page from a pdf as a jpeg

Their is a utility called pdftojpg which can be used to convert the pdf to img

You can found the code here https://github.com/pankajr141/pdf2jpg

from pdf2jpg import pdf2jpg
inputpath = r"D:\inputdir\pdf1.pdf"
outputpath = r"D:\outputdir"
# To convert single page
result = pdf2jpg.convert_pdf2jpg(inputpath, outputpath, pages="1")
print(result)

# To convert multiple pages
result = pdf2jpg.convert_pdf2jpg(inputpath, outputpath, pages="1,0,3")
print(result)

# to convert all pages
result = pdf2jpg.convert_pdf2jpg(inputpath, outputpath, pages="ALL")
print(result)

How do you set the document title in React?

const setTitle = (title) => {
  const prevTitle = document.title;
  document.title = title;
  return () => document.title = prevTitle;
}

const MyComponent = () => {
  useEffect(() => setTitle('Title while MyComponent is mounted'), []);

  return <div>My Component</div>;
}

This is a pretty straight forward solution I threw together while working today. setTitle returns a function that resets the title to what it was prior to using setTitle, it works wonderfully inside of React's useEffect hook.

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

You need to only depend on one major version of angular, so update all modules depending on angular 2.x :

  • update @angular/flex-layout to ^2.0.0-beta.9
  • update @angular/material to ^2.0.0-beta.12
  • update angularfire2 to ^4.0.0-rc.2
  • update zone.js to ^0.8.18
  • update webpack to ^3.8.1
  • add @angular/[email protected] (required for @angular/material)
  • replace angular2-google-maps by @agm/[email protected] (new name)

VSCode cannot find module '@angular/core' or any other modules

I solved this problem as follow:

  1. Open Visual studio code with your project.
  2. Terminal -> New Terminal.
  3. Write npm install.

Node.js: Python not found exception due to node-sass and node-gyp

Node-sass tries to download the binary for you platform when installing. Node 5 is supported by 3.8 https://github.com/sass/node-sass/releases/tag/v3.8.0 If your Jenkins can't download the prebuilt binary, then you need to follow the platform requirements on Node-gyp README (Python2, VS or MSBuild, ...) If possible I'd suggest updating your Node to at least 6 since 5 isn't supported by Node anymore. If you want to upgrade to 8, you'll need to update node-sass to 4.5.3

Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App

If you need in different Layer :

Create a Static Class and expose all config properties on that layer as below :

_x000D_
_x000D_
using Microsoft.Extensions.Configuration;_x000D_
using System.IO;_x000D_
_x000D_
namespace Core.DAL_x000D_
{_x000D_
    public static class ConfigSettings_x000D_
    {_x000D_
        public static string conStr1 { get ; }_x000D_
        static ConfigSettings()_x000D_
        {_x000D_
            var configurationBuilder = new ConfigurationBuilder();_x000D_
            string path = Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json");_x000D_
            configurationBuilder.AddJsonFile(path, false);_x000D_
            conStr1 = configurationBuilder.Build().GetSection("ConnectionStrings:ConStr1").Value;_x000D_
        }_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

Angular 4 HttpClient Query Parameters

If you have an object that can be converted to {key: 'stringValue'} pairs, you can use this shortcut to convert it:

this._Http.get(myUrlString, {params: {...myParamsObject}});

I just love the spread syntax!

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

you have to tell angular that you updated the content after ngAfterContentChecked you can import ChangeDetectorRef from @angular/core and call detectChanges

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

constructor( private cdref: ChangeDetectorRef ) {}


ngAfterContentChecked() {

this.sampleViewModel.DataContext = this.DataContext;
this.sampleViewModel.Position = this.Position;
this.cdref.detectChanges();

 }

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.

Update .NET web service to use TLS 1.2

We actually just upgraded a .NET web service to 4.6 to allow TLS 1.2.

What Artem is saying were the first steps we've done. We recompiled the framework of the web service to 4.6 and we tried change the registry key to enable TLS 1.2, although this didn't work: the connection was still in TLS 1.0. Also, we didn't want to disallow SLL 3.0, TLS 1.0 or TLS 1.1 on the machine: other web services could be using this; we rolled-back our changes on the registry.

We actually changed the Web.Config files to tell IIS: "hey, run me in 4.6 please".

Here's the changes we added in the web.config + recompilation in .NET 4.6:

<system.web>
    <compilation targetFramework="4.6"/> <!-- Changed framework 4.0 to 4.6 -->

    <!--Added this httpRuntime -->
    <httpRuntime targetFramework="4.6" />

    <authentication mode="Windows"/>
    <pages controlRenderingCompatibilityVersion="4.0"/>
</system.web>

And the connection changed to TLS 1.2, because IIS is now running the web service in 4.6 (told explicitly) and 4.6 is using TLS 1.2 by default.

How to format JSON in notepad++

The answer was to install the plugin individually. I installed all the three plugins shown in the screenshot together. And it created the issue. I had to install each plugin individually and then it worked fine. I am able to format the JSON string.

Get current url in Angular

other.component.ts

So final correct solution is :

import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router'; 

/* 'router' it must be in small case */

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

    export class OtherComponent implements OnInit {

        public href: string = "";
        url: string = "asdf";

        constructor(private router : Router) {} // make variable private so that it would be accessible through out the component

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

Maintaining href "open in new tab" with an onClick handler in React

You have two options here, you can make it open in a new window/tab with JS:

<td onClick={()=> window.open("someLink", "_blank")}>text</td>

But a better option is to use a regular link but style it as a table cell:

<a style={{display: "table-cell"}} href="someLink" target="_blank">text</a>

iOS 11, 12, and 13 installed certificates not trusted automatically (self signed)

This has happened to me also, after undating to IOS11 on my iPhone. When I try to connect to the corporate network it bring up the corporate cert and says it isn't trusted. I press the 'trust' button and the connection fails and the cert does not appear in the trusted certs list.

EF Core add-migration Build Failed

Just got into this issue. In my case, I was debugging my code and it was making my migrations fail.

Since in Visual Studio Code, the debugger is so low-profile (only a small bar), I didn't realize about this until I read some questions and decided to look better.

Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running?

This worked for me, It might just work for you if you are using Ubuntu 16 or 18 (14 may also work). Easy to give a try:

Go to Ubuntu Software, type in Docker. Uninstall docker (108 mb) if it is preinstalled there. Install docker Now run the commands and see if the same error comes

The error:

enter image description here

After doing the above steps. enter image description here

As you can see, it worked:)

Android dependency has different version for the compile and runtime

If anyone getting this dependency issue in 2019, update Android Studio to 3.4 or later

Pandas create empty DataFrame with only column names

Are you looking for something like this?

    COLUMN_NAMES=['A','B','C','D','E','F','G']
    df = pd.DataFrame(columns=COLUMN_NAMES)
    df.columns

   Index(['A', 'B', 'C', 'D', 'E', 'F', 'G'], dtype='object')

Enums in Javascript with ES6

Maybe this solution ? :)

function createEnum (array) {
  return Object.freeze(array
    .reduce((obj, item) => {
      if (typeof item === 'string') {
        obj[item.toUpperCase()] = Symbol(item)
      }
      return obj
    }, {}))
}

Example:

createEnum(['red', 'green', 'blue']);

> {RED: Symbol(red), GREEN: Symbol(green), BLUE: Symbol(blue)}

How to enable CORS in ASP.net Core WebAPI

I think if you use your own CORS middleware you need to make sure it is really CORS request by checking origin header.

 public class CorsMiddleware
{
    private readonly RequestDelegate _next;
    private readonly IMemoryCache _cache;
    private readonly ILogger<CorsMiddleware> _logger;

    public CorsMiddleware(RequestDelegate next, IMemoryCache cache, ILogger<CorsMiddleware> logger)
    {
        _next = next;
        _cache = cache;
        _logger = logger;
    }
    public async Task InvokeAsync(HttpContext context, IAdministrationApi adminApi)
    {
        if (context.Request.Headers.ContainsKey(CorsConstants.Origin) || context.Request.Headers.ContainsKey("origin"))
        {
            if (!context.Request.Headers.TryGetValue(CorsConstants.Origin, out var origin))
            {
                context.Request.Headers.TryGetValue("origin", out origin);
            }

            bool isAllowed;
            // Getting origin from DB to check with one from request and save it in cache 
            var result = _cache.GetOrCreateAsync(origin, async cacheEntry => await adminApi.DoesExistAsync(origin));
            isAllowed = result.Result.Result;

            if (isAllowed)
            {
                context.Response.Headers.Add(CorsConstants.AccessControlAllowOrigin, origin);
                context.Response.Headers.Add(
                    CorsConstants.AccessControlAllowHeaders,
                    $"{HeaderNames.Authorization}, {HeaderNames.ContentType}, {HeaderNames.AcceptLanguage}, {HeaderNames.Accept}");
                context.Response.Headers.Add(CorsConstants.AccessControlAllowMethods, "POST, GET, PUT, PATCH, DELETE, OPTIONS");

                if (context.Request.Method == "OPTIONS")
                {
                    _logger.LogInformation("CORS with origin {Origin} was handled successfully", origin);
                    context.Response.StatusCode = (int)HttpStatusCode.NoContent;
                    return;
                }

                await _next(context);
            }
            else
            {
                if (context.Request.Method == "OPTIONS")
                {
                    _logger.LogInformation("Preflight CORS request with origin {Origin} was declined", origin);
                    context.Response.StatusCode = (int)HttpStatusCode.NoContent;
                    return;
                }

                _logger.LogInformation("Simple CORS request with origin {Origin} was declined", origin);
                context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                return;
            }
        }

        await _next(context);
    }

How to download Visual Studio Community Edition 2015 (not 2017)

You can use these links to download Visual Studio 2015

Community Edition:

And for anyone in the future who might be looking for the other editions here are the links for them as well:

Professional Edition:

Enterprise Edition:

VS 2017 Metadata file '.dll could not be found

I had the same issue. My problem was someone else on the team moved a class folder, and the project was looking for it.

For me, there were 44 errors; 43 ended in .dll (searching for a dependency) and the first one in the error list ended with .cs (searching for the actual class). I tried clean-build, and clean, unload, reload, build, but nothing working. I ended up locating the class in the project, and just deleted it, as it was showing up as unavailable anyways, followed by a clean-build.

That did the trick for me! Hope this helps.

Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error

Faced the same issue, another solution is to add default includes, this fixed the problem for me:

$(IncludePath);

How do I Set Background image in Flutter?

import 'package:flutter/material.dart';

void main() => runApp(DestiniApp());

class DestiniApp extends StatefulWidget {
  @override
  _DestiniAppState createState() => _DestiniAppState();
}

class _DestiniAppState extends State<DestiniApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: SafeArea(
        child: Scaffold(
          appBar: AppBar(
            backgroundColor: Color.fromRGBO(245, 0, 87, 1),
            title: Text(
              "Landing Page Bankground Image",
            ),
          ),
          body: Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                  image: ExactAssetImage("images/appBack.jpg"),
                  fit: BoxFit.cover
              ),
            ),
          ),
        ),
      ),
    );
  }
}

Output: enter image description here

Cannot connect to the Docker daemon on macOS

on OSX assure you have launched the Docker application before issuing

docker ps

or docker build ... etc ... yes it seems strange and somewhat misleading that issuing

docker --version

gives version even though the docker daemon is not running ... ditto for those other version cmds ... I just encountered exactly the same symptoms ... this behavior on OSX is different from on linux

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

I you want to put the response of the request in the navItems. Because http.get() return an observable you will have to subscribe to it.

Look at this example:

_x000D_
_x000D_
// version without map_x000D_
this.http.get("../data/navItems.json")_x000D_
    .subscribe((success) => {_x000D_
      this.navItems = success.json();          _x000D_
    });_x000D_
_x000D_
// with map_x000D_
import 'rxjs/add/operator/map'_x000D_
this.http.get("../data/navItems.json")_x000D_
    .map((data) => {_x000D_
      return data.json();_x000D_
    })_x000D_
    .subscribe((success) => {_x000D_
      this.navItems = success;          _x000D_
    });
_x000D_
_x000D_
_x000D_

Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details

in my case:: I was using kotlin extensions to access and bind my views, I had recently moved a view to another screen and forgot to remove its reference from the previous fragment that caused this error.

kotlin synthetic extensions are not compile time safe. I really loved this but apparently in big projects, if this happens again I'm surely going to get a heart attack.

How to get root directory of project in asp.net core. Directory.GetCurrentDirectory() doesn't seem to work correctly on a mac

If that can be useful to anyone, in a Razor Page cshtml.cs file, here is how to get it: add an IHostEnvironment hostEnvironment parameter to the constructor and it will be injected automatically:

public class IndexModel : PageModel
{
    private readonly ILogger<IndexModel> _logger;
    private readonly IHostEnvironment _hostEnvironment;

    public IndexModel(ILogger<IndexModel> logger, IHostEnvironment hostEnvironment)
    {
        _logger = logger;
        _hostEnvironment = hostEnvironment; // has ContentRootPath property
    }

    public void OnGet()
    {

    }
}

PS: IHostEnvironment is in Microsoft.Extensions.Hosting namespace, in Microsoft.Extensions.Hosting.Abstractions.dll ... what a mess!

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

Another way (worked for 2015) is open "Install/remove programs" (Apps & features), find Visual Studio, select Modify. In opened window, press Modify, check

  • Languages -> Visual C++ -> Common tools for Visual C++
  • Windows and web development -> Tools for universal windows apps -> Tools (1.4.1) and Windows 10 SDK ([version])
  • Windows and web development -> Tools for universal windows apps -> Windows 10 SDK ([version])

and install. Then right click on solution -> Re-target and it will compile

Python Pandas iterate over rows and access column names

for i in range(1,len(na_rm.columns)):
           print ("column name:", na_rm.columns[i])

Output :

column name: seretide_price
column name: symbicort_mkt_shr
column name: symbicort_price

use Lodash to sort array of object by value

This method orderBy does not change the input array, you have to assign the result to your array :

var chars = this.state.characters;

chars = _.orderBy(chars, ['name'],['asc']); // Use Lodash to sort array by 'name'

 this.setState({characters: chars})

How to check if a value is not null and not empty string in JS

I often test for truthy value and also for empty spaces in the string:

if(!(!data || data.trim().length === 0)) {
  // do something here
}

If you have a string consisting of one or more empty spaces it will evaluate to true.

IOPub data rate exceeded in Jupyter notebook (when viewing image)

Removing print statements can also fix the problem.

Apart from loading images, this error also happens when your code is printing continuously at a high rate, which is causing the error "IOPub data rate exceeded". E.g. if you have a print statement in a for loop somewhere that is being called over 1000 times.

How to use paths in tsconfig.json?

This works for me:

 yarn add --dev tsconfig-paths

 ts-node -r tsconfig-paths/register <your-index-file>.ts

This loads all paths in tsconfig.json. A sample tsconfig.json:

{
    "compilerOptions": {
        {…}
        "baseUrl": "./src",
        "paths": {
            "assets/*": [ "assets/*" ],
            "styles/*": [ "styles/*" ]
        }
    },
}

Make sure you have both baseUrl and paths for this to work

And then you can import like :

import {AlarmIcon} from 'assets/icons'

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

Don't use userForm = new FormGroup()

Use form = new FormGroup() instead.

And in the form use <form [formGroup]="form"> ...</form>. It works for me with angular 6

Seaborn Barplot - Displaying Values

Works with single ax or with matrix of ax (subplots)

from matplotlib import pyplot as plt
import numpy as np

def show_values_on_bars(axs):
    def _show_on_single_plot(ax):        
        for p in ax.patches:
            _x = p.get_x() + p.get_width() / 2
            _y = p.get_y() + p.get_height()
            value = '{:.2f}'.format(p.get_height())
            ax.text(_x, _y, value, ha="center") 

    if isinstance(axs, np.ndarray):
        for idx, ax in np.ndenumerate(axs):
            _show_on_single_plot(ax)
    else:
        _show_on_single_plot(axs)

fig, ax = plt.subplots(1, 2)
show_values_on_bars(ax)

pgadmin4 : postgresql application server could not be contacted.

I use the cmd prompt on Windows 10 with psql postgres postgres.

Then I launch pgAdmin4 and it works.

How to convert string to Date in Angular2 \ Typescript?

You can use date filter to convert in date and display in specific format.

In .ts file (typescript):

let dateString = '1968-11-16T00:00:00' 
let newDate = new Date(dateString);

In HTML:

{{dateString |  date:'MM/dd/yyyy'}}

Below are some formats which you can implement :

Backend:

public todayDate = new Date();

HTML :

<select>
<option value=""></option>
<option value="MM/dd/yyyy">[{{todayDate | date:'MM/dd/yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy">[{{todayDate | date:'EEEE, MMMM d, yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm a'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm:ss a'}}]</option>
<option value="MM/dd/yyyy h:mm a">[{{todayDate | date:'MM/dd/yyyy h:mm a'}}]</option>
<option value="MM/dd/yyyy h:mm:ss a">[{{todayDate | date:'MM/dd/yyyy h:mm:ss a'}}]</option>
<option value="MMMM d">[{{todayDate | date:'MMMM d'}}]</option>   
<option value="yyyy-MM-ddTHH:mm:ss">[{{todayDate | date:'yyyy-MM-ddTHH:mm:ss'}}]</option>
<option value="h:mm a">[{{todayDate | date:'h:mm a'}}]</option>
<option value="h:mm:ss a">[{{todayDate | date:'h:mm:ss a'}}]</option>      
<option value="EEEE, MMMM d, yyyy hh:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy hh:mm:ss a'}}]</option>
<option value="MMMM yyyy">[{{todayDate | date:'MMMM yyyy'}}]</option> 
</select>

SyntaxError: unexpected EOF while parsing

There are some cases can lead to this issue, if it occered in the middle of the code it will be "IndentationError: expected an indented block" or "SyntaxError: invalid syntax", if it at the last line it may "SyntaxError: unexpected EOF while parsing":

Missing the body of "if","while"and"for" statement-->

root@nest:~/workplace# cat test.py
l = [1,2,3]
for i in l:
root@nest:~/workplace# python3 test.py
  File "test.py", line 3

               ^
SyntaxError: unexpected EOF while parsing

Unclosed parentheses (Especially in complex nested states)-->

root@nest:~/workplace# cat test.py
l = [1,2,3]
print( l
root@nest:~/workplace# python3 test.py
  File "test.py", line 3

            ^
SyntaxError: unexpected EOF while parsing

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

Hope this helps. From eclipse, you right click the project -> Run As -> Run on Server and then it worked for me. I used Eclipse Jee Neon and Apache Tomcat 9.0. :)

I just removed the head portion in index.html file and it worked fine.This is the head tag in html file

UndefinedMetricWarning: F-score is ill-defined and being set to 0.0 in labels with no predicted samples

As the error message states, the method used to get the F score is from the "Classification" part of sklearn - thus the talking about "labels".

Do you have a regression problem? Sklearn provides a "F score" method for regression under the "feature selection" group: http://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.f_regression.html

In case you do have a classification problem, @Shovalt's answer seems correct to me.

typescript: error TS2693: 'Promise' only refers to a type, but is being used as a value here

Just change the target to "ES2017" in tsconfig.json file.

this is my tsconfig.json file

{
"compilerOptions": {
/* Basic Options */
    "target": "ES2017",   /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */
    "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    "declaration": true,  /* Generates corresponding '.d.ts' file. */
    "sourceMap": true,    /* Generates corresponding '.map' file. */
    "outDir": "./dist",   /* Redirect output structure to the directory. */
    "strict": true        /* Enable all strict type-checking options. */
  },
  "include": [
    "src/**/*"
  ],
  "exclude": [
    "node_modules"
  ]
}

How to install pandas from pip on windows cmd?

Since both pip nor python commands are not installed along Python in Windows, you will need to use the Windows alternative py, which is included by default when you installed Python. Then you have the option to specify a general or specific version number after the py command.

C:\> py      -m pip install pandas  %= one of Python on the system =%
C:\> py -2   -m pip install pandas  %= one of Python 2 on the system =%
C:\> py -2.7 -m pip install pandas  %= only for Python 2.7 =%
C:\> py -3   -m pip install pandas  %= one of Python 3 on the system =%
C:\> py -3.6 -m pip install pandas  %= only for Python 3.6 =%

Alternatively, in order to get pip to work without py -m part, you will need to add pip to the PATH environment variable.

C:\> setx PATH "%PATH%;C:\<path\to\python\folder>\Scripts"

Now you can run the following command as expected.

C:\> pip install pandas

Troubleshooting:


Problem:

connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed

Solution:

This is caused by your SSL certificate is unable to verify the host server. You can add pypi.python.org to the trusted host or specify an alternative SSL certificate. For more information, please see this post. (Thanks to Anuj Varshney for suggesting this)

C:\> py -m pip install --trusted-host pypi.python.org pip pandas

Problem:

PermissionError: [WinError 5] Access is denied

Solution:

This is a caused by when you don't permission to modify the Python site-package folders. You can avoid this with one of the following methods:

  • Run Windows Command Prompt as administrator (thanks to DataGirl's suggestion) by:

    1. Windows-Key + R to open run
    2. type in cmd.exe in the search box
    3. CTRL + SHIFT + ENTER
    4. An alternative method for step 1-3 would be to manually locate cmd.exe, right click, then click Run as Administrator.
  • Run pip in user mode by adding --user option when installing with pip. Which typically install the package to the local %APPDATA% Python folder.

C:\> py -m pip install --user pandas
C:\> py -m venv c:\path\to\new\venv
C:\> <path\to\the\new\venv>\Scripts\activate.bat

Unit Tests not discovered in Visual Studio 2017

In my case, it was UWP project present in the solution causing the issue.

When I unloaded the UWP project, tests were discovered. When I loaded it back, test disappeard again.

Try to unload all projects and keep test project only. Ten rebuild solution and test shound appear in Test Runner. Load projects one by one and rebuild solution each time to find out what project are causing the problem

sample repo

VS bug report

Vuejs and Vue.set(), update array

VueJS can't pickup your changes to the state if you manipulate arrays like this.

As explained in Common Beginner Gotchas, you should use array methods like push, splice or whatever and never modify the indexes like this a[2] = 2 nor the .length property of an array.

_x000D_
_x000D_
new Vue({_x000D_
  el: '#app',_x000D_
  data: {_x000D_
    f: 'DD-MM-YYYY',_x000D_
    items: [_x000D_
      "10-03-2017",_x000D_
      "12-03-2017"_x000D_
    ]_x000D_
  },_x000D_
  methods: {_x000D_
_x000D_
    cha: function(index, item, what, count) {_x000D_
      console.log(item + " index > " + index);_x000D_
      val = moment(this.items[index], this.f).add(count, what).format(this.f);_x000D_
_x000D_
      this.items.$set(index, val)_x000D_
      console.log("arr length:  " + this.items.length);_x000D_
    }_x000D_
  }_x000D_
})
_x000D_
ul {_x000D_
  list-style-type: none;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.11/vue.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>_x000D_
<div id="app">_x000D_
  <ul>_x000D_
    <li v-for="(index, item) in items">_x000D_
      <br><br>_x000D_
      <button v-on:click="cha(index, item, 'day', -1)">_x000D_
      - day</button> {{ item }}_x000D_
      <button v-on:click="cha(index, item, 'day', 1)">_x000D_
      + day</button>_x000D_
      <br><br>_x000D_
    </li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Change line width of lines in matplotlib pyplot legend

@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.

Method 1

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
    line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
    text.set_fontsize('x-large')

plt.savefig('leg_example')
plt.show()

Method 2

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()

The above two methods produce the same output image:

output image

Error:Failed to open zip file. Gradle's dependency cache may be corrupt

Find 'gradle-wrapper.properties' in root project

distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip

Change "https" to "http".

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

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

    cordova platform update android@latest

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

Copy Files from Windows to the Ubuntu Subsystem

You should only access Linux files system (those located in lxss folder) from inside WSL; DO NOT create/modify any files in lxss folder in Windows - it's dangerous and WSL will not see these files.

Files can be shared between WSL and Windows, though; put the file outside of lxss folder. You can access them via drvFS (/mnt) such as /mnt/c/Users/yourusername/files within WSL. These files stay synced between WSL and Windows.

For details and why, see: https://blogs.msdn.microsoft.com/commandline/2016/11/17/do-not-change-linux-files-using-windows-apps-and-tools/

How to use local docker images with Minikube?

One approach is to build the image locally and then do:

docker save imageNameGoesHere | pv | (eval $(minikube docker-env) && docker load)

minikube docker-env might not return the correct info running under a different user / sudo. Instead you can run sudo -u yourUsername minikube docker-env.

It should return something like:

export DOCKER_TLS_VERIFY="1"
export DOCKER_HOST="tcp://192.168.99.100:2376"
export DOCKER_CERT_PATH="/home/chris/.minikube/certs"
export DOCKER_API_VERSION="1.23"
# Run this command to configure your shell:
# eval $(minikube docker-env)

How can I make Bootstrap 4 columns all the same height?

You can use the new Bootstrap cards:

_x000D_
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>_x000D_
_x000D_
<div class="card-group">_x000D_
  <div class="card">_x000D_
    <img class="card-img-top" src="..." alt="Card image cap">_x000D_
    <div class="card-block">_x000D_
      <h4 class="card-title">Card title</h4>_x000D_
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>_x000D_
    </div>_x000D_
    <div class="card-footer">_x000D_
      <small class="text-muted">Last updated 3 mins ago</small>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="card">_x000D_
    <img class="card-img-top" src="..." alt="Card image cap">_x000D_
    <div class="card-block">_x000D_
      <h4 class="card-title">Card title</h4>_x000D_
      <p class="card-text">This card has supporting text below as a natural lead-in to additional content.</p>_x000D_
    </div>_x000D_
    <div class="card-footer">_x000D_
      <small class="text-muted">Last updated 3 mins ago</small>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="card">_x000D_
    <img class="card-img-top" src="..." alt="Card image cap">_x000D_
    <div class="card-block">_x000D_
      <h4 class="card-title">Card title</h4>_x000D_
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.</p>_x000D_
    </div>_x000D_
    <div class="card-footer">_x000D_
      <small class="text-muted">Last updated 3 mins ago</small>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Link: Click here

regards,

Maven build Compilation error : Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project Maven

This is an irritating error that pops up once in a while , jotting down some steps which help:

Writing answer from eclipse perspective as base logic will remain the same whether done by Intellij or command line

  1. Rt click your project -> Maven -> Update project -> Select Force update -> Click OK
  2. Under properties tag , add :
<maven.compiler.source>1.8</maven.compiler.source> 
<maven.compiler.target>1.8</maven.compiler.target>
  1. In some instances, you will start seeing error as we tried force update saying , failure to transfer X dependency from Y path , resolutions will not be reattempted , bla bla bla

    In such case quickly fix it by cd to .m2/repository folder and run following command :

for /r %i in (*.lastUpdated) do del %i

"SSL certificate verify failed" using pip to install packages

If adding pypi.python.org as a trusted host does not work, you try adding files.pythonhosted.org. For example

python -m pip install --upgrade --trusted-host files.pythonhosted.org <package-name>

The default XML namespace of the project must be the MSBuild XML namespace

if the project is not a big ,

1- change the name of folder project

2- make a new project with the same project (before renaming)

3- add existing files from the old project to the new project (totally same , same folders , same names , ...)

4- open the the new project file (as xml ) and the old project

5- copy the new project file (xml content ) and paste it in the old project file

6- delete the old project

7- rename the old folder project to old name

Cannot read property 'style' of undefined -- Uncaught Type Error

Add your <script> to the bottom of your <body>, or add an event listener for DOMContentLoaded following this StackOverflow question.

If that script executes in the <head> section of the code, document.getElementsByClassName(...) will return an empty array because the DOM is not loaded yet.

You're getting the Type Error because you're referencing search_span[0], but search_span[0] is undefined.

This works when you execute it in Dev Tools because the DOM is already loaded.

Changing the git user inside Visual Studio Code

You can view all of your settings and where they are coming from using:

git config --list --show-origin

Delete the unwanted credentials from the directory and then VSCode ask you for the next time you perform git operation.

Python update a key in dict if it doesn't exist

Use dict.setdefault():

>>> d = {1: 'one'}
>>> d.setdefault(1, '1')
'one'
>>> d    # d has not changed because the key already existed
{1: 'one'}
>>> d.setdefault(2, 'two')
'two'
>>> d
{1: 'one', 2: 'two'}

ImportError: No module named tensorflow

I ran into the same issue. I simply updated my command to begin with python3 instead of python and it worked perfectly.

Chrome violation : [Violation] Handler took 83ms of runtime

It seems you have found your solution, but still it will be helpful to others, on this page on point based on Chrome 59.

4.Note the red triangle in the top-right of the Animation Frame Fired event. Whenever you see a red triangle, it's a warning that there may be an issue related to this event.

If you hover on these triangle you can see those are the violation handler errors and as per point 4. yes there is some issue related to that event.

Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Borderless.Colored'

I found it, I was trying to compile my app which is using facebook sdk. I was made that like augst 2016. When I try to open it today i got same error. I had that line in my gradle " compile 'com.facebook.android:facebook-android-sdk:4.+' " and I went https://developers.facebook.com/docs/android/change-log-4x this page and i found the sdk version while i was running this app succesfully and it was 4.14.1 then I changed that line to " compile 'com.facebook.android:facebook-android-sdk:4.14.1' " and it worked.

Property 'value' does not exist on type 'EventTarget'

Here is the simple approach I used:

const element = event.currentTarget as HTMLInputElement
const value = element.value

The error shown by TypeScript compiler is gone and the code works.

Set order of columns in pandas dataframe

Just select the order yourself by typing in the column names. Note the double brackets:

frame = frame[['column I want first', 'column I want second'...etc.]]

How do I specify row heights in CSS Grid layout?

One of the Related posts gave me the (simple) answer.

Apparently the auto value on the grid-template-rows property does exactly what I was looking for.

.grid {
    display:grid;
    grid-template-columns: 1fr 1.5fr 1fr;
    grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
    grid-gap:10px;
    height: calc(100vh - 10px);
}

SELECT list is not in GROUP BY clause and contains nonaggregated column .... incompatible with sql_mode=only_full_group_by

Below method solved my problem:

In ubuntu

Type: sudo vi /etc/mysql/my.cnf

type A to enter insert mode

In the last line paste below two line code:

[mysqld]
sql_mode = STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

Type esc to exit input mode

Type :wq to save and close vim.

Type sudo service mysql restart to restart MySQL.

`col-xs-*` not working in Bootstrap 4

I just wondered, why col-xs-6 did not work for me but then I found the answer in the Bootstrap 4 documentation. The class prefix for extra small devices is now col- while in the previous versions it was col-xs.

https://getbootstrap.com/docs/4.1/layout/grid/#grid-options

Bootstrap 4 dropped all col-xs-* classes, so use col-* instead. For example col-xs-6 replaced by col-6.

python pip on Windows - command 'cl.exe' failed

You need to have cl.exe (the Microsoft C Compiler) installed on your computer and in your PATH. PATH is an environment variable that tells Windows where to find executable files.

First, ensure the C++ build tools for Visual Studio are installed. You can download Build Tools for Visual Studio separately from the Visual Studio downloads page, then choose C++ build tools from the installer. If you already have Visual Studio, you can also install Desktop development with C++ from the Visual Studio Installer which you should have in Start Menu.

Then, instead of the normal Command Prompt or PowerShell, use one of the special command prompts in the Visual Studio folder in Start Menu. For 32-bit Python, you're probably looking for x86 Native Tools Command Prompt. This sets up PATH automatically, so that cl.exe can be found.

`React/RCTBridgeModule.h` file not found

For viewers who got this error after upgrading React Native to 0.40+, you may need to run react-native upgrade on the command line.

How to persist data in a dockerized postgres database using volumes

Strangely enough, the solution ended up being to change

volumes:
  - ./postgres-data:/var/lib/postgresql

to

volumes:
  - ./postgres-data:/var/lib/postgresql/data

Nested routes with react router v4 / v5

I succeeded in defining nested routes by wrapping with Switch and define nested route before than root route.

<BrowserRouter>
  <Switch>
    <Route path="/staffs/:id/edit" component={StaffEdit} />
    <Route path="/staffs/:id" component={StaffShow} />
    <Route path="/staffs" component={StaffIndex} />
  </Switch>
</BrowserRouter>

Reference: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Switch.md

Typescript react - Could not find a declaration file for module ''react-materialize'. 'path/to/module-name.js' implicitly has an any type

I got it after lots of trouble In react app there will be a react-app-env.d.ts file in src folder just declare module there

/// <reference types="react-scripts" />
declare module 'react-color/lib/components/alpha/AlphaPointer'

How to remove components created with Angular-CLI

No As of now you can't do this by any command. You've to remove Manually from app.module.ts and app.routing.module.ts if you're using Angular 5

How to convert FormData (HTML5 object) to JSON

If you need support for serializing nested fields, similar to how PHP handles form fields, you can use the following function

_x000D_
_x000D_
function update(data, keys, value) {_x000D_
  if (keys.length === 0) {_x000D_
    // Leaf node_x000D_
    return value;_x000D_
  }_x000D_
_x000D_
  let key = keys.shift();_x000D_
  if (!key) {_x000D_
    data = data || [];_x000D_
    if (Array.isArray(data)) {_x000D_
      key = data.length;_x000D_
    }_x000D_
  }_x000D_
_x000D_
  // Try converting key to a numeric value_x000D_
  let index = +key;_x000D_
  if (!isNaN(index)) {_x000D_
    // We have a numeric index, make data a numeric array_x000D_
    // This will not work if this is a associative array _x000D_
    // with numeric keys_x000D_
    data = data || [];_x000D_
    key = index;_x000D_
  }_x000D_
  _x000D_
  // If none of the above matched, we have an associative array_x000D_
  data = data || {};_x000D_
_x000D_
  let val = update(data[key], keys, value);_x000D_
  data[key] = val;_x000D_
_x000D_
  return data;_x000D_
}_x000D_
_x000D_
function serializeForm(form) {_x000D_
  return Array.from((new FormData(form)).entries())_x000D_
    .reduce((data, [field, value]) => {_x000D_
      let [_, prefix, keys] = field.match(/^([^\[]+)((?:\[[^\]]*\])*)/);_x000D_
_x000D_
      if (keys) {_x000D_
        keys = Array.from(keys.matchAll(/\[([^\]]*)\]/g), m => m[1]);_x000D_
        value = update(data[prefix], keys, value);_x000D_
      }_x000D_
      data[prefix] = value;_x000D_
      return data;_x000D_
    }, {});_x000D_
}_x000D_
_x000D_
document.getElementById('output').textContent = JSON.stringify(serializeForm(document.getElementById('form')), null, 2);
_x000D_
<form id="form">_x000D_
  <input name="field1" value="Field 1">_x000D_
  <input name="field2[]" value="Field 21">_x000D_
  <input name="field2[]" value="Field 22">_x000D_
  <input name="field3[a]" value="Field 3a">_x000D_
  <input name="field3[b]" value="Field 3b">_x000D_
  <input name="field3[c]" value="Field 3c">_x000D_
  <input name="field4[x][a]" value="Field xa">_x000D_
  <input name="field4[x][b]" value="Field xb">_x000D_
  <input name="field4[x][c]" value="Field xc">_x000D_
  <input name="field4[y][a]" value="Field ya">_x000D_
  <input name="field5[z][0]" value="Field z0">_x000D_
  <input name="field5[z][]" value="Field z1">_x000D_
  <input name="field6.z" value="Field 6Z0">_x000D_
  <input name="field6.z" value="Field 6Z1">_x000D_
</form>_x000D_
_x000D_
<h2>Output</h2>_x000D_
<pre id="output">_x000D_
</pre>
_x000D_
_x000D_
_x000D_

Print Html template in Angular 2 (ng-print in Angular 2)

EDIT: updated the snippets for a more generic approach

Just as an extension to the accepted answer,

For getting the existing styles to preserve the look 'n feel of the targeted component, you can:

  1. make a query to pull the <style> and <link> elements from the top-level document

  2. inject it into the HTML string.

To grab a HTML tag:

private getTagsHtml(tagName: keyof HTMLElementTagNameMap): string
{
    const htmlStr: string[] = [];
    const elements = document.getElementsByTagName(tagName);
    for (let idx = 0; idx < elements.length; idx++)
    {
        htmlStr.push(elements[idx].outerHTML);
    }

    return htmlStr.join('\r\n');
}

Then in the existing snippet:

const printContents = document.getElementById('print-section').innerHTML;
const stylesHtml = this.getTagsHtml('style');
const linksHtml = this.getTagsHtml('link');

const popupWin = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');
popupWin.document.open();
popupWin.document.write(`
    <html>
        <head>
            <title>Print tab</title>
            ${linksHtml}
            ${stylesHtml}
            ^^^^^^^^^^^^^ add them as usual to the head
        </head>
        <body onload="window.print(); window.close()">
            ${printContents}
        </body>
    </html>
    `
);
popupWin.document.close();

Now using existing styles (Angular components create a minted style for itself), as well as existing style frameworks (e.g. Bootstrap, MaterialDesign, Bulma) it should look like a snippet of the existing screen

Uncaught ReferenceError: <function> is not defined at HTMLButtonElement.onclick

Same Problem I had... I was writing all the script in a seperate file and was adding it through tag into the end of the HTML file after body tag. After moving the the tag inside the body tag it works fine. before :

</body>
<script>require('../script/viewLog.js')</script>

after :

<script>require('../script/viewLog.js')</script>
</body>

Could not find a declaration file for module 'module-name'. '/path/to/module-name.js' implicitly has an 'any' type

If you're importing a third-party module 'foo' that doesn't provide any typings, either in the library itself, or in the @types/foo package (generated from the DefinitelyTyped repository), then you can make this error go away by declaring the module in a file with a .d.ts extension. TypeScript looks for .d.ts files in the same places that it will look for normal .ts files: as specified under "files", "include", and "exclude" in the tsconfig.json.

// foo.d.ts
declare module 'foo';

Then when you import foo it'll just be typed as any.


Alternatively, if you want to roll your own typings you can do that too:

// foo.d.ts
declare module 'foo' {
    export function getRandomNumber(): number
} 

Then this will compile correctly:

import { getRandomNumber } from 'foo';
const x = getRandomNumber(); // x is inferred as number

You don't have to provide full typings for the module, just enough for the bits that you're actually using (and want proper typings for), so it's particularly easy to do if you're using a fairly small amount of API.


On the other hand, if you don't care about the typings of external libraries and want all libraries without typings to be imported as any, you can add this to a file with a .d.ts extension:

declare module '*';

The benefit (and downside) of this is that you can import absolutely anything and TS will compile.

Violation Long running JavaScript task took xx ms

Update: Chrome 58+ hid these and other debug messages by default. To display them click the arrow next to 'Info' and select 'Verbose'.

Chrome 57 turned on 'hide violations' by default. To turn them back on you need to enable filters and uncheck the 'hide violations' box.

suddenly it appears when someone else involved in the project

I think it's more likely you updated to Chrome 56. This warning is a wonderful new feature, in my opinion, please only turn it off if you're desperate and your assessor will take marks away from you. The underlying problems are there in the other browsers but the browsers just aren't telling you there's a problem. The Chromium ticket is here but there isn't really any interesting discussion on it.

These messages are warnings instead of errors because it's not really going to cause major problems. It may cause frames to get dropped or otherwise cause a less smooth experience.

They're worth investigating and fixing to improve the quality of your application however. The way to do this is by paying attention to what circumstances the messages appear, and doing performance testing to narrow down where the issue is occurring. The simplest way to start performance testing is to insert some code like this:

function someMethodIThinkMightBeSlow() {
    const startTime = performance.now();

    // Do the normal stuff for this function

    const duration = performance.now() - startTime;
    console.log(`someMethodIThinkMightBeSlow took ${duration}ms`);
}

If you want to get more advanced, you could also use Chrome's profiler, or make use of a benchmarking library like this one.

Once you've found some code that's taking a long time (50ms is Chrome's threshold), you have a couple of options:

  1. Cut out some/all of that task that may be unnecessary
  2. Figure out how to do the same task faster
  3. Divide the code into multiple asynchronous steps

(1) and (2) may be difficult or impossible, but it's sometimes really easy and should be your first attempts. If needed, it should always be possible to do (3). To do this you will use something like:

setTimeout(functionToRunVerySoonButNotNow);

or

// This one is not available natively in IE, but there are polyfills available.
Promise.resolve().then(functionToRunVerySoonButNotNow);

You can read more about the asynchronous nature of JavaScript here.

How to prevent a browser from storing passwords

Thank you for giving a reply to me. I followed the below link

Disable browser 'Save Password' functionality

I resolved the issue by just adding readonly & onfocus="this.removeAttribute('readonly');" attributes besides autocomplete="off" to the inputs as shown below.

<input type="text" name="UserName" autocomplete="off" readonly 
onfocus="this.removeAttribute('readonly');" >

<input type="password" name="Password" autocomplete="off" readonly 
onfocus="this.removeAttribute('readonly');" >

This is working fine for me.

tsconfig.json: Build:No inputs were found in config file

Btw, just had the same problem.

If you had my case, then you probably have the tsconfig.json not in the same directory as the .ts file.

(In my case I stupidly had next to launch.json and tasks.json inside the .vscode folder :P)

Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2

simple solution will be change spring.datasource.url=jdbc:h2:file:~/dasboot in application.properties to new file name like : spring.datasource.url=jdbc:h2:file:~/dasboots

can not find module "@angular/material"

Change to,

import {MaterialModule} from '@angular/material';

DEMO

Does 'position: absolute' conflict with Flexbox?

you have forgotten width of parent

_x000D_
_x000D_
.parent {_x000D_
   display: flex;_x000D_
   justify-content: center;_x000D_
   position: absolute;_x000D_
   width:100%_x000D_
 }
_x000D_
<div class="parent">_x000D_
  <div class="child">text</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to make readonly all inputs in some div in Angular2?

If using reactive forms, you can also disable the entire form or any sub-set of controls in a FormGroup with myFormGroup.disable().

How do I make a https post in Node Js without any third party module?

For example, like this:

const querystring = require('querystring');
const https = require('https');

var postData = querystring.stringify({
    'msg' : 'Hello World!'
});

var options = {
  hostname: 'posttestserver.com',
  port: 443,
  path: '/post.php',
  method: 'POST',
  headers: {
       'Content-Type': 'application/x-www-form-urlencoded',
       'Content-Length': postData.length
     }
};

var req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });
});

req.on('error', (e) => {
  console.error(e);
});

req.write(postData);
req.end();

Angular2: custom pipe could not be found

This didnt worked for me. (Im with Angular 2.1.2). I had NOT to import MainPipeModule in app.module.ts and importe it instead in the module where the component Im using the pipe is imported too.

Looks like if your component is declared and imported in a different module, you need to include your PipeModule in that module too.

Spring security CORS Filter

Ok, after over 2 days of searching we finally fixed the problem. We deleted all our filter and configurations and instead used this 5 lines of code in the application class.

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        final ApplicationContext ctx = SpringApplication.run(Application.class, args);
    }

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("http://localhost:3000");
            }
        };
    }
}

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

On a rather unrelated note: more performance hacks!

  • [the first «conjecture» has been finally debunked by @ShreevatsaR; removed]

  • When traversing the sequence, we can only get 3 possible cases in the 2-neighborhood of the current element N (shown first):

    1. [even] [odd]
    2. [odd] [even]
    3. [even] [even]

    To leap past these 2 elements means to compute (N >> 1) + N + 1, ((N << 1) + N + 1) >> 1 and N >> 2, respectively.

    Let`s prove that for both cases (1) and (2) it is possible to use the first formula, (N >> 1) + N + 1.

    Case (1) is obvious. Case (2) implies (N & 1) == 1, so if we assume (without loss of generality) that N is 2-bit long and its bits are ba from most- to least-significant, then a = 1, and the following holds:

    (N << 1) + N + 1:     (N >> 1) + N + 1:
    
            b10                    b1
             b1                     b
           +  1                   + 1
           ----                   ---
           bBb0                   bBb
    

    where B = !b. Right-shifting the first result gives us exactly what we want.

    Q.E.D.: (N & 1) == 1 ? (N >> 1) + N + 1 == ((N << 1) + N + 1) >> 1.

    As proven, we can traverse the sequence 2 elements at a time, using a single ternary operation. Another 2× time reduction.

The resulting algorithm looks like this:

uint64_t sequence(uint64_t size, uint64_t *path) {
    uint64_t n, i, c, maxi = 0, maxc = 0;

    for (n = i = (size - 1) | 1; i > 2; n = i -= 2) {
        c = 2;
        while ((n = ((n & 3)? (n >> 1) + n + 1 : (n >> 2))) > 2)
            c += 2;
        if (n == 2)
            c++;
        if (c > maxc) {
            maxi = i;
            maxc = c;
        }
    }
    *path = maxc;
    return maxi;
}

int main() {
    uint64_t maxi, maxc;

    maxi = sequence(1000000, &maxc);
    printf("%llu, %llu\n", maxi, maxc);
    return 0;
}

Here we compare n > 2 because the process may stop at 2 instead of 1 if the total length of the sequence is odd.

[EDIT:]

Let`s translate this into assembly!

MOV RCX, 1000000;



DEC RCX;
AND RCX, -2;
XOR RAX, RAX;
MOV RBX, RAX;

@main:
  XOR RSI, RSI;
  LEA RDI, [RCX + 1];

  @loop:
    ADD RSI, 2;
    LEA RDX, [RDI + RDI*2 + 2];
    SHR RDX, 1;
    SHRD RDI, RDI, 2;    ror rdi,2   would do the same thing
    CMOVL RDI, RDX;      Note that SHRD leaves OF = undefined with count>1, and this doesn't work on all CPUs.
    CMOVS RDI, RDX;
    CMP RDI, 2;
  JA @loop;

  LEA RDX, [RSI + 1];
  CMOVE RSI, RDX;

  CMP RAX, RSI;
  CMOVB RAX, RSI;
  CMOVB RBX, RCX;

  SUB RCX, 2;
JA @main;



MOV RDI, RCX;
ADD RCX, 10;
PUSH RDI;
PUSH RCX;

@itoa:
  XOR RDX, RDX;
  DIV RCX;
  ADD RDX, '0';
  PUSH RDX;
  TEST RAX, RAX;
JNE @itoa;

  PUSH RCX;
  LEA RAX, [RBX + 1];
  TEST RBX, RBX;
  MOV RBX, RDI;
JNE @itoa;

POP RCX;
INC RDI;
MOV RDX, RDI;

@outp:
  MOV RSI, RSP;
  MOV RAX, RDI;
  SYSCALL;
  POP RAX;
  TEST RAX, RAX;
JNE @outp;

LEA RAX, [RDI + 59];
DEC RDI;
SYSCALL;

Use these commands to compile:

nasm -f elf64 file.asm
ld -o file file.o

See the C and an improved/bugfixed version of the asm by Peter Cordes on Godbolt. (editor's note: Sorry for putting my stuff in your answer, but my answer hit the 30k char limit from Godbolt links + text!)

ES6 map an array of objects, to return an array of objects with new keys

You just need to wrap object in ()

_x000D_
_x000D_
var arr = [{_x000D_
  id: 1,_x000D_
  name: 'bill'_x000D_
}, {_x000D_
  id: 2,_x000D_
  name: 'ted'_x000D_
}]_x000D_
_x000D_
var result = arr.map(person => ({ value: person.id, text: person.name }));_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_

Getting an object array from an Angular service

Take a look at your code :

 getUsers(): Observable<User[]> {
        return Observable.create(observer => {
            this.http.get('http://users.org').map(response => response.json();
        })
    }

and code from https://angular.io/docs/ts/latest/tutorial/toh-pt6.html (BTW. really good tutorial, you should check it out)

 getHeroes(): Promise<Hero[]> {
    return this.http.get(this.heroesUrl)
               .toPromise()
               .then(response => response.json().data as Hero[])
               .catch(this.handleError);
  }

The HttpService inside Angular2 already returns an observable, sou don't need to wrap another Observable around like you did here:

   return Observable.create(observer => {
        this.http.get('http://users.org').map(response => response.json()

Try to follow the guide in link that I provided. You should be just fine when you study it carefully.

---EDIT----

First of all WHERE you log the this.users variable? JavaScript isn't working that way. Your variable is undefined and it's fine, becuase of the code execution order!

Try to do it like this:

  getUsers(): void {
        this.userService.getUsers()
            .then(users => {
               this.users = users
               console.log('this.users=' + this.users);
            });


    }

See where the console.log(...) is!

Try to resign from toPromise() it's seems to be just for ppl with no RxJs background.

Catch another link: https://scotch.io/tutorials/angular-2-http-requests-with-observables Build your service once again with RxJs observables.

Django model "doesn't declare an explicit app_label"

I got this one when I used ./manage.py shell then I accidentally imported from the root project level directory

# don't do this
from project.someapp.someModule import something_using_a_model
# do this
from someapp.someModule import something_using_a_model

something_using_a_model()

Number prime test in JavaScript

A small suggestion here, why do you want to run the loop for whole n numbers?

If a number is prime it will have 2 factors (1 and number itself). If it's not a prime they will have 1, number itself and more, you need not run the loop till the number, may be you can consider running it till the square root of the number.

You can either do it by euler's prime logic. Check following snippet:

function isPrime(num) {
  var sqrtnum=Math.floor(Math.sqrt(num));
    var prime = num != 1;
    for(var i=2; i<sqrtnum+1; i++) { // sqrtnum+1
        if(num % i == 0) {
            prime = false;
            break;
        }
    }
    return prime;
}

Now the complexity is O(sqrt(n))

For more information Why do we check up to the square root of a prime number to determine if it is prime?

Hope it helps

Check if date is a valid one

console.log(` moment('2019-09-01', 'YYYY-MM-DD').isValid()?  ` +moment('2019-09-01', 'YYYY-MM-DD').isValid())
console.log(` moment('2019-22-01', 'YYYY-DD-MM').isValid()?  ` +moment('2019-22-01', 'YYYY-DD-MM').isValid())
console.log(` moment('2019-22-22', 'YYYY-DD-MM').isValid()?  ` +moment('2019-22-22', 'YYYY-DD-MM').isValid())
console.log(` moment('undefined', 'YYYY-DD-MM').isValid()?  ` +moment('undefined', 'YYYY-DD-MM').isValid())

 moment('2019-09-01', 'YYYY-MM-DD').isValid()?  true
 moment('2019-22-01', 'YYYY-DD-MM').isValid()?  true
 moment('2019-22-22', 'YYYY-DD-MM').isValid()?  false
 moment('undefined', 'YYYY-DD-MM').isValid()?  false

moment.js get current time in milliseconds?

From the docs: http://momentjs.com/docs/#/parsing/unix-timestamp-milliseconds/

So use either of these:


moment(...).valueOf()

to parse a preexisting date and convert the representation to a unix timestamp


moment().valueOf()

for the current unix timestamp

How to get height and width of device display in angular2 using typescript?

Keep in mind if you are wanting to test this component you will want to inject the window. Use the @Inject() function to inject the window object by naming it using a string token like detailed in this duplicate

Matplotlib - How to plot a high resolution graph?

You can use savefig() to export to an image file:

plt.savefig('filename.png')

In addition, you can specify the dpi argument to some scalar value, for example:

plt.savefig('filename.png', dpi=300)

Ansible: get current target host's IP address

You can use in your template.j2 {{ ansible_eth0.ipv4.address }} the same way you use {{inventory_hostname}}.

ps: Please refer to the following blogpost to have more information about HOW TO COLLECT INFORMATION ABOUT REMOTE HOSTS WITH ANSIBLE GATHERS FACTS .

'hoping it’ll help someone one day ?

mysqli_connect(): (HY000/2002): No connection could be made because the target machine actively refused it

It is just a matter of changing the port user by mysql:3308 to 3306

Just right click on wamp-> select tools

under Port Used By mysql:3308 clcik on "use a port other than 3308

In the text port text box appear : type 3306 and save. Wait until the wampserver restarts and get green.

Now run your PHP code, It will work. That's it - Good Luck

How to beautifully update a JPA entity in Spring Data?

I have encountered this issue!
Luckily, I determine 2 ways and understand some things but the rest is not clear.
Hope someone discuss or support if you know.

  1. Use RepositoryExtendJPA.save(entity).
    Example:
    List<Person> person = this.PersonRepository.findById(0) person.setName("Neo"); This.PersonReository.save(person);
    this block code updated new name for record which has id = 0;
  2. Use @Transactional from javax or spring framework.
    Let put @Transactional upon your class or specified function, both are ok.
    I read at somewhere that this annotation do a "commit" action at the end your function flow. So, every things you modified at entity would be updated to database.

Getting a UnhandledPromiseRejectionWarning when testing using mocha/chai

I faced this issue:

(node:1131004) UnhandledPromiseRejectionWarning: Unhandled promise rejection (re jection id: 1): TypeError: res.json is not a function (node:1131004) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.j s process with a non-zero exit code.

It was my mistake, I was replacing res object in then(function(res), so changed res to result and now it is working.

Wrong

module.exports.update = function(req, res){
        return Services.User.update(req.body)
                .then(function(res){//issue was here, res overwrite
                    return res.json(res);
                }, function(error){
                    return res.json({error:error.message});
                }).catch(function () {
                   console.log("Promise Rejected");
              });

Correction

module.exports.update = function(req, res){
        return Services.User.update(req.body)
                .then(function(result){//res replaced with result
                    return res.json(result);
                }, function(error){
                    return res.json({error:error.message});
                }).catch(function () {
                   console.log("Promise Rejected");
              });

Service code:

function update(data){
   var id = new require('mongodb').ObjectID(data._id);
        userData = {
                    name:data.name,
                    email:data.email,
                    phone: data.phone
                };
 return collection.findAndModify(
          {_id:id}, // query
          [['_id','asc']],  // sort order
          {$set: userData}, // replacement
          { "new": true }
          ).then(function(doc) {
                if(!doc)
                    throw new Error('Record not updated.');
                return doc.value;   
          });
    }

module.exports = {
        update:update
}

PySpark 2.0 The size or shape of a DataFrame

print((df.count(), len(df.columns)))

is easier for smaller datasets.

However if the dataset is huge, an alternative approach would be to use pandas and arrows to convert the dataframe to pandas df and call shape

spark.conf.set("spark.sql.execution.arrow.enabled", "true")
spark.conf.set("spark.sql.crossJoin.enabled", "true")
print(df.toPandas().shape)

How to set image width to be 100% and height to be auto in react native?

Right click on you image to get resolution. In my case 1233 x 882

const { width } = Dimensions.get('window');

const ratio = 882 / 1233;

    const style = {
      width,
      height: width * ratio
    }

<Image source={image} style={style} resizeMode="contain" />

That all

Angular 2 Scroll to top on Route Change

The main idea behind this code is to keep all visited urls along with respective scrollY data in an array. Every time a user abandons a page (NavigationStart) this array is updated. Every time a user enters a new page (NavigationEnd), we decide to restore Y position or don't depending on how do we get to this page. If a refernce on some page was used we scroll to 0. If browser back/forward features were used we scroll to Y saved in our array. Sorry for my English :)

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Location, PopStateEvent } from '@angular/common';
import { Router, Route, RouterLink, NavigationStart, NavigationEnd, 
    RouterEvent } from '@angular/router';
import { Subscription } from 'rxjs/Subscription';

@Component({
  selector: 'my-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {

  private _subscription: Subscription;
  private _scrollHistory: { url: string, y: number }[] = [];
  private _useHistory = false;

  constructor(
    private _router: Router,
    private _location: Location) {
  }

  public ngOnInit() {

    this._subscription = this._router.events.subscribe((event: any) => 
    {
      if (event instanceof NavigationStart) {
        const currentUrl = (this._location.path() !== '') 
           this._location.path() : '/';
        const item = this._scrollHistory.find(x => x.url === currentUrl);
        if (item) {
          item.y = window.scrollY;
        } else {
          this._scrollHistory.push({ url: currentUrl, y: window.scrollY });
        }
        return;
      }
      if (event instanceof NavigationEnd) {
        if (this._useHistory) {
          this._useHistory = false;
          window.scrollTo(0, this._scrollHistory.find(x => x.url === 
          event.url).y);
        } else {
          window.scrollTo(0, 0);
        }
      }
    });

    this._subscription.add(this._location.subscribe((event: PopStateEvent) 
      => { this._useHistory = true;
    }));
  }

  public ngOnDestroy(): void {
    this._subscription.unsubscribe();
  }
}

Python/Json:Expecting property name enclosed in double quotes

JSON strings must use double quotes. The JSON python library enforces this so you are unable to load your string. Your data needs to look like this:

{"http://example.org/about": {"http://purl.org/dc/terms/title": [{"type": "literal", "value": "Anna's Homepage"}]}}

If that's not something you can do, you could use ast.literal_eval() instead of json.loads()

Remove a modified file from pull request

Removing a file from pull request but not from your local repository.

  1. Go to your branch from where you created the request use the following commands

git checkout -- c:\temp..... next git checkout origin/master -- c:\temp... u replace origin/master with any other branch. Next git commit -m c:\temp..... Next git push origin

Note : no single quote or double quotes for the filepath

How to import component into another root component in Angular 2

For Angular RC5 and RC6 you have to declare component in the module metadata decorator's declarations key, so add CoursesComponent in your main module declarations as below and remove directives from AppComponent metadata.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { CoursesComponent } from './courses.component';

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ AppComponent, CoursesComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

How to fetch JSON file in Angular 2

I needed to load the settings file synchronously, and this was my solution:

export function InitConfig(config: AppConfig) { return () => config.load(); }

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

@Injectable()
export class AppConfig {
    Settings: ISettings;

    constructor() { }

    load() {
        return new Promise((resolve) => {
            this.Settings = this.httpGet('assets/clientsettings.json');
            resolve(true);
        });
    }

    httpGet(theUrl): ISettings {
        const xmlHttp = new XMLHttpRequest();
        xmlHttp.open( 'GET', theUrl, false ); // false for synchronous request
        xmlHttp.send( null );
        return JSON.parse(xmlHttp.responseText);
    }
}

This is then provided as a app_initializer which is loaded before the rest of the application.

app.module.ts

{
      provide: APP_INITIALIZER,
      useFactory: InitConfig,
      deps: [AppConfig],
      multi: true
    },

DataTables: Cannot read property style of undefined

You said any suggestions wold be helpful, so currently I resolved my DataTables "cannot read property 'style' of undefined" problem but my problem was basically using wrong indexes at data table initiation phase's columnDefs section. I got 9 columns and the indexes are 0, 1, 2, .. , 8 but I was using indexes for 9 and 10 so after fixing the wrong index issue the fault has disappeared. I hope this helps.

In short, you got to watch your columns amount and indexes if consistent everywhere.

Buggy Code:

    jQuery('#table').DataTable({
        "ajax": {
            url: "something_url",
            type: 'POST'
        },
        "processing": true,
        "serverSide": true,
        "bPaginate": true,
        "sPaginationType": "full_numbers",
        "columns": [
            { "data": "cl1" },
            { "data": "cl2" },
            { "data": "cl3" },
            { "data": "cl4" },
            { "data": "cl5" },
            { "data": "cl6" },
            { "data": "cl7" },
            { "data": "cl8" },
            { "data": "cl9" }
        ],
        columnDefs: [
            { orderable: false, targets: [ 7, 9, 10 ] } //This part was wrong
        ]
    });

Fixed Code:

    jQuery('#table').DataTable({
        "ajax": {
            url: "something_url",
            type: 'POST'
        },
        "processing": true,
        "serverSide": true,
        "bPaginate": true,
        "sPaginationType": "full_numbers",
        "columns": [
            { "data": "cl1" },
            { "data": "cl2" },
            { "data": "cl3" },
            { "data": "cl4" },
            { "data": "cl5" },
            { "data": "cl6" },
            { "data": "cl7" },
            { "data": "cl8" },
            { "data": "cl9" }
        ],
        columnDefs: [
            { orderable: false, targets: [ 5, 7, 8 ] } //This part is ok now
        ]
    });

How to reset the use/password of jenkins on windows?

I created a new user with "admin" and new password on the installation steps. But after sometime, i wanted to sign in again and that password was showing incorrect, so i used the initial password again to login.

The initial password can be found in the below location:-

C:\Program Files(x86)\Jenkins\secrets\initialAdminPassword

try this method

Convert Promise to Observable

try this:

import 'rxjs/add/observable/fromPromise';
import { Observable } from "rxjs/Observable";

const subscription = Observable.fromPromise(
    firebase.auth().createUserWithEmailAndPassword(email, password)
);
subscription.subscribe(firebaseUser => /* Do anything with data received */,
                       error => /* Handle error here */);

you can find complete reference to fromPromise operator here.

How to enable directory listing in apache web server

I had to disable selinux to make this work. Note. The system needs to be rebooted for selinux to take effect.

How to register multiple implementations of the same interface in Asp.Net Core?

I created my own extension over IServiceCollection used WithName extension:

public static IServiceCollection AddScopedWithName<TService, TImplementation>(this IServiceCollection services, string serviceName)
        where TService : class
        where TImplementation : class, TService
    {
        Type serviceType = typeof(TService);
        Type implementationServiceType = typeof(TImplementation);
        ServiceCollectionTypeMapper.Instance.AddDefinition(serviceType.Name, serviceName, implementationServiceType.AssemblyQualifiedName);
        services.AddScoped<TImplementation>();
        return services;
    }

ServiceCollectionTypeMapper is a singleton instance that maps IService > NameOfService > Implementation where an interface could have many implementations with different names, this allows to register types than we can resolve when wee need and is a different approach than resolve multiple services to select what we want.

 /// <summary>
/// Allows to set the service register mapping.
/// </summary>
public class ServiceCollectionTypeMapper
{
    private ServiceCollectionTypeMapper()
    {
        this.ServiceRegister = new Dictionary<string, Dictionary<string, string>>();
    }

    /// <summary>
    /// Gets the instance of mapper.
    /// </summary>
    public static ServiceCollectionTypeMapper Instance { get; } = new ServiceCollectionTypeMapper();

    private Dictionary<string, Dictionary<string, string>> ServiceRegister { get; set; }

    /// <summary>
    /// Adds new service definition.
    /// </summary>
    /// <param name="typeName">The name of the TService.</param>
    /// <param name="serviceName">The TImplementation name.</param>
    /// <param name="namespaceFullName">The TImplementation AssemblyQualifiedName.</param>
    public void AddDefinition(string typeName, string serviceName, string namespaceFullName)
    {
        if (this.ServiceRegister.TryGetValue(typeName, out Dictionary<string, string> services))
        {
            if (services.TryGetValue(serviceName, out _))
            {
                throw new InvalidOperationException($"Exists an implementation with the same name [{serviceName}] to the type [{typeName}].");
            }
            else
            {
                services.Add(serviceName, namespaceFullName);
            }
        }
        else
        {
            Dictionary<string, string> serviceCollection = new Dictionary<string, string>
            {
                { serviceName, namespaceFullName },
            };
            this.ServiceRegister.Add(typeName, serviceCollection);
        }
    }

    /// <summary>
    /// Get AssemblyQualifiedName of implementation.
    /// </summary>
    /// <typeparam name="TService">The type of the service implementation.</typeparam>
    /// <param name="serviceName">The name of the service.</param>
    /// <returns>The AssemblyQualifiedName of the inplementation service.</returns>
    public string GetService<TService>(string serviceName)
    {
        Type serviceType = typeof(TService);

        if (this.ServiceRegister.TryGetValue(serviceType.Name, out Dictionary<string, string> services))
        {
            if (services.TryGetValue(serviceName, out string serviceImplementation))
            {
                return serviceImplementation;
            }
            else
            {
                return null;
            }
        }
        else
        {
            return null;
        }
    }

To register a new service:

services.AddScopedWithName<IService, MyService>("Name");

To resolve service we need an extension over IServiceProvider like this.

/// <summary>
    /// Gets the implementation of service by name.
    /// </summary>
    /// <typeparam name="T">The type of service.</typeparam>
    /// <param name="serviceProvider">The service provider.</param>
    /// <param name="serviceName">The service name.</param>
    /// <returns>The implementation of service.</returns>
    public static T GetService<T>(this IServiceProvider serviceProvider, string serviceName)
    {
        string fullnameImplementation = ServiceCollectionTypeMapper.Instance.GetService<T>(serviceName);
        if (fullnameImplementation == null)
        {
            throw new InvalidOperationException($"Unable to resolve service of type [{typeof(T)}] with name [{serviceName}]");
        }
        else
        {
            return (T)serviceProvider.GetService(Type.GetType(fullnameImplementation));
        }
    }

When resolve:

serviceProvider.GetService<IWithdrawalHandler>(serviceName);

Remember that serviceProvider can be injected within a constructor in our application as IServiceProvider.

I hope this helps.

You have to be inside an angular-cli project in order to use the build command after reinstall of angular-cli

Same as John Pankowicz answer, but in my case I had to run

npm install -g @angular/cli@latest

for the versions to match.

ngModel cannot be used to register form controls with a parent formGroup directive

when you write formcontrolname Angular 2 do not accept. You have to write formControlName . it is about uppercase second words.

<input type="number" [(ngModel)]="myObject.name" formcontrolname="nameFormControl"/>

if the error still conitnue try to set form control for all of object(myObject) field.

between start <form> </form> for example: <form [formGroup]="myForm" (ngSubmit)="submitForm(myForm.value)"> set form control for all input field </form>.

TypeScript - Append HTML to container element in Angular 2

You could do something like this:

htmlComponent.ts

htmlVariable: string = "<b>Some html.</b>"; //this is html in TypeScript code that you need to display

htmlComponent.html

<div [innerHtml]="htmlVariable"></div> //this is how you display html code from TypeScript in your html

path.join vs path.resolve with __dirname

Yes there is a difference between the functions but the way you are using them in this case will result in the same outcome.

path.join returns a normalized path by merging two paths together. It can return an absolute path, but it doesn't necessarily always do so.

For instance:

path.join('app/libs/oauth', '/../ssl')

resolves to app/libs/ssl

path.resolve, on the other hand, will resolve to an absolute path.

For instance, when you run:

path.resolve('bar', '/foo');

The path returned will be /foo since that is the first absolute path that can be constructed.

However, if you run:

path.resolve('/bar/bae', '/foo', 'test');

The path returned will be /foo/test again because that is the first absolute path that can be formed from right to left.

If you don't provide a path that specifies the root directory then the paths given to the resolve function are appended to the current working directory. So if your working directory was /home/mark/project/:

path.resolve('test', 'directory', '../back');

resolves to

/home/mark/project/test/back

Using __dirname is the absolute path to the directory containing the source file. When you use path.resolve or path.join they will return the same result if you give the same path following __dirname. In such cases it's really just a matter of preference.

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

<create-report-card-form [currentReportCardCount]="providerData.reportCards.length" ...
                         ^^^^^^^^^^^^^^^^^^^^^^^^

In your HomeComponent template, you are trying to bind to an input on the CreateReportCardForm component that doesn't exist.

In CreateReportCardForm, these are your only three inputs:

@Input() public reportCardDataSourcesItems: SelectItem[];
@Input() public reportCardYearItems: SelectItem[];
@Input() errorMessages: Message[];

Add one for currentReportCardCount and you should be good to go.

Saving a high resolution image in R

You can do the following. Add your ggplot code after the first line of code and end with dev.off().

tiff("test.tiff", units="in", width=5, height=5, res=300)
# insert ggplot code
dev.off()

res=300 specifies that you need a figure with a resolution of 300 dpi. The figure file named 'test.tiff' is saved in your working directory.

Change width and height in the code above depending on the desired output.

Note that this also works for other R plots including plot, image, and pheatmap.

Other file formats

In addition to TIFF, you can easily use other image file formats including JPEG, BMP, and PNG. Some of these formats require less memory for saving.

DELETE_FAILED_INTERNAL_ERROR Error while Installing APK

Different solutions for the same problem:

1. uncheck the Instant Run

Settings > Build, Execution, Deployment > Instant Run.

2. Restart Android Studio

Click on File> invalidate Caches/Restart, then click on Invalidate and Restart button from the pop up window.

3. Check Device's memory

Sometimes your device don't have enough space to install new applications, in that case android studio through this error.

4. Check manifest for Activities Declaration

Make sure that your manifest.java have declared all of the used activities properly.

Hope it would help :)

How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

I have a simple example to show how to do angular 2 rc6 dynamic component.

Say, you have a dynamic html template = template1 and want to dynamic load, firstly wrap into component

@Component({template: template1})
class DynamicComponent {}

here template1 as html, may be contains ng2 component

From rc6, have to have @NgModule wrap this component. @NgModule, just like module in anglarJS 1, it decouple different part of ng2 application, so:

@Component({
  template: template1,

})
class DynamicComponent {

}
@NgModule({
  imports: [BrowserModule,RouterModule],
  declarations: [DynamicComponent]
})
class DynamicModule { }

(Here import RouterModule as in my example there is some route components in my html as you can see later on)

Now you can compile DynamicModule as: this.compiler.compileModuleAndAllComponentsAsync(DynamicModule).then( factory => factory.componentFactories.find(x => x.componentType === DynamicComponent))

And we need put above in app.moudule.ts to load it, please see my app.moudle.ts. For more and full details check: https://github.com/Longfld/DynamicalRouter/blob/master/app/MyRouterLink.ts and app.moudle.ts

and see demo: http://plnkr.co/edit/1fdAYP5PAbiHdJfTKgWo?p=preview

"Uncaught TypeError: a.indexOf is not a function" error when opening new foundation project

This error might be caused by the jQuery event-aliases like .load(), .unload() or .error() that all are deprecated since jQuery 1.8. Lookup for these aliases in your code and replace them with the .on() method instead. For example, replace the following deprecated excerpt:

$(window).load(function(){...});

with the following:

$(window).on('load', function(){ ...});

How to pass multiple parameter to @Directives (@Components) in Angular with TypeScript?

Similar to the above solutions I used @Input() in a directive and able to pass multiple arrays of values in the directive.

selector: '[selectorHere]',

@Input() options: any = {};

Input.html

<input selectorHere [options]="selectorArray" />

Array from TS file

selectorArray= {
  align: 'left',
  prefix: '$',
  thousands: ',',
  decimal: '.',
  precision: 2
};

webpack command not working

I had to reinstall webpack to get it working with my local version of webpack, e.g:

$ npm uninstall webpack
$ npm i -D webpack

how to make UITextView height dynamic according to text length?

Give this a try:

CGRect frame = self.textView.frame;
frame.size.height = self.textView.contentSize.height;
self.textView.frame = frame;

Edit- Here's the Swift:

var frame = self.textView.frame
frame.size.height = self.textView.contentSize.height
self.textView.frame = frame

why $(window).load() is not working in jQuery?

<script type="text/javascript">
   $(window).ready(function () {
      alert("Window Loaded");
   });
</script>

How to set Spring profile from system variable?

If i run the command line : java -Dspring.profiles.active=development -jar yourApplication.jar from my webapplication directory it states that the path is incorrect. So i just defined the profile in manualy in the application.properties file like this :

spring.profiles.active=mysql 

or

spring.profiles.active=postgres

or

spring.profiles.active=mongodb

iOS 10 - Changes in asking permissions of Camera, microphone and Photo Library causing application to crash

Please find below codes for ios 10 request permission sample for info.plist.
You can modify for your custom message.

    <key>NSCameraUsageDescription</key>
    <string>${PRODUCT_NAME} Camera Usage</string>

    <key>NSBluetoothPeripheralUsageDescription</key>
    <string>${PRODUCT_NAME} BluetoothPeripheral</string>

    <key>NSCalendarsUsageDescription</key>
    <string>${PRODUCT_NAME} Calendar Usage</string>

    <key>NSContactsUsageDescription</key>
    <string>${PRODUCT_NAME} Contact fetch</string>

    <key>NSHealthShareUsageDescription</key>
    <string>${PRODUCT_NAME} Health Description</string>

    <key>NSHealthUpdateUsageDescription</key>
    <string>${PRODUCT_NAME} Health Updates</string>

    <key>NSHomeKitUsageDescription</key>
    <string>${PRODUCT_NAME} HomeKit Usage</string>

    <key>NSLocationAlwaysUsageDescription</key>
    <string>${PRODUCT_NAME} Use location always</string>

    <key>NSLocationUsageDescription</key>
    <string>${PRODUCT_NAME} Location Updates</string>

    <key>NSLocationWhenInUseUsageDescription</key>
    <string>${PRODUCT_NAME} WhenInUse Location</string>

    <key>NSAppleMusicUsageDescription</key>
    <string>${PRODUCT_NAME} Music Usage</string>

    <key>NSMicrophoneUsageDescription</key>
    <string>${PRODUCT_NAME} Microphone Usage</string>

    <key>NSMotionUsageDescription</key>
    <string>${PRODUCT_NAME} Motion Usage</string>

    <key>kTCCServiceMediaLibrary</key>
    <string>${PRODUCT_NAME} MediaLibrary Usage</string>

    <key>NSPhotoLibraryUsageDescription</key>
    <string>${PRODUCT_NAME} PhotoLibrary Usage</string>

    <key>NSRemindersUsageDescription</key>
    <string>${PRODUCT_NAME} Reminder Usage</string>

    <key>NSSiriUsageDescription</key>
    <string>${PRODUCT_NAME} Siri Usage</string>

    <key>NSSpeechRecognitionUsageDescription</key>
    <string>${PRODUCT_NAME} Speech Recognition Usage</string>

    <key>NSVideoSubscriberAccountUsageDescription</key>
    <string>${PRODUCT_NAME} Video Subscribe Usage</string>

iOS 11 and plus, If you want to add photo/image to your library then you must add this key

    <key>NSPhotoLibraryAddUsageDescription</key>
    <string>${PRODUCT_NAME} library Usage</string>

"Please provide a valid cache path" error in laravel

So apparently what happened was when I was duplicating my project the framework folder inside my storage folder was not copied to the new directory, this cause my error.

Session 'app' error while installing APK

None of the above worked for me, the simplest solution was to go to

File > invalidate caches/restart > invalidate and restart

enter image description here

"OverflowError: Python int too large to convert to C long" on windows but not mac

You'll get that error once your numbers are greater than sys.maxsize:

>>> p = [sys.maxsize]
>>> preds[0] = p
>>> p = [sys.maxsize+1]
>>> preds[0] = p
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: Python int too large to convert to C long

You can confirm this by checking:

>>> import sys
>>> sys.maxsize
2147483647

To take numbers with larger precision, don't pass an int type which uses a bounded C integer behind the scenes. Use the default float:

>>> preds = np.zeros((1, 3))

How to split data into 3 sets (train, validation and test)?

Considering that df id your original dataframe:

1 - First you split data between Train and Test (10%):

my_test_size = 0.10

X_train_, X_test, y_train_, y_test = train_test_split(
    df.index.values,
    df.label.values,
    test_size=my_test_size,
    random_state=42,
    stratify=df.label.values,    
)

2 - Then you split the train set between train and validation (20%):

my_val_size = 0.20

X_train, X_val, y_train, y_val = train_test_split(
    df.loc[X_train_].index.values,
    df.loc[X_train_].label.values,
    test_size=my_val_size,
    random_state=42,
    stratify=df.loc[X_train_].label.values,  
)

3 - Then, you slice the original dataframe according to the indices generated in the steps above:

# data_type is not necessary. 
df['data_type'] = ['not_set']*df.shape[0]
df.loc[X_train, 'data_type'] = 'train'
df.loc[X_val, 'data_type'] = 'val'
df.loc[X_test, 'data_type'] = 'test'

The result is going to be like this:

enter image description here

Note: This soluctions uses the workaround mentioned in the question.

How do you send a Firebase Notification to all devices via CURL?

The most easiest way I came up with to send the push notification to all the devices is to subscribe them to a topic "all" and then send notification to this topic. Copy this in your main activity

FirebaseMessaging.getInstance().subscribeToTopic("all");

Now send the request as

{
   "to":"/topics/all",
   "data":
   {
      "title":"Your title",
      "message":"Your message"
      "image-url":"your_image_url"
   }
}

This might be inefficient or non-standard way, but as I mentioned above it's the easiest. Please do post if you have any better way to send a push notification to all the devices.

You can follow this tutorial if you're new to sending push notifications using Firebase Cloud Messaging Tutorial - Push Notifications using FCM


To send a message to a combination of topics, specify a condition, which is a boolean expression that specifies the target topics. For example, the following condition will send messages to devices that are subscribed to TopicA and either TopicB or TopicC:

{
   "data":
   {
      "title": "Your title",
      "message": "Your message"
      "image-url": "your_image_url"
   },
   "condition": "'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)"
}

Read more about conditions and topics here on FCM documentation

Visual Studio Code Automatic Imports

I got this working by installing the various plugins below.

Most of the time things just import by themselves as soon as I type the class name. Alternatively, a lightbulb appears that you can click on. Or you can push F1, and type "import..." and there are various options there too. I kinda use all of them. Also F1 Implement for implementing an interface is helpful, but doesn't always work.

List of Plugins

Screenshot of Extensions

screenshot of extensions
*click for full resolution

The term "Add-Migration" is not recognized

It's so simple.

Just install Microsoft.EntityFrameworkCore.Tools package from nuget:

Install-Package Microsoft.EntityFrameworkCore.Tools -Version 3.1.5

You can also use this link to install the latest version: Nuget package link

.NET CLI command:

dotnet add package Microsoft.EntityFrameworkCore.Tools

Data-frame Object has no Attribute

I'd like to make it simple for you. the reason of " 'DataFrame' object has no attribute 'Number'/'Close'/or any col name " is because you are looking at the col name and it seems to be "Number" but in reality it is " Number" or "Number " , that extra space is because in the excel sheet col name is written in that format. You can change it in excel or you can write data.columns = data.columns.str.strip() / df.columns = df.columns.str.strip() but the chances are that it will throw the same error in particular in some cases after the query. changing name in excel sheet will work definitely.

Automatically accept all SDK licences

this solved my error

echo yes | $ANDROID_HOME/tools/bin/sdkmanager "build-tools;25.0.2"

Pass multiple parameters to rest API - Spring

Multiple parameters can be given like below,

    @RequestMapping(value = "/mno/{objectKey}", method = RequestMethod.GET, produces = "application/json")
    public List<String> getBook(HttpServletRequest httpServletRequest, @PathVariable(name = "objectKey") String objectKey
      , @RequestParam(value = "id", defaultValue = "false")String id,@RequestParam(value = "name", defaultValue = "false") String name) throws Exception {
               //logic
}

Angular 2 TypeScript how to find element in Array

Assume I have below array:

Skins[
    {Id: 1, Name: "oily skin"}, 
    {Id: 2, Name: "dry skin"}
];

If we want to get item with Id = 1 and Name = "oily skin", We'll try as below:

var skinName = skins.find(x=>x.Id == "1").Name;

The result will return the skinName is "Oily skin".

enter image description here

CGRectMake, CGPointMake, CGSizeMake, CGRectZero, CGPointZero is unavailable in Swift

Try the following:

var myToolBar = UIToolbar.init(frame: CGRect.init(x: 0, y: 0, width: 320, height: 44))

This is for the swift's latest version

Getting "project" nuget configuration is invalid error

NOTE: This is mentioned in the question but restarting Visual Studio fixes the issue in most cases.

Updating Visual Studio to 'Update 2' got it working again.

Tools -> Extensions and Updates ->Visual Studio Update 2

As mentioned in the question and the link i posted therein, I'd already updated NuGet Package Manager to 3.4.4 prior to this and restarted to no avail, so I don't know if the combination of both these actions worked.

How to use npm with ASP.NET Core

Shawn Wildermuth has a nice guide here: https://wildermuth.com/2017/11/19/ASP-NET-Core-2-0-and-the-End-of-Bower

The article links to the gulpfile on GitHub where he's implemented the strategy in the article. You could just copy and paste most of the gulpfile contents into yours, but be sure to add the appropriate packages in package.json under devDependencies: gulp gulp-uglify gulp-concat rimraf merge-stream

Append integer to beginning of list in Python

Another way of doing the same,

list[0:0] = [a]

How to close existing connections to a DB

in restore wizard click "close existing connections to destination database"

in Detach Database wizard click "Drop connection" item.

How do you transfer or export SQL Server 2005 data to Excel

If you are looking for ad-hoc items rather than something that you would put into SSIS. From within SSMS simply highlight the results grid, copy, then paste into excel, it isn't elegant, but works. Then you can save as native .xls rather than .csv

Groovy executing shell commands

To add one more important information to above provided answers -

For a process

def proc = command.execute();

always try to use

def outputStream = new StringBuffer();
proc.waitForProcessOutput(outputStream, System.err)
//proc.waitForProcessOutput(System.out, System.err)

rather than

def output = proc.in.text;

to capture the outputs after executing commands in groovy as the latter is a blocking call (SO question for reason).

How to make a stable two column layout in HTML/CSS

Here you go:

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
  <title>Cols</title>_x000D_
  <style>_x000D_
    #left {_x000D_
      width: 200px;_x000D_
      float: left;_x000D_
    }_x000D_
    #right {_x000D_
      margin-left: 200px;_x000D_
      /* Change this to whatever the width of your left column is*/_x000D_
    }_x000D_
    .clear {_x000D_
      clear: both;_x000D_
    }_x000D_
  </style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div id="container">_x000D_
    <div id="left">_x000D_
      Hello_x000D_
    </div>_x000D_
    <div id="right">_x000D_
      <div style="background-color: red; height: 10px;">Hello</div>_x000D_
    </div>_x000D_
    <div class="clear"></div>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

See it in action here: http://jsfiddle.net/FVLMX/

Pandas : compute mean or std (standard deviation) over entire dataframe

You could convert the dataframe to be a single column with stack (this changes the shape from 5x3 to 15x1) and then take the standard deviation:

df.stack().std()         # pandas default degrees of freedom is one

Alternatively, you can use values to convert from a pandas dataframe to a numpy array before taking the standard deviation:

df.values.std(ddof=1)    # numpy default degrees of freedom is zero

Unlike pandas, numpy will give the standard deviation of the entire array by default, so there is no need to reshape before taking the standard deviation.

A couple of additional notes:

  • The numpy approach here is a bit faster than the pandas one, which is generally true when you have the option to accomplish the same thing with either numpy or pandas. The speed difference will depend on the size of your data, but numpy was roughly 10x faster when I tested a few different sized dataframes on my laptop (numpy version 1.15.4 and pandas version 0.23.4).

  • The numpy and pandas approaches here will not give exactly the same answers, but will be extremely close (identical at several digits of precision). The discrepancy is due to slight differences in implementation behind the scenes that affect how the floating point values get rounded.

Owl Carousel, making custom navigation

In owl carousel 2 you can use font-awesome icons or any custom images in navText option like this:

$(".category-wrapper").owlCarousel({
     items: 4,
     loop: true,
     margin: 30,
     nav: true,
     smartSpeed: 900,
     navText: ["<i class='fa fa-chevron-left'></i>","<i class='fa fa-chevron-right'></i>"]
});

Post to another page within a PHP script

For PHP processing, look into cURL. It will allow you to call pages on your back end and retrieve data from it. Basically you would do something like this:

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_URL,$fetch_url);
curl_setopt ($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt ($ch,CURLOPT_USERAGENT, $user_agent;
curl_setopt ($ch,CURLOPT_CONNECTTIMEOUT,60);
$response = curl_exec ( $ch );
curl_close($ch);

You can also look into the PHP HTTP Extension.

How to use the switch statement in R functions?

Well, switch probably wasn't really meant to work like this, but you can:

AA = 'foo'
switch(AA, 
foo={
  # case 'foo' here...
  print('foo')
},
bar={
  # case 'bar' here...
  print('bar')    
},
{
   print('default')
}
)

...each case is an expression - usually just a simple thing, but here I use a curly-block so that you can stuff whatever code you want in there...

SQL Server Installation - What is the Installation Media Folder?

For me the Issue was I didn't run the setup as Administrator, after running the setup as administrator the message go away and I was prompted to install and continue process.

Checking if a textbox is empty in Javascript

function valid(id)
    {
        var textVal=document.getElementById(id).value;
        if (!textVal.match("Tryit") 
        {
            alert("Field says Tryit");
            return false;
        } 
        else 
        {
            return true;
        }
     }

Use this for expressing things

Processing $http response in service

When binding the UI to your array you'll want to make sure you update that same array directly by setting the length to 0 and pushing the data into the array.

Instead of this (which set a different array reference to data which your UI won't know about):

 myService.async = function() {
    $http.get('test.json')
    .success(function (d) {
      data = d;
    });
  };

try this:

 myService.async = function() {
    $http.get('test.json')
    .success(function (d) {
      data.length = 0;
      for(var i = 0; i < d.length; i++){
        data.push(d[i]);
      }
    });
  };

Here is a fiddle that shows the difference between setting a new array vs emptying and adding to an existing one. I couldn't get your plnkr working but hopefully this works for you!

How To Inject AuthenticationManager using Java Configuration in a Custom Filter

Override method authenticationManagerBean in WebSecurityConfigurerAdapter to expose the AuthenticationManager built using configure(AuthenticationManagerBuilder) as a Spring bean:

For example:

   @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
   @Override
   public AuthenticationManager authenticationManagerBean() throws Exception {
       return super.authenticationManagerBean();
   }

Tkinter: How to use threads to preventing main event loop from "freezing"

I will submit the basis for an alternate solution. It is not specific to a Tk progress bar per se, but it can certainly be implemented very easily for that.

Here are some classes that allow you to run other tasks in the background of Tk, update the Tk controls when desired, and not lock up the gui!

Here's class TkRepeatingTask and BackgroundTask:

import threading

class TkRepeatingTask():

    def __init__( self, tkRoot, taskFuncPointer, freqencyMillis ):
        self.__tk_   = tkRoot
        self.__func_ = taskFuncPointer        
        self.__freq_ = freqencyMillis
        self.__isRunning_ = False

    def isRunning( self ) : return self.__isRunning_ 

    def start( self ) : 
        self.__isRunning_ = True
        self.__onTimer()

    def stop( self ) : self.__isRunning_ = False

    def __onTimer( self ): 
        if self.__isRunning_ :
            self.__func_() 
            self.__tk_.after( self.__freq_, self.__onTimer )

class BackgroundTask():

    def __init__( self, taskFuncPointer ):
        self.__taskFuncPointer_ = taskFuncPointer
        self.__workerThread_ = None
        self.__isRunning_ = False

    def taskFuncPointer( self ) : return self.__taskFuncPointer_

    def isRunning( self ) : 
        return self.__isRunning_ and self.__workerThread_.isAlive()

    def start( self ): 
        if not self.__isRunning_ :
            self.__isRunning_ = True
            self.__workerThread_ = self.WorkerThread( self )
            self.__workerThread_.start()

    def stop( self ) : self.__isRunning_ = False

    class WorkerThread( threading.Thread ):
        def __init__( self, bgTask ):      
            threading.Thread.__init__( self )
            self.__bgTask_ = bgTask

        def run( self ):
            try :
                self.__bgTask_.taskFuncPointer()( self.__bgTask_.isRunning )
            except Exception as e: print repr(e)
            self.__bgTask_.stop()

Here's a Tk test which demos the use of these. Just append this to the bottom of the module with those classes in it if you want to see the demo in action:

def tkThreadingTest():

    from tkinter import Tk, Label, Button, StringVar
    from time import sleep

    class UnitTestGUI:

        def __init__( self, master ):
            self.master = master
            master.title( "Threading Test" )

            self.testButton = Button( 
                self.master, text="Blocking", command=self.myLongProcess )
            self.testButton.pack()

            self.threadedButton = Button( 
                self.master, text="Threaded", command=self.onThreadedClicked )
            self.threadedButton.pack()

            self.cancelButton = Button( 
                self.master, text="Stop", command=self.onStopClicked )
            self.cancelButton.pack()

            self.statusLabelVar = StringVar()
            self.statusLabel = Label( master, textvariable=self.statusLabelVar )
            self.statusLabel.pack()

            self.clickMeButton = Button( 
                self.master, text="Click Me", command=self.onClickMeClicked )
            self.clickMeButton.pack()

            self.clickCountLabelVar = StringVar()            
            self.clickCountLabel = Label( master,  textvariable=self.clickCountLabelVar )
            self.clickCountLabel.pack()

            self.threadedButton = Button( 
                self.master, text="Timer", command=self.onTimerClicked )
            self.threadedButton.pack()

            self.timerCountLabelVar = StringVar()            
            self.timerCountLabel = Label( master,  textvariable=self.timerCountLabelVar )
            self.timerCountLabel.pack()

            self.timerCounter_=0

            self.clickCounter_=0

            self.bgTask = BackgroundTask( self.myLongProcess )

            self.timer = TkRepeatingTask( self.master, self.onTimer, 1 )

        def close( self ) :
            print "close"
            try: self.bgTask.stop()
            except: pass
            try: self.timer.stop()
            except: pass            
            self.master.quit()

        def onThreadedClicked( self ):
            print "onThreadedClicked"
            try: self.bgTask.start()
            except: pass

        def onTimerClicked( self ) :
            print "onTimerClicked"
            self.timer.start()

        def onStopClicked( self ) :
            print "onStopClicked"
            try: self.bgTask.stop()
            except: pass
            try: self.timer.stop()
            except: pass                        

        def onClickMeClicked( self ):
            print "onClickMeClicked"
            self.clickCounter_+=1
            self.clickCountLabelVar.set( str(self.clickCounter_) )

        def onTimer( self ) :
            print "onTimer"
            self.timerCounter_+=1
            self.timerCountLabelVar.set( str(self.timerCounter_) )

        def myLongProcess( self, isRunningFunc=None ) :
            print "starting myLongProcess"
            for i in range( 1, 10 ):
                try:
                    if not isRunningFunc() :
                        self.onMyLongProcessUpdate( "Stopped!" )
                        return
                except : pass   
                self.onMyLongProcessUpdate( i )
                sleep( 1.5 ) # simulate doing work
            self.onMyLongProcessUpdate( "Done!" )                

        def onMyLongProcessUpdate( self, status ) :
            print "Process Update: %s" % (status,)
            self.statusLabelVar.set( str(status) )

    root = Tk()    
    gui = UnitTestGUI( root )
    root.protocol( "WM_DELETE_WINDOW", gui.close )
    root.mainloop()

if __name__ == "__main__": 
    tkThreadingTest()

Two import points I'll stress about BackgroundTask:

1) The function you run in the background task needs to take a function pointer it will both invoke and respect, which allows the task to be cancelled mid way through - if possible.

2) You need to make sure the background task is stopped when you exit your application. That thread will still run even if your gui is closed if you don't address that!

How to call any method asynchronously in c#

Check out the MSDN article Asynchronous Programming with Async and Await if you can afford to play with new stuff. It was added to .NET 4.5.

Example code snippet from the link (which is itself from this MSDN sample code project):

// Three things to note in the signature: 
//  - The method has an async modifier.  
//  - The return type is Task or Task<T>. (See "Return Types" section.)
//    Here, it is Task<int> because the return statement returns an integer. 
//  - The method name ends in "Async."
async Task<int> AccessTheWebAsync()
{ 
    // You need to add a reference to System.Net.Http to declare client.
    HttpClient client = new HttpClient();

    // GetStringAsync returns a Task<string>. That means that when you await the 
    // task you'll get a string (urlContents).
    Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");

    // You can do work here that doesn't rely on the string from GetStringAsync.
    DoIndependentWork();

    // The await operator suspends AccessTheWebAsync. 
    //  - AccessTheWebAsync can't continue until getStringTask is complete. 
    //  - Meanwhile, control returns to the caller of AccessTheWebAsync. 
    //  - Control resumes here when getStringTask is complete.  
    //  - The await operator then retrieves the string result from getStringTask. 
    string urlContents = await getStringTask;

    // The return statement specifies an integer result. 
    // Any methods that are awaiting AccessTheWebAsync retrieve the length value. 
    return urlContents.Length;
}

Quoting:

If AccessTheWebAsync doesn't have any work that it can do between calling GetStringAsync and awaiting its completion, you can simplify your code by calling and awaiting in the following single statement.

string urlContents = await client.GetStringAsync();

More details are in the link.

How to create a dotted <hr/> tag?

hr {
    border-top:1px dotted #000;
    /*Rest of stuff here*/
}

SELECT last id, without INSERT

In MySQL, this does return the highest value from the id column:

SELECT MAX(id) FROM tablename;

However, this does not put that id into $n:

$n = mysql_query("SELECT max(id) FROM tablename");

To get the value, you need to do this:

$result = mysql_query("SELECT max(id) FROM tablename");

if (!$result) {
    die('Could not query:' . mysql_error());
}

$id = mysql_result($result, 0, 'id');

If you want to get the last insert ID from A, and insert it into B, you can do it with one command:

INSERT INTO B (col) SELECT MAX(id) FROM A;

Calling a function on bootstrap modal open

You can use the shown event/show event based on what you need:

$( "#code" ).on('shown', function(){
    alert("I want this to appear after the modal has opened!");
});

Demo: Plunker

Update for Bootstrap 3.0

For Bootstrap 3.0 you can still use the shown event but you would use it like this:

$('#code').on('shown.bs.modal', function (e) {
  // do something...
})

See the Bootstrap 3.0 docs here under "Events".

pandas dataframe convert column type to string or categorical

Prior answers focused on nominal data (e.g. unordered). If there is a reason to impose order for an ordinal variable, then one would use:

# Transform to category
df['zipcode_category'] = df['zipcode_category'].astype('category')

# Add ordered category
df['zipcode_ordered'] = df['zipcode_category']

# Setup the ordering
df.zipcode_ordered.cat.set_categories(
    new_categories = [90211, 90210], ordered = True, inplace = True
)

# Output IDs
df['zipcode_ordered_id'] = df.zipcode_ordered.cat.codes
print(df)
#  zipcode_category zipcode_ordered  zipcode_ordered_id
#            90210           90210                   1
#            90211           90211                   0

More details on setting ordered categories can be found at the pandas website:

https://pandas.pydata.org/pandas-docs/stable/user_guide/categorical.html#sorting-and-order

How do I check for vowels in JavaScript?

cycles, arrays, regexp... for what? It can be much quicker :)

function isVowel(char)
{
    return char === 'a' || char === 'e' || char === 'i' || char === 'o' || char === 'u' || false;
}

SMTP connect() failed PHPmailer - PHP

Troubleshooting

You have add this code:

 $mail->SMTPOptions = array(
        'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
        )
    );

And Enabling Allow less secure apps: "will usually solve the problem for PHPMailer, and it does not really make your app significantly less secure. Reportedly, changing this setting may take an hour or more to take effect, so don't expect an immediate fix"

This work for me!

vue.js 2 how to watch store values from vuex

The best way to watch store changes is to use mapGetters as Gabriel said. But there is a case when you can't do it through mapGetters e.g. you want to get something from store using parameter:

getters: {
  getTodoById: (state, getters) => (id) => {
    return state.todos.find(todo => todo.id === id)
  }
}

in that case you can't use mapGetters. You may try to do something like this instead:

computed: {
    todoById() {
        return this.$store.getters.getTodoById(this.id)
    }
}

But unfortunately todoById will be updated only if this.id is changed

If you want you component update in such case use this.$store.watch solution provided by Gong. Or handle your component consciously and update this.id when you need to update todoById.

Spring MVC 4: "application/json" Content Type is not being set correctly

First thing to understand is that the RequestMapping#produces() element in

@RequestMapping(value = "/json", method = RequestMethod.GET, produces = "application/json")

serves only to restrict the mapping for your request handlers. It does nothing else.

Then, given that your method has a return type of String and is annotated with @ResponseBody, the return value will be handled by StringHttpMessageConverter which sets the Content-type header to text/plain. If you want to return a JSON string yourself and set the header to application/json, use a return type of ResponseEntity (get rid of @ResponseBody) and add appropriate headers to it.

@RequestMapping(value = "/json", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<String> bar() {
    final HttpHeaders httpHeaders= new HttpHeaders();
    httpHeaders.setContentType(MediaType.APPLICATION_JSON);
    return new ResponseEntity<String>("{\"test\": \"jsonResponseExample\"}", httpHeaders, HttpStatus.OK);
}

Note that you should probably have

<mvc:annotation-driven /> 

in your servlet context configuration to set up your MVC configuration with the most suitable defaults.

SQL Server IIF vs CASE

IIF is the same as CASE WHEN <Condition> THEN <true part> ELSE <false part> END. The query plan will be the same. It is, perhaps, "syntactical sugar" as initially implemented.

CASE is portable across all SQL platforms whereas IIF is SQL SERVER 2012+ specific.

Append date to filename in linux

I use this script in bash:

#!/bin/bash

now=$(date +"%b%d-%Y-%H%M%S")
FILE="$1"
name="${FILE%.*}"
ext="${FILE##*.}"

cp -v $FILE $name-$now.$ext

This script copies filename.ext to filename-date.ext, there is another that moves filename.ext to filename-date.ext, you can download them from here. Hope you find them useful!!

How to align matching values in two columns in Excel, and bring along associated values in other columns

assuming the item numbers are unique, a VLOOKUP should get you the information you need.

first value would be =VLOOKUP(E1,A:B,2,FALSE), and the same type of formula to retrieve the second value would be =VLOOKUP(E1,C:D,2,FALSE). Wrap them in an IFERROR if you want to return anything other than #N/A if there is no corresponding value in the item column(s)

How to print (using cout) a number in binary form?

#include <iostream> 
#include <cmath>       // in order to use pow() function
using namespace std; 

string show_binary(unsigned int u, int num_of_bits);

int main() 
{ 

  cout << show_binary(128, 8) << endl;   // should print 10000000
  cout << show_binary(128, 5) << endl;   // should print 00000
  cout << show_binary(128, 10) << endl;  // should print 0010000000

  return 0; 
}

string show_binary(unsigned int u, int num_of_bits) 
{ 
  string a = "";

  int t = pow(2, num_of_bits);   // t is the max number that can be represented

  for(t; t>0; t = t/2)           // t iterates through powers of 2
      if(u >= t){                // check if u can be represented by current value of t
          u -= t;
          a += "1";               // if so, add a 1
      }
      else {
          a += "0";               // if not, add a 0
      }

  return a ;                     // returns string
}

Convert dictionary to list collection in C#

If you want to pass the Dictionary keys collection into one method argument.

List<string> lstKeys = Dict.Keys;
Methodname(lstKeys);
-------------------
void MethodName(List<String> lstkeys)
{
    `enter code here`
    //Do ur task
}

How to enable CORS in ASP.NET Core

you have three ways to enable CORS:

  • In middleware using a named policy or default policy.
  • Using endpoint routing.
  • With the [EnableCors] attribute.

Enable CORS with named policy:

public class Startup
{
    readonly string CorsPolicy = "_corsPolicy";

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy(name: CorsPolicy,
                              builder =>
                              {
                                 builder.AllowAnyOrigin()
                                      .AllowAnyMethod()
                                      .AllowAnyHeader()
                                      .AllowCredentials();
                              });
        });

        // services.AddResponseCaching();
        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseRouting();

        app.UseCors(CorsPolicy);

        // app.UseResponseCaching();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

UseCors must be called before UseResponseCaching when using UseResponseCaching.

Enable CORS with default policy:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddDefaultPolicy(
                builder =>
                {
                     builder.AllowAnyOrigin()
                                      .AllowAnyMethod()
                                      .AllowAnyHeader()
                                      .AllowCredentials();
                });
        });

        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseRouting();

        app.UseCors();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

Enable CORS with endpoint

public class Startup
{
    readonly string CorsPolicy = "_corsPolicy ";

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy(name: CorsPolicy,
                              builder =>
                              {
                                  builder.AllowAnyOrigin()
                                      .AllowAnyMethod()
                                      .AllowAnyHeader()
                                      .AllowCredentials();
                              });
        });

        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseRouting();

        app.UseCors();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers()
                     .RequireCors(CorsPolicy)
        });
    }
}

Enable CORS with attributes

you have tow option

  • [EnableCors] specifies the default policy.
  • [EnableCors("{Policy String}")] specifies a named policy.

Wait until boolean value changes it state

public Boolean test() throws InterruptedException {
    BlockingQueue<Boolean> booleanHolder = new LinkedBlockingQueue<>();
    new Thread(() -> {
        try {
            TimeUnit.SECONDS.sleep(2);
            booleanHolder.put(true);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }).start();
    return booleanHolder.poll(4, TimeUnit.SECONDS);
}

jQuery - Getting the text value of a table cell in the same row as a clicked element

Nick has the right answer, but I wanted to add you could also get the cell data without needing the class name

var Something = $(this).closest('tr').find('td:eq(1)').text();

:eq(#) has a zero based index (link).

jQuery counter to count up to a target number

Don't know about plugins but this shouldn't be too hard:

;(function($) {        
     $.fn.counter = function(options) {
        // Set default values
        var defaults = {
            start: 0,
            end: 10,
            time: 10,
            step: 1000,
            callback: function() { }
        }
        var options = $.extend(defaults, options);            
        // The actual function that does the counting
        var counterFunc = function(el, increment, end, step) {
            var value = parseInt(el.html(), 10) + increment;
            if(value >= end) {
                el.html(Math.round(end));
                options.callback();
            } else {
                el.html(Math.round(value));
                setTimeout(counterFunc, step, el, increment, end, step);
            }
        }            
        // Set initial value
        $(this).html(Math.round(options.start));
        // Calculate the increment on each step
        var increment = (options.end - options.start) / ((1000 / options.step) * options.time);            
        // Call the counter function in a closure to avoid conflicts
        (function(e, i, o, s) {
            setTimeout(counterFunc, s, e, i, o, s);
        })($(this), increment, options.end, options.step);
    }
})(jQuery);

Usage:

$('#foo').counter({
    start: 1000,
    end: 4500,
    time: 8,
    step: 500,
    callback: function() {
        alert("I'm done!");
    }
});

Example:

http://www.ulmanen.fi/stuff/counter.php

I guess the usage is self-explanatory; in this example, the counter will start from 1000 and count up to 4500 in 8 seconds in 500ms intervals, and will call the callback function when the counting is done.

How to quit a java app from within the program

Runtime.getCurrentRumtime().halt(0);

Arithmetic operation resulted in an overflow. (Adding integers)

2055786000 + 93552000 = 2149338000, which is greater than 2^31. So if you're using signed integers coded on 4 bytes, the result of the operation doesn't fit and you get an overflow exception.

Visual Studio Post Build Event - Copy to Relative Directory Location

If none of the TargetDir or other macros point to the right place, use the ".." directory to go backwards up the folder hierarchy.

ie. Use $(SolutionDir)\..\.. to get your base directory.


For list of all macros, see here:

http://msdn.microsoft.com/en-us/library/c02as0cs.aspx

Converting from byte to int in java

if you want to combine the 4 bytes into a single int you need to do

int i= (rno[0]<<24)&0xff000000|
       (rno[1]<<16)&0x00ff0000|
       (rno[2]<< 8)&0x0000ff00|
       (rno[3]<< 0)&0x000000ff;

I use 3 special operators | is the bitwise logical OR & is the logical AND and << is the left shift

in essence I combine the 4 8-bit bytes into a single 32 bit int by shifting the bytes in place and ORing them together

I also ensure any sign promotion won't affect the result with & 0xff

How add class='active' to html menu with php

             <ul>

                <li><a <?php echo ($page == "yourfilename") ? "class='active'" : ""; ?> href="user.php" ><span>Article</span></a></li>
                <li><a <?php echo ($page == "yourfilename") ? "class='active'" : ""; ?> href="newarticle.php"><span>New Articles</span></a></li>

                </ul>

Expression must have class type

a is a pointer. You need to use->, not .

SQL Inner join more than two tables

Here is a general SQL query syntax to join three or more table. This SQL query should work in all major relation database e.g. MySQL, Oracle, Microsoft SQLServer, Sybase and PostgreSQL :

SELECT t1.col, t3.col FROM table1 join table2 ON table1.primarykey = table2.foreignkey
                                  join table3 ON table2.primarykey = table3.foreignkey

We first join table 1 and table 2 which produce a temporary table with combined data from table1 and table2, which is then joined to table3. This formula can be extended for more than 3 tables to N tables, You just need to make sure that SQL query should have N-1 join statement in order to join N tables. like for joining two tables we require 1 join statement and for joining 3 tables we need 2 join statement.

Check file extension in upload form in PHP

use this function

 function check_image_extension($image){

        $images_extentions = array("jpg","JPG","jpeg","JPEG","png","PNG");

        $image_parts = explode(".",$image);

        $image_end_part = end($image_parts);

        if(in_array($image_end_part,$images_extentions ) == true){

            return time() . "." . $image_end_part;


        }else{

            return false;
        }


    }

Example: Communication between Activity and Service using Messaging

This is how I implemeted Activity->Service Communication: on my Activity i had

private static class MyResultReciever extends ResultReceiver {
     /**
     * Create a new ResultReceive to receive results.  Your
     * {@link #onReceiveResult} method will be called from the thread running
     * <var>handler</var> if given, or from an arbitrary thread if null.
     *
     * @param handler
     */
     public MyResultReciever(Handler handler) {
         super(handler);
     }

     @Override
     protected void onReceiveResult(int resultCode, Bundle resultData) {
         if (resultCode == 100) {
             //dostuff
         }
     }

And then I used this to start my Service

protected void onCreate(Bundle savedInstanceState) {
MyResultReciever resultReciever = new MyResultReciever(handler);
        service = new Intent(this, MyService.class);
        service.putExtra("receiver", resultReciever);
        startService(service);
}

In my Service i had

public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null)
        resultReceiver = intent.getParcelableExtra("receiver");
    return Service.START_STICKY;
}

Hope this Helps

How to create a timeline with LaTeX?

The tikz package seems to have what you want.

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{snakes}

\begin{document}

  \begin{tikzpicture}[snake=zigzag, line before snake = 5mm, line after snake = 5mm]
    % draw horizontal line   
    \draw (0,0) -- (2,0);
    \draw[snake] (2,0) -- (4,0);
    \draw (4,0) -- (5,0);
    \draw[snake] (5,0) -- (7,0);

    % draw vertical lines
    \foreach \x in {0,1,2,4,5,7}
      \draw (\x cm,3pt) -- (\x cm,-3pt);

    % draw nodes
    \draw (0,0) node[below=3pt] {$ 0 $} node[above=3pt] {$   $};
    \draw (1,0) node[below=3pt] {$ 1 $} node[above=3pt] {$ 10 $};
    \draw (2,0) node[below=3pt] {$ 2 $} node[above=3pt] {$ 20 $};
    \draw (3,0) node[below=3pt] {$  $} node[above=3pt] {$  $};
    \draw (4,0) node[below=3pt] {$ 5 $} node[above=3pt] {$ 50 $};
    \draw (5,0) node[below=3pt] {$ 6 $} node[above=3pt] {$ 60 $};
    \draw (6,0) node[below=3pt] {$  $} node[above=3pt] {$  $};
    \draw (7,0) node[below=3pt] {$ n $} node[above=3pt] {$ 10n $};
  \end{tikzpicture}

\end{document}

I'm not too expert with tikz, but this does give a good timeline, which looks like:

enter image description here

Python variables as keys to dict

Based on the answer by mouad, here's a more pythonic way to select the variables based on a prefix:

# All the vars that I want to get start with fruit_
fruit_apple = 1
fruit_carrot = 'f'
rotten = 666

prefix = 'fruit_'
sourcedict = locals()
fruitdict = { v[len(prefix):] : sourcedict[v]
              for v in sourcedict
              if v.startswith(prefix) }
# fruitdict = {'carrot': 'f', 'apple': 1}

You can even put that in a function with prefix and sourcedict as arguments.

Checking if a date is valid in javascript

Try this:

var date = new Date();
console.log(date instanceof Date && !isNaN(date.valueOf()));

This should return true.

UPDATED: Added isNaN check to handle the case commented by Julian H. Lam

Android RatingBar change star colors

Use android:theme attribute:

styles.xml

<style name="Theme.Rating" parent="Theme.AppCompat.Light">
    <item name="colorAccent">@color/rating</item>
</style>

layout.xml

<android.support.v7.widget.AppCompatRatingBar
    android:theme="@style/Theme.Rating"
    android:numStars="5"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

How to define a two-dimensional array?

Here is the code snippet for creating a matrix in python:

# get the input rows and cols
rows = int(input("rows : "))
cols = int(input("Cols : "))

# initialize the list
l=[[0]*cols for i in range(rows)]

# fill some random values in it
for i in range(0,rows):
    for j in range(0,cols):
        l[i][j] = i+j

# print the list
for i in range(0,rows):
    print()
    for j in range(0,cols):
        print(l[i][j],end=" ")

Please suggest if I have missed something.

How to solve the “failed to lazily initialize a collection of role” Hibernate exception

If you are trying to have a relation between a entity and a Collection or a List of java objects (for example Long type), it would like something like this:

@ElementCollection(fetch = FetchType.EAGER)
    public List<Long> ids;

Vue.js : How to set a unique ID for each component instance?

If your uid is not used by other compoment, I have an idea.

uid: Math.random()

Simple and enough.

How to get a product's image in Magento?

$model = Mage::getModel('catalog/product'); //getting product model
$_products = $model->getCollection(); //getting product object for particular product id
foreach($_products as $_product) { ?>
    <a href = '<?php echo $model->load($_product->getData("entity_id"))->getUrl_path(); ?>'> <img src= '<?php echo $model->load($_product->getData("entity_id"))->getImageUrl();  ?>' width="75px" height="75px"/></a>
     <?php echo "<br/>".$model->load($_product->getData("entity_id"))->getPrice()."<br/>". $model->load($_product->getData("entity_id"))->getSpecial_price()."<br/>".$model->load($_product->getData("entity_id"))->getName()?>
<?php 

how to get multiple checkbox value using jquery

You can do it like this,

$('.ads_Checkbox:checked')

You can iterate through them with each() and fill the array with checkedbox values.

Live Demo

To get the values of selected checkboxes in array

var i = 0;
$('#save_value').click(function () {
       var arr = [];
       $('.ads_Checkbox:checked').each(function () {
           arr[i++] = $(this).val();
       });      
});

Edit, using .map()

You can also use jQuery.map with get() to get the array of selected checkboxe values.

As a side note using this.value instead of $(this).val() would give better performance.

Live Demo

$('#save_value').click(function(){
    var arr = $('.ads_Checkbox:checked').map(function(){
        return this.value;
    }).get();
}); 

How do I format a date as ISO 8601 in moment.js?

If you just want the date portion (e.g. 2017-06-27), and you want it to work regardless of time zone and also in Arabic, here is code I wrote:

function isoDate(date) {
    if (!date) {
        return null
    }
    date = moment(date).toDate()

    // don't call toISOString because it takes the time zone into
    // account which we don't want.  Also don't call .format() because it
    // returns Arabic instead of English

    var month = 1 + date.getMonth()
    if (month < 10) {
        month = '0' + month
    }
    var day = date.getDate()
    if (day < 10) {
        day = '0' + day
    }
    return date.getFullYear() + '-' + month + '-' + day
}

Why does typeof array with objects return "object" and not "array"?

Try this example and you will understand also what is the difference between Associative Array and Object in JavaScript.

Associative Array

var a = new Array(1,2,3); 
a['key'] = 'experiment';
Array.isArray(a);

returns true

Keep in mind that a.length will be undefined, because length is treated as a key, you should use Object.keys(a).length to get the length of an Associative Array.

Object

var a = {1:1, 2:2, 3:3,'key':'experiment'}; 
Array.isArray(a)

returns false

JSON returns an Object ... could return an Associative Array ... but it is not like that

Apply a theme to an activity in Android?

To set it programmatically in Activity.java:

public void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setTheme(R.style.MyTheme); // (for Custom theme)
  setTheme(android.R.style.Theme_Holo); // (for Android Built In Theme)

  this.setContentView(R.layout.myactivity);

To set in Application scope in Manifest.xml (all activities):

 <application
    android:theme="@android:style/Theme.Holo"
    android:theme="@style/MyTheme">

To set in Activity scope in Manifest.xml (single activity):

  <activity
    android:theme="@android:style/Theme.Holo"
    android:theme="@style/MyTheme">

To build a custom theme, you will have to declare theme in themes.xml file, and set styles in styles.xml file.

simple way to display data in a .txt file on a webpage?

You cannot style a text file, it must be HTML

Greater than and less than in one statement

java is not python.

you can't do anything like this

if(0 < i < 5) or if(i in range(0,6))

you mentioned the easiest way :

int i = getFilesSize();
if(0 < i && i < 5){
    //operations

}

of

   if(0 < i){
       if(i < 5){
          //operations
       }
     }

What exactly does stringstream do?

To answer the question. stringstream basically allows you to treat a string object like a stream, and use all stream functions and operators on it.

I saw it used mainly for the formatted output/input goodness.

One good example would be c++ implementation of converting number to stream object.

Possible example:

template <class T>
string num2str(const T& num, unsigned int prec = 12) {
    string ret;
    stringstream ss;
    ios_base::fmtflags ff = ss.flags();
    ff |= ios_base::floatfield;
    ff |= ios_base::fixed;
    ss.flags(ff);
    ss.precision(prec);
    ss << num;
    ret = ss.str();
    return ret;
};

Maybe it's a bit complicated but it is quite complex. You create stringstream object ss, modify its flags, put a number into it with operator<<, and extract it via str(). I guess that operator>> could be used.

Also in this example the string buffer is hidden and not used explicitly. But it would be too long of a post to write about every possible aspect and use-case.

Note: I probably stole it from someone on SO and refined, but I don't have original author noted.

Resize on div element

DIV does not fire a resize event, so you won't be able to do exactly what you've coded, but you could look into monitoring DOM properties.

If you are actually working with something like resizables, and that is the only way for a div to change in size, then your resize plugin will probably be implementing a callback of its own.

How to generate and validate a software license key?

I don't know how elaborate you want to get

but i believe that .net can access the hard drive serial number.

you could have the program send you that and something eles ( like user name and mac address of the nic)

you compute a code based off that and email them back the key.

they will keep them from switching machines after they have the key.

Could not establish secure channel for SSL/TLS with authority '*'

We had this issue on a new webserver from .aspx pages calling a webservice. We had not given permission to the app pool user to the machine certificate. The issue was fixed after we granted permission to the app pool user.

Readably print out a python dict() sorted by key

I wrote the following function to print dicts, lists, and tuples in a more readable format:

def printplus(obj):
    """
    Pretty-prints the object passed in.

    """
    # Dict
    if isinstance(obj, dict):
        for k, v in sorted(obj.items()):
            print u'{0}: {1}'.format(k, v)

    # List or tuple            
    elif isinstance(obj, list) or isinstance(obj, tuple):
        for x in obj:
            print x

    # Other
    else:
        print obj

Example usage in iPython:

>>> dict_example = {'c': 1, 'b': 2, 'a': 3}
>>> printplus(dict_example)
a: 3
b: 2
c: 1

>>> tuple_example = ((1, 2), (3, 4), (5, 6), (7, 8))
>>> printplus(tuple_example)
(1, 2)
(3, 4)
(5, 6)
(7, 8)

.append(), prepend(), .after() and .before()

Imagine the DOM (HTML page) as a tree right. The HTML elements are the nodes of this tree.

The append() adds a new node to the child of the node you called it on.

Example:$("#mydiv").append("<p>Hello there</p>") 

creates a child node <p> to <div>

The after() adds a new node as a sibling or at the same level or child to the parent of the node you called it on.

How to check if a folder exists

Quite simple:

new File("/Path/To/File/or/Directory").exists();

And if you want to be certain it is a directory:

File f = new File("/Path/To/File/or/Directory");
if (f.exists() && f.isDirectory()) {
   ...
}

Take multiple lists into dataframe

I think you're almost there, try removing the extra square brackets around the lst's (Also you don't need to specify the column names when you're creating a dataframe from a dict like this):

import pandas as pd
lst1 = range(100)
lst2 = range(100)
lst3 = range(100)
percentile_list = pd.DataFrame(
    {'lst1Title': lst1,
     'lst2Title': lst2,
     'lst3Title': lst3
    })

percentile_list
    lst1Title  lst2Title  lst3Title
0          0         0         0
1          1         1         1
2          2         2         2
3          3         3         3
4          4         4         4
5          5         5         5
6          6         6         6
...

If you need a more performant solution you can use np.column_stack rather than zip as in your first attempt, this has around a 2x speedup on the example here, however comes at bit of a cost of readability in my opinion:

import numpy as np
percentile_list = pd.DataFrame(np.column_stack([lst1, lst2, lst3]), 
                               columns=['lst1Title', 'lst2Title', 'lst3Title'])

How to use ADB to send touch events to device using sendevent command?

Android comes with an input command-line tool that can simulate miscellaneous input events. To simulate tapping, it's:

input tap x y

You can use the adb shell ( > 2.3.5) to run the command remotely:

adb shell input tap x y

How to turn on WCF tracing?

Go to your Microsoft SDKs directory. A path like this:

C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6 Tools

Open the WCF Configuration Editor (Microsoft Service Configuration Editor) from that directory:

SvcConfigEditor.exe

(another option to open this tool is by navigating in Visual Studio 2017 to "Tools" > "WCF Service Configuration Editor")

wcf configuration editor

Open your .config file or create a new one using the editor and navigate to Diagnostics.

There you can click the "Enable MessageLogging".

enable messagelogging

More info: https://msdn.microsoft.com/en-us/library/ms732009(v=vs.110).aspx

With the trace viewer from the same directory you can open the trace log files:

SvcTraceViewer.exe

You can also enable tracing using WMI. More info: https://msdn.microsoft.com/en-us/library/ms730064(v=vs.110).aspx

How to analyze information from a Java core dump?

Okay if you've created the core dump with gcore or gdb then you'll need to convert it to something called a HPROF file. These can be used by VisualVM, Netbeans or Eclipse's Memory Analyzer Tool (formerly SAP Memory Analyzer). I'd recommend Eclipse MAT.

To convert the file use the commandline tool jmap.

# jmap -dump:format=b,file=dump.hprof /usr/bin/java core.1234

where:

dump.hprof is the name of the hprof file you wish to create

/usr/bin/java is the path to the version of the java binary that generated the core dump

core.1234 is your regular core file.

Reflection - get attribute name and value on property

To get all attributes of a property in a dictionary use this:

typeof(Book)
  .GetProperty("Name")
  .GetCustomAttributes(false) 
  .ToDictionary(a => a.GetType().Name, a => a);

remember to change from false to true if you want to include inheritted attributes as well.

How to make <input type="date"> supported on all browsers? Any alternatives?

best easy and working solution i have found is, working on following browsers

  1. Google Chrome
  2. Firefox
  3. Microsoft Edge
  4. Safari

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Untitled Document</title>
    </head>
    
    <body>
    <h2>Poly Filler Script for Date/Time</h2>
    <form method="post" action="">
        <input type="date" />
        <br/><br/>
        <input type="time" />
    </form>
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="http://cdn.jsdelivr.net/webshim/1.12.4/extras/modernizr-custom.js"></script>
    <script src="http://cdn.jsdelivr.net/webshim/1.12.4/polyfiller.js"></script>
    <script>
      webshims.setOptions('waitReady', false);
      webshims.setOptions('forms-ext', {type: 'date'});
      webshims.setOptions('forms-ext', {type: 'time'});
      webshims.polyfill('forms forms-ext');
    </script>
    
    </body>
    </html>
    

How do I get the last four characters from a string in C#?

A simple solution would be:

string mystring = "34234234d124";
string last4 = mystring.Substring(mystring.Length - 4, 4);

How to change the minSdkVersion of a project?

check it: Android Studio->file->project structure->app->flavors->min sdk version and if you want to run your application on your mobile you have to set min sdk version less than your device sdk(API) you can install any API levels.

How to manually reload Google Map with JavaScript

Yes, you can 'refresh' a Google Map like this:

google.maps.event.trigger(map, 'resize');

This basically sends a signal to your map to redraw it.

Hope that helps!

How to specify a min but no max decimal using the range data annotation attribute?

I would put decimal.MaxValue.ToString() since this is the effective ceiling for the decmial type it is equivalent to not having an upper bound.

How to get relative path of a file in visual studio?

I'm a little late, and I'm not sure if this is what you're looking for, but I thought I'd add it just in case someone else finds it useful.

Suppose this is your file structure:

/BulutDepoProject
    /bin
        Main.exe
    /FolderIcon
        Folder.ico
        Main.cs

You need to write your path relative to the Main.exe file. So, you want to access Folder.ico, in your Main.cs you can use:

String path = "..\\FolderIcon\\Folder.ico"

That seemed to work for me!

What is the closest thing Windows has to fork()?

The following document provides some information on porting code from UNIX to Win32: https://msdn.microsoft.com/en-us/library/y23kc048.aspx

Among other things, it indicates that the process model is quite different between the two systems and recommends consideration of CreateProcess and CreateThread where fork()-like behavior is required.

Import CSV file into SQL Server

Import the file into Excel by first opening excel, then going to DATA, import from TXT File, choose the csv extension which will preserve 0 prefixed values, and save that column as TEXT because excel will drop the leading 0 otherwise (DO NOT double click to open with Excel if you have numeric data in a field starting with a 0 [zero]). Then just save out as a Tab Delimited Text file. When you are importing into excel you get an option to save as GENERAL, TEXT, etc.. choose TEXT so that quotes in the middle of a string in a field like YourCompany,LLC are preserved also...

BULK INSERT dbo.YourTableName
FROM 'C:\Users\Steve\Downloads\yourfiletoIMPORT.txt'
WITH (
FirstRow = 2, (if skipping a header row)
FIELDTERMINATOR = '\t',
ROWTERMINATOR   = '\n'
)

I wish I could use the FORMAT and Fieldquote functionality but that does not appear to be supported in my version of SSMS

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

I had the same problem. Make sure you include assembly name in Factory property in your .svc file. Maybe you need to clean IIS cache if you had renamed project assembly name.

How to remove leading and trailing whitespace in a MySQL field?

This statement will remove and update the field content of your database

To remove whitespaces in the left side of the field value

UPDATE table SET field1 = LTRIM(field1);

ex. UPDATE member SET firstName = LTRIM(firstName);

To remove whitespaces in the right side of the field value

UPDATE table SETfield1 = RTRIM(field1);

ex. UPDATE member SET firstName = RTRIM(firstName);

Creating a jQuery object from a big HTML-string

var jQueryObject = $('<div></div>').html( string ).children();

This creates a dummy jQuery object in which you can put the string as HTML. Then, you get the children only.

UTF-8 in Windows 7 CMD

This question has been already answered in Unicode characters in Windows command line - how?

You missed one step -> you need to use Lucida console fonts in addition to executing chcp 65001 from cmd console.

Functional programming vs Object Oriented programming

You don't necessarily have to choose between the two paradigms. You can write software with an OO architecture using many functional concepts. FP and OOP are orthogonal in nature.

Take for example C#. You could say it's mostly OOP, but there are many FP concepts and constructs. If you consider Linq, the most important constructs that permit Linq to exist are functional in nature: lambda expressions.

Another example, F#. You could say it's mostly FP, but there are many OOP concepts and constructs available. You can define classes, abstract classes, interfaces, deal with inheritance. You can even use mutability when it makes your code clearer or when it dramatically increases performance.

Many modern languages are multi-paradigm.

Recommended readings

As I'm in the same boat (OOP background, learning FP), I'd suggest you some readings I've really appreciated:

error: expected primary-expression before ')' token (C)

You should create a variable of the type SelectionneNonSelectionne.

struct SelectionneNonSelectionne var;

After that pass that variable to the function like

characterSelection(screen, var);

The error is caused since you are passing the type name SelectionneNonSelectionne

IndexError: list index out of range and python

If you read a list from text file, you may get the last empty line as a list element. You can get rid of it like this:

list.pop()
for i in list:
   i[12]=....

Android: adb: Permission Denied

You might need to activate adb root from the developer settings menu. If you run adb root from the cmd line you can get:

root access is disabled by system setting - enable in settings -> development options

Once you activate the root option (ADB only or Apps and ADB) adb will restart and you will be able to use root from the cmd line.

Shrinking navigation bar when scrolling down (bootstrap3)

toggleClass works too:

$(window).on("scroll", function() {
    $("nav").toggleClass("shrink", $(this).scrollTop() > 50)
});

Chrome extension: accessing localStorage in content script

Another option would be to use the chromestorage API. This allows storage of user data with optional syncing across sessions.

One downside is that it is asynchronous.

https://developer.chrome.com/extensions/storage.html

Is Spring annotation @Controller same as @Service?

No, they are pretty different from each other.

Both are different specializations of @Component annotation (in practice, they're two different implementations of the same interface) so both can be discovered by the classpath scanning (if you declare it in your XML configuration)

@Service annotation is used in your service layer and annotates classes that perform service tasks, often you don't use it but in many case you use this annotation to represent a best practice. For example, you could directly call a DAO class to persist an object to your database but this is horrible. It is pretty good to call a service class that calls a DAO. This is a good thing to perform the separation of concerns pattern.

@Controller annotation is an annotation used in Spring MVC framework (the component of Spring Framework used to implement Web Application). The @Controller annotation indicates that a particular class serves the role of a controller. The @Controller annotation acts as a stereotype for the annotated class, indicating its role. The dispatcher scans such annotated classes for mapped methods and detects @RequestMapping annotations.

So looking at the Spring MVC architecture you have a DispatcherServlet class (that you declare in your XML configuration) that represent a front controller that dispatch all the HTTP Request towards the appropriate controller classes (annotated by @Controller). This class perform the business logic (and can call the services) by its method. These classes (or its methods) are typically annotated also with @RequestMapping annotation that specify what HTTP Request is handled by the controller and by its method.

For example:

@Controller
@RequestMapping("/appointments")
public class AppointmentsController {

    private final AppointmentBook appointmentBook;

    @Autowired
    public AppointmentsController(AppointmentBook appointmentBook) {
        this.appointmentBook = appointmentBook;
    }

    @RequestMapping(method = RequestMethod.GET)
    public Map<String, Appointment> get() {
        return appointmentBook.getAppointmentsForToday();
    }

This class is a controller.

This class handles all the HTTP Request toward "/appointments" "folder" and in particular the get method is the method called to handle all the GET HTTP Request toward the folder "/appointments".

I hope that now it is more clear for you.

Does the target directory for a git clone have to match the repo name?

Yes, it is possible:

git clone https://github.com/pitosalas/st3_packages Packages 

You can specify the local root directory when using git clone.

<directory> 

The name of a new directory to clone into.
The "humanish" part of the source repository is used if no directory is explicitly given (repo for /path/to/repo.git and foo for host.xz:foo/.git).
Cloning into an existing directory is only allowed if the directory is empty.


As Chris comments, you can then rename that top directory.
Git only cares about the .git within said top folder, which you can get with various commands:

git rev-parse --show-toplevel git rev-parse --git-dir 

java.net.UnknownHostException: Unable to resolve host "<url>": No address associated with hostname and End of input at character 0 of

I got the same error and the issue was that I was on VPN and I didn't realize it. After disconnecting from the VPN and reconnecting to my WIFI network, the problem was resolved.

How can I make a TextBox be a "password box" and display stars when using MVVM?

I did the below from the Views codebehind to set my property within the view model. Not sure if it really " breaks" the MVVM pattern but its the best and least complexe solution found.

  var data = this.DataContext as DBSelectionViewModel;

        data.PassKey = txtPassKey.Password;

How do I programmatically change file permissions?

In addition to erickson's suggestions, there's also jna, which allows you to call native libraries without using jni. It's shockingly easy to use, and I've used it on a couple of projects with great success.

The only caveat is that it's slower than jni, so if you're doing this to a very large number of files that might be an issue for you.

(Editing to add example)

Here's a complete jna chmod example:

import com.sun.jna.Library;
import com.sun.jna.Native;

public class Main {
    private static CLibrary libc = (CLibrary) Native.loadLibrary("c", CLibrary.class);

    public static void main(String[] args) {
        libc.chmod("/path/to/file", 0755);
    }
}

interface CLibrary extends Library {
    public int chmod(String path, int mode);
}

How to change color of ListView items on focus and on click

Declare list item components as final outside your setOnClickListener or whatever you want to apply on your list item like this:

final View yourView;
final TextView yourTextView;

And in overriding onClick or whatever method you use, just set colors as needed like this:

yourView.setBackgroundColor(Color.WHITE/*or whatever RGB suites good contrast*/);
yourTextView.setTextColor(Color.BLACK/*or whatever RGB suites good contrast*/);

Or without the final declaration, if let's say you implement an onClick() for a custom adapter to populate a list, this is what I used in getView() for my setOnClickListener/onClick():

//reset color for all list items in case any item was previously selected
for(int i = 0; i < parent.getChildCount(); i++)
{
  parent.getChildAt(i).setBackgroundColor(Color.BLACK);
  TextView text=(TextView) parent.getChildAt(i).findViewById(R.id.item);
  text.setTextColor(Color.rgb(0,178,178));
}
//highlight currently selected item
 parent.getChildAt(position).setBackgroundColor(Color.rgb(0,178,178));
 TextView text=(TextView) parent.getChildAt(position).findViewById(R.id.item);
 text.setTextColor(Color.rgb(0,178,178));

Removing cordova plugins from the project

  • access the folder
  • list the plugins (cordova plugin list)
  • ionic cordova plugin remove "pluginName"

Should be fine!

Write HTML string in JSON

Just encode html using Base64 algorithm before adding html to the JSON and decode html using Base64 when you read.

byte[] utf8 = htmlMessage.getBytes("UTF8");
htmlMessage= new String(new Base64().encode(utf8));


byte[] dec = new Base64().decode(htmlMessage.getBytes());
htmlMessage = new String(dec , "UTF8");

Is there a way to 'uniq' by column?

sort -u -t, -k1,1 file
  • -u for unique
  • -t, so comma is the delimiter
  • -k1,1 for the key field 1

Test result:

[email protected],2009-11-27 00:58:29.793000000,xx3.net,255.255.255.0 
[email protected],2009-11-27 01:05:47.893000000,xx2.net,127.0.0.1 

blur vs focusout -- any real differences?

The documentation for focusout says (emphasis mine):

The focusout event is sent to an element when it, or any element inside of it, loses focus. This is distinct from the blur event in that it supports detecting the loss of focus on descendant elements (in other words, it supports event bubbling).

The same distinction exists between the focusin and focus events.

Eclipse executable launcher error: Unable to locate companion shared library

I faced this problem and solved it by running Eclipse as admin.

How to make FileFilter in java?

Here is a little utility class that I created:

import java.io.File;
import java.io.FilenameFilter;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * Convenience utility to create a FilenameFilter, based on a list of extensions
 */
public class FileExtensionFilter implements FilenameFilter {
    private Set<String> exts = new HashSet<String>();

    /**
     * @param extensions
     *            a list of allowed extensions, without the dot, e.g.
     *            <code>"xml","html","rss"</code>
     */
    public FileExtensionFilter(String... extensions) {
        for (String ext : extensions) {
            exts.add("." + ext.toLowerCase().trim());
        }
    }

    public boolean accept(File dir, String name) {
        final Iterator<String> extList = exts.iterator();
        while (extList.hasNext()) {
            if (name.toLowerCase().endsWith(extList.next())) {
                return true;
            }
        }
        return false;
    }
}

Usage:

       String[] files = new File("myfile").list(new FileExtensionFilter("pdf", "zip"));

insert echo into the specific html element like div which has an id or class

Have you tried this?:

    $string = '';
    while($row = mysql_fetch_array($result))
    {
    //this will combine all the results into one string
    $string .= '<img src="'.$row['name'].'" />
                <div>'.$row['name'].'</div>
                <div>'.$row['title'].'</div>
                <div>'.$row['description'].'</div>
                <div>'.$row['link'].'</div><br />';

    //or this will add the individual result in an array
 /*
     $yourHtml[] = $row;
*/
    }

then you echo the $tring to the place you want it to be

<div id="place_here">
   <?php echo $string; ?>
   <?php 
     //or
    /*
      echo '<img src="'.$yourHtml[0]['name'].'" />;//change the index, or you just foreach loop it
    */
    ?>
</div>

How to represent the double quotes character (") in regex?

you need to use backslash before ". like \"

From the doc here you can see that

A character preceded by a backslash ( \ ) is an escape sequence and has special meaning to the compiler.

and " (double quote) is a escacpe sequence

When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. For example, if you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes. To print the sentence

She said "Hello!" to me.

you would write

System.out.println("She said \"Hello!\" to me.");

Create a Dropdown List for MVC3 using Entity Framework (.edmx Model) & Razor Views && Insert A Database Record to Multiple Tables

Well, actually I'll have to say David is right with his solution, but there are some topics disturbing me:

  1. You should never send your model to the view => This is correct
  2. If you create a ViewModel, and include the Model as member in the ViewModel, then you effectively sent your model to the View => this is BAD
  3. Using dictionaries to send the options to the view => this not good style

So how can you create a better coupling?

I would use a tool like AutoMapper or ValueInjecter to map between ViewModel and Model. AutoMapper does seem to have the better syntax and feel to it, but the current version lacks a very severe topic: It is not able to perform the mapping from ViewModel to Model (under certain circumstances like flattening, etc., but this is off topic) So at present I prefer to use ValueInjecter.

So you create a ViewModel with the fields you need in the view. You add the SelectList items you need as lookups. And you add them as SelectLists already. So you can query from a LINQ enabled sourc, select the ID and text field and store it as a selectlist: You gain that you do not have to create a new type (dictionary) as lookup and you just move the new SelectList from the view to the controller.

  // StaffTypes is an IEnumerable<StaffType> from dbContext
  // viewModel is the viewModel initialized to copy content of Model Employee  
  // viewModel.StaffTypes is of type SelectList

  viewModel.StaffTypes =
    new SelectList(
        StaffTypes.OrderBy( item => item.Name )
        "StaffTypeID",
        "Type",
        viewModel.StaffTypeID
    );

In the view you just have to call

@Html.DropDownListFor( model => mode.StaffTypeID, model.StaffTypes )

Back in the post element of your method in the controller you have to take a parameter of the type of your ViewModel. You then check for validation. If the validation fails, you have to remember to re-populate the viewModel.StaffTypes SelectList, because this item will be null on entering the post function. So I tend to have those population things separated into a function. You just call back return new View(viewModel) if anything is wrong. Validation errors found by MVC3 will automatically be shown in the view.

If you have your own validation code you can add validation errors by specifying which field they belong to. Check documentation on ModelState to get info on that.

If the viewModel is valid you have to perform the next step:

If it is a create of a new item, you have to populate a model from the viewModel (best suited is ValueInjecter). Then you can add it to the EF collection of that type and commit changes.

If you have an update, you get the current db item first into a model. Then you can copy the values from the viewModel back to the model (again using ValueInjecter gets you do that very quick). After that you can SaveChanges and are done.

Feel free to ask if anything is unclear.

inline conditionals in angular.js

Works even in exotic Situations:

<br ng-show="myCondition == true" />

Wait until all jQuery Ajax requests are done?

If you want to know when all ajax requests are finished in your document, no matter how many of them exists, just use $.ajaxStop event this way:

$(document).ajaxStop(function () {
  // 0 === $.active
});

In this case, neither you need to guess how many requests are happening in the application, that might finish in the future, nor dig into functions complex logic or find which functions are doing HTTP(S) requests.

$.ajaxStop here can also be bound to any HTML node that you think might be modified by requst.


Update:
If you want to stick with ES syntax, then you can use Promise.all for known ajax methods:

Promise.all([ajax1(), ajax2()]).then(() => {
  // all requests finished successfully
}).catch(() => {
  // all requests finished but one or more failed
})

An interesting point here is that it works both with Promises and $.ajax requests.

Here is the jsFiddle demonstration.


Update 2:
Yet more recent version using async/await syntax:

try {
  const results = await Promise.all([ajax1(), ajax2()])
  // do other actions
} catch(ex) { }

R: "Unary operator error" from multiline ggplot2 command

It looks like you might have inserted an extra + at the beginning of each line, which R is interpreting as a unary operator (like - interpreted as negation, rather than subtraction). I think what will work is

ggplot(combined.data, aes(x = region, y = expression, fill = species)) +
    geom_boxplot() +
    scale_fill_manual(values = c("yellow", "orange")) + 
    ggtitle("Expression comparisons for ACTB") + 
    theme(axis.text.x = element_text(angle=90, face="bold", colour="black"))

Perhaps you copy and pasted from the output of an R console? The console uses + at the start of the line when the input is incomplete.

How to select an option from drop down using Selenium WebDriver C#?

You must create a select element object from the drop down list.

 using OpenQA.Selenium.Support.UI;

 // select the drop down list
 var education = driver.FindElement(By.Name("education"));
 //create select element object 
 var selectElement = new SelectElement(education);

 //select by value
 selectElement.SelectByValue("Jr.High"); 
 // select by text
 selectElement.SelectByText("HighSchool");

More info here

MVC - Set selected value of SelectList

Use LINQ and add the condition on the "selected" as a question mark condition.

    var listSiteId = (from site in db.GetSiteId().ToList()
                                      select new SelectListItem
                                      {
                                          Value = site.SITEID,
                                          Text = site.NAME,
                                          Selected = (dimension.DISPLAYVALUE == site.SITEID) ? true : false,
                                      }).ToList();
                    ViewBag.SiteId = listSiteId;

How do I drag and drop files into an application?

Yet another gotcha:

The framework code that calls the Drag-events swallow all exceptions. You might think your event code is running smoothly, while it is gushing exceptions all over the place. You can't see them because the framework steals them.

That's why I always put a try/catch in these event handlers, just so I know if they throw any exceptions. I usually put a Debugger.Break(); in the catch part.

Before release, after testing, if everything seems to behave, I remove or replace these with real exception handling.

Bootstrap 3: pull-right for col-lg only

Just use bootstrap's responsive utility classes!

The best solution for that task is to use the following code:

<div class="row">
    <div class="col-lg-6 col-md-6">elements 1</div>
    <div class="col-lg-6 col-md-6 text-right">
        <div class="visible-lg-inline-block visible-md-block visible-sm-block visible-xs-block">
            elements 2
        </div>
    </div>
</div>

Element will be aligned to the right only on lg screens - on the rest the display attribute will be set to block as it is by default for div element. This approach is using text-right class on the parent element instead of pull-right.

Alternative solution:

The biggest disadvantage is that the html code inside needs to be repeated twice.

<div class="row">
    <div class="col-lg-6 col-md-6">elements 1</div>
    <div class="col-lg-6 col-md-6">
         <div class="pull-right visible-lg">
            elements 2
         </div>
         <div class="hidden-lg">
            elements 2
         </div>
    </div>
</div>

Warning: mysql_connect(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock) in

Mac OS X EL Capitan + MAMP Pro Do this

cd /var
sudo mkdir mysql
sudo chmod 755 mysql
cd mysql
sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock mysql.sock

Then do this

cd /tmp
sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock mysql.sock

Hope this saves you some time.

How do I update all my CPAN modules to their latest versions?

Try perl -MCPAN -e "upgrade /(.\*)/". It works fine for me.

Automatically size JPanel inside JFrame

If the BorderLayout option provided by our friends doesnot work, try adding ComponentListerner to the JFrame and implement the componentResized(event) method. When the JFrame object will be resized, this method will be called. So if you write the the code to set the size of the JPanel in this method, you will achieve the intended result.

Ya, I know this 'solution' is not good but use it as a safety net. ;)

Get an array of list element contents in jQuery

var arr = new Array();

$('li').each(function() { 
  arr.push(this.innerHTML); 
})

Run a command shell in jenkins

Error shows that script does not exists

The file does not exists. check your full path

C:\Windows\TEMP\hudson6299483223982766034.sh
The system cannot find the file specified

Moreover, to launch .sh scripts into windows, you need to have CYGWIN installed and well configured into your path

Confirm that script exists.

Into jenkins script, do the following to confirm that you do have the file

cd C:\Windows\TEMP\
ls -rtl
sh -xe hudson6299483223982766034.sh

Convert MySQL to SQlite

If you have been given a database file and have not installed the correct server (either SQLite or MySQL), try this tool: https://dbconvert.com/sqlite/mysql/ The trial version allows converting the first 50 records of each table, the rest of the data is watermarked. This is a Windows program, and can either dump into a running database server, or can dump output to a .sql file

Are parameters in strings.xml possible?

Yes, just format your strings in the standard String.format() way.

See the method Context.getString(int, Object...) and the Android or Java Formatter documentation.

In your case, the string definition would be:

<string name="timeFormat">%1$d minutes ago</string>

Which mime type should I use for mp3

Use .mp3 audio/mpeg, that's the one I always used. I guess others are just aliases.

Git checkout: updating paths is incompatible with switching branches

For me I had a typo and my remote branch didn't exist

Use git branch -a to list remote branches

Calculating a directory's size using Python?

This walks all sub-directories; summing file sizes:

import os

def get_size(start_path = '.'):
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(start_path):
        for f in filenames:
            fp = os.path.join(dirpath, f)
            # skip if it is symbolic link
            if not os.path.islink(fp):
                total_size += os.path.getsize(fp)

    return total_size

print(get_size(), 'bytes')

And a oneliner for fun using os.listdir (Does not include sub-directories):

import os
sum(os.path.getsize(f) for f in os.listdir('.') if os.path.isfile(f))

Reference:

Updated To use os.path.getsize, this is clearer than using the os.stat().st_size method.

Thanks to ghostdog74 for pointing this out!

os.stat - st_size Gives the size in bytes. Can also be used to get file size and other file related information.

import os

nbytes = sum(d.stat().st_size for d in os.scandir('.') if d.is_file())

Update 2018

If you use Python 3.4 or previous then you may consider using the more efficient walk method provided by the third-party scandir package. In Python 3.5 and later, this package has been incorporated into the standard library and os.walk has received the corresponding increase in performance.

Update 2019

Recently I've been using pathlib more and more, here's a pathlib solution:

from pathlib import Path

root_directory = Path('.')
sum(f.stat().st_size for f in root_directory.glob('**/*') if f.is_file())

How to filter data in dataview

Eg:

Datatable newTable =  new DataTable();

            foreach(string s1 in list)
            {
                if (s1 != string.Empty) {
                    dvProducts.RowFilter = "(CODE like '" + serachText + "*') AND (CODE <> '" + s1 + "')";
                    foreach(DataRow dr in dvProducts.ToTable().Rows)
                    {
                       newTable.ImportRow(dr);
                    }
                }
            }
ListView1.DataSource = newTable;
ListView1.DataBind();

Print range of numbers on same line

Though the answer has been given for the question. I would like to add, if in case we need to print numbers without any spaces then we can use the following code

        for i in range(1,n):
            print(i,end="")

What's the point of 'meta viewport user-scalable=no' in the Google Maps API

Disabling user-scalable (namely, the ability to double tap to zoom) allows the browser to reduce the click delay. In touch-enable browsers, when the user expects the double tap to zoom, the browser generally waits 300ms before firing the click event, waiting to see if the user will double tap. Disabling user-scalable allows for the Chrome browser to fire the click event immediately, allowing for a better user experience.

From Google IO 2013 session https://www.youtube.com/watch?feature=player_embedded&v=DujfpXOKUp8#t=1435s

Update: its not true anymore, <meta name="viewport" content="width=device-width"> is enough to remove 300ms delay

How to find what code is run by a button or element in Chrome using Developer Tools

This solution needs the jQuery's data method.

  1. Open Chrome's console (although any browser with jQuery loaded will work)
  2. Run $._data($(".example").get(0), "events")
  3. Drill down the output to find the desired event handler.
  4. Right-click on "handler" and select "Show function definition"
  5. The code will be shown in the Sources tab

$._data() is just accessing jQuery's data method. A more readable alternative could be jQuery._data().

Interesting point by this SO answer:

As of jQuery 1.8, the event data is no longer available from the "public API" for data. Read this jQuery blog post. You should now use this instead:

jQuery._data( elem, "events" ); elem should be an HTML Element, not a jQuery object, or selector.

Please note, that this is an internal, 'private' structure, and shouldn't be modified. Use this for debugging purposes only.

In older versions of jQuery, you might have to use the old method which is:

jQuery( elem ).data( "events" );

A version agnostic jQuery would be: (jQuery._data || jQuery.data)(elem, 'events');

How to remove specific object from ArrayList in Java?

This helped me:

        card temperaryCardFour = theDeck.get(theDeck.size() - 1);
        theDeck.remove(temperaryCardFour);    

instead of

theDeck.remove(numberNeededRemoved);

I got a removal conformation on the first snippet of code and an un removal conformation on the second.

Try switching your code with the first snippet I think that is your problem.

Nathan Nelson

Basic Ajax send/receive with node.js

Here is a fully functional example of what you are trying to accomplish. I created the example inside of hyperdev rather than jsFiddle so that you could see the server-side and client-side code.

View Code: https://hyperdev.com/#!/project/destiny-authorization

View Working Application: https://destiny-authorization.hyperdev.space/

This code creates a handler for a get request that returns a random string:

app.get("/string", function(req, res) {
    var strings = ["string1", "string2", "string3"]
    var n = Math.floor(Math.random() * strings.length)
    res.send(strings[n])
});

This jQuery code then makes the ajax request and receives the random string from the server.

$.get("/string", function(string) {
  $('#txtString').val(string);
});

Note that this example is based on code from Jamund Ferguson's answer so if you find this useful be sure to upvote him as well. I just thought this example would help you to see how everything fits together.

Angular 5 ngHide ngShow [hidden] not working

There is two way for hide a element

  1. Use the "hidden" html attribute But in angular you can bind it with one or more fields like this :

    <input class="txt" type="password" [(ngModel)]="input_pw" [hidden]="isHidden">

2.Better way of doing this is to use " *ngIf " directive like this :

<input class="txt" type="password" [(ngModel)]="input_pw" *ngIf="!isHidden">

Now why this is a better way because it doesn't just hide the element, it will removes it from the html code so this will help your page to render.

recursion versus iteration

Most of the answers seem to assume that iterative = for loop. If your for loop is unrestricted (a la C, you can do whatever you want with your loop counter), then that is correct. If it's a real for loop (say as in Python or most functional languages where you cannot manually modify the loop counter), then it is not correct.

All (computable) functions can be implemented both recursively and using while loops (or conditional jumps, which are basically the same thing). If you truly restrict yourself to for loops, you will only get a subset of those functions (the primitive recursive ones, if your elementary operations are reasonable). Granted, it's a pretty large subset which happens to contain every single function you're likely to encouter in practice.

What is much more important is that a lot of functions are very easy to implement recursively and awfully hard to implement iteratively (manually managing your call stack does not count).

Eclipse shows errors but I can't find them

Right Click on Project -> Build Path -> Configure Build Path. Check if Maven Dependencies is there in list, if not then update maven project by Right Click on Project -> Maven -> Update Project

No generated R.java file in my project

Just Restart the Eclipse will solve this Issue as the workspace will be freshly Build ! go to

File -> Restart

Its the easiest way to avoid frustration by going it into Build,properties,blah blah.....

How do I compile the asm generated by GCC?

Yes, You can use gcc to compile your asm code. Use -c for compilation like this:

gcc -c file.S -o file.o

This will give object code file named file.o. To invoke linker perform following after above command:

gcc file.o -o file

Ruby: How to turn a hash into HTTP parameters?

The best approach it is to use Hash.to_params which is the one working fine with arrays.

{a: 1, b: [1,2,3]}.to_param
"a=1&b[]=1&b[]=2&b[]=3"

VS 2012: Scroll Solution Explorer to current file

It is possible in VSS by three ways.

  1. You can click on Active sync icon on Solution Explorer.

VSS Active sync with icon in solution Explorer

  1. By selecting Active sync checkbox in Tools (Tools > Options > Projects and Solutions > General). In that check the Track Active Item in Solution Explorer Checkbox. When you select a file in the main window, it will automatically navigate to active file in the Explorer.

VSS_Tools_Active_sync

  1. By using the Shortcut key (Ctrl + [ + S), you can able to navigate to active Item.

Note: Either 1 or 2 only works in a mean time.. So You have to use either 1st or 2nd.

Convert DateTime to a specified Format

Easy peasy:

var date = DateTime.Parse("14/11/2011"); // may need some Culture help here
Console.Write(date.ToString("yyyy-MM-dd"));

Take a look at DateTime.ToString() method, Custom Date and Time Format Strings and Standard Date and Time Format Strings

string customFormattedDateTimeString = DateTime.Now.ToString("yyyy-MM-dd");

MySQL - SELECT * INTO OUTFILE LOCAL ?

You can achieve what you want with the mysql console with the -s (--silent) option passed in.

It's probably a good idea to also pass in the -r (--raw) option so that special characters don't get escaped. You can use this to pipe queries like you're wanting.

mysql -u username -h hostname -p -s -r -e "select concat('this',' ','works')"

EDIT: Also, if you want to remove the column name from your output, just add another -s (mysql -ss -r etc.)

How do I redirect to the previous action in ASP.NET MVC?

If you are not concerned with unit testing then you can simply write:

return Redirect(ControllerContext.HttpContext.Request.UrlReferrer.ToString());

How do I list all tables in all databases in SQL Server in a single result set?

please fill the @likeTablename param for search table.

now this parameter set to %tbltrans% for search all table contain tbltrans in name.

set @likeTablename to '%' to show all table.

declare @AllTableNames nvarchar(max);

select  @AllTableNames=STUFF((select ' SELECT  TABLE_CATALOG collate DATABASE_DEFAULT+''.''+TABLE_SCHEMA collate DATABASE_DEFAULT+''.''+TABLE_NAME collate DATABASE_DEFAULT as tablename FROM '+name+'.INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = ''BASE TABLE'' union '
 FROM master.sys.databases 
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)') 
,1,1,'');

set @AllTableNames=left(@AllTableNames,len(@AllTableNames)-6)

declare @likeTablename nvarchar(200)='%tbltrans%';
set @AllTableNames=N'select tablename from('+@AllTableNames+N')at where tablename like '''+N'%'+@likeTablename+N'%'+N''''
exec sp_executesql  @AllTableNames

Displaying one div on top of another

There are many ways to do it, but this is pretty simple and avoids issues with disrupting inline content positioning. You might need to adjust for margins/padding, too.

#backdrop, #curtain {
  height: 100px;
  width: 200px;
}

#curtain {
  position: relative;
  top: -100px;
}

How do I use PHP namespaces with autoload?

I recently found tanerkuc's answer very helpful! Just wanted to add that using strrpos() + substr() is slightly faster than explode() + end():

spl_autoload_register( function( $class ) {
    $pos = strrpos( $class, '\\' );
    include ( $pos === false ? $class : substr( $class, $pos + 1 ) ).'.php';
});

Loop over html table and get checked checkboxes (JQuery)

The following code snippet enables/disables a button depending on whether at least one checkbox on the page has been checked.
$('input[type=checkbox]').change(function () {
    $('#test > tbody  tr').each(function () {
        if ($('input[type=checkbox]').is(':checked')) {
            $('#btnexcellSelect').removeAttr('disabled');
        } else {
            $('#btnexcellSelect').attr('disabled', 'disabled');
        }
        if ($(this).is(':checked')){
            console.log( $(this).attr('id'));
         }else{
             console.log($(this).attr('id'));
         }
     });
});

Here is demo in JSFiddle.

How to get the first element of an array?

Use this to split character in javascript.

var str = "boy, girl, dog, cat";
var arr = str.split(",");
var fst = arr.splice(0,1).join("");
var rest = arr.join(",");

What is the "-->" operator in C/C++?

while( x-- > 0 )

is how that's parsed.

Java get String CompareTo as a comparator object

The Arrays class has versions of sort() and binarySearch() which don't require a Comparator. For example, you can use the version of Arrays.sort() which just takes an array of objects. These methods call the compareTo() method of the objects in the array.

How to get the unix timestamp in C#

This is what I use.

 public class TimeStamp
    {
        public Int32 UnixTimeStampUTC()
        {
            Int32 unixTimeStamp;
            DateTime currentTime = DateTime.Now;
            DateTime zuluTime = currentTime.ToUniversalTime();
            DateTime unixEpoch = new DateTime(1970, 1, 1);
            unixTimeStamp = (Int32)(zuluTime.Subtract(unixEpoch)).TotalSeconds;
            return unixTimeStamp;
        }
}

Bootstrap 4, How do I center-align a button?

Use text-center class in the parent container for Bootstrap 4

How to install numpy on windows using pip install?

As of March 2016, pip install numpy works on Windows without a Fortran compiler. See here.

pip install scipy still tries to use a compiler.

July 2018: mojoken reports pip install scipy working on Windows without a Fortran compiler.

The server encountered an internal error or misconfiguration and was unable to complete your request

Check your servers error log, typically /var/log/apache2/error.log.

Copy and paste content from one file to another file in vi

The below option works most of time and also for pasting later.

 "xnyy
x - buffer name
n - number of line to Yank - optional

The lines yanked will be stored in the buffer 'x'. It can be used anywhere in the edit.

To paste line(s) in the other file,

:e filename&location

Example: Type the below command in the current edit

:e /u/test/Test2.sh
and paste using "xP
P - before cursor
p - after cursor

Complete operation

open file 1 :

vi Test1.sh

a10yy

-Yanked 10 lines

-now open the second file from the current edit

*:e /u/test/Test2.sh*

-move the cursor to the line where you have to paste

*"ap*

--Lines from the buffer '*a*' will be copied after the current cursor pos

How to remove new line characters from a string?

just do that

s = s.Replace("\n", String.Empty).Replace("\t", String.Empty).Replace("\r", String.Empty);

Prevent jQuery UI dialog from setting focus to first textbox

jQuery UI 1.10.0 Changelog lists ticket 4731 as being fixed.

Looks like focusSelector was not implemented, but a cascading search for various elements was used instead. From the ticket:

Extend autofocus, starting with [autofocus], then :tabbable content, then buttonpane, then close button, then dialog

So, mark an element with the autofocus attribute and that is the element that should get the focus:

<input autofocus>

In the documentation, the focus logic is explained (just under the table of contents, under the title 'Focus'):

Upon opening a dialog, focus is automatically moved to the first item that matches the following:

  1. The first element within the dialog with the autofocus attribute
  2. The first :tabbable element within the dialog's content
  3. The first :tabbable element within the dialog's buttonpane
  4. The dialog's close button
  5. The dialog itself

Removing leading and trailing spaces from a string

    char *str = (char*) malloc(50 * sizeof(char));
    strcpy(str, "    some random string (<50 chars)  ");

    while(*str == ' ' || *str == '\t' || *str == '\n')
            str++;

    int len = strlen(str);

    while(len >= 0 && 
            (str[len - 1] == ' ' || str[len - 1] == '\t' || *str == '\n')
    {
            *(str + len - 1) = '\0';
            len--;
    }

    printf(":%s:\n", str);

Format telephone and credit card numbers in AngularJS

I created an AngularJS module to handle this issue regarding phonenumbers for myself with a custom directive and accompanying filter.

jsfiddle example: http://jsfiddle.net/aberke/s0xpkgmq/

Filter use example: <p>{{ phonenumberValue | phonenumber }}</p>

Filter code:

.filter('phonenumber', function() {
    /* 
    Format phonenumber as: c (xxx) xxx-xxxx
        or as close as possible if phonenumber length is not 10
        if c is not '1' (country code not USA), does not use country code
    */

    return function (number) {
        /* 
        @param {Number | String} number - Number that will be formatted as telephone number
        Returns formatted number: (###) ###-####
            if number.length < 4: ###
            else if number.length < 7: (###) ###

        Does not handle country codes that are not '1' (USA)
        */
        if (!number) { return ''; }

        number = String(number);

        // Will return formattedNumber. 
        // If phonenumber isn't longer than an area code, just show number
        var formattedNumber = number;

        // if the first character is '1', strip it out and add it back
        var c = (number[0] == '1') ? '1 ' : '';
        number = number[0] == '1' ? number.slice(1) : number;

        // # (###) ###-#### as c (area) front-end
        var area = number.substring(0,3);
        var front = number.substring(3, 6);
        var end = number.substring(6, 10);

        if (front) {
            formattedNumber = (c + "(" + area + ") " + front);  
        }
        if (end) {
            formattedNumber += ("-" + end);
        }
        return formattedNumber;
    };
});

Directive use example:

<phonenumber-directive placeholder="'Input phonenumber here'" model='myModel.phonenumber'></phonenumber-directive>

Directive code:

.directive('phonenumberDirective', ['$filter', function($filter) {
    /*
    Intended use:
        <phonenumber-directive placeholder='prompt' model='someModel.phonenumber'></phonenumber-directive>
    Where:
        someModel.phonenumber: {String} value which to bind only the numeric characters [0-9] entered
            ie, if user enters 617-2223333, value of 6172223333 will be bound to model
        prompt: {String} text to keep in placeholder when no numeric input entered
    */

    function link(scope, element, attributes) {

        // scope.inputValue is the value of input element used in template
        scope.inputValue = scope.phonenumberModel;

        scope.$watch('inputValue', function(value, oldValue) {

            value = String(value);
            var number = value.replace(/[^0-9]+/g, '');
            scope.phonenumberModel = number;
            scope.inputValue = $filter('phonenumber')(number);
        });
    }

    return {
        link: link,
        restrict: 'E',
        scope: {
            phonenumberPlaceholder: '=placeholder',
            phonenumberModel: '=model',
        },
        // templateUrl: '/static/phonenumberModule/template.html',
        template: '<input ng-model="inputValue" type="tel" class="phonenumber" placeholder="{{phonenumberPlaceholder}}" title="Phonenumber (Format: (999) 9999-9999)">',
    };
}])

Full code with module and how to use it: https://gist.github.com/aberke/042eef0f37dba1138f9e

How do I catch an Ajax query post error?

Since jQuery 1.5 you can use the deferred objects mechanism:

$.post('some.php', {name: 'John'})
    .done(function(msg){  })
    .fail(function(xhr, status, error) {
        // error handling
    });

Another way is using .ajax:

$.ajax({
  type: "POST",
  url: "some.php",
  data: "name=John&location=Boston",
  success: function(msg){
        alert( "Data Saved: " + msg );
  },
  error: function(XMLHttpRequest, textStatus, errorThrown) {
     alert("some error");
  }
});

All combinations of a list of lists

Numpy can do it:

 >>> import numpy
 >>> a = [[1,2,3],[4,5,6],[7,8,9,10]]
 >>> [list(x) for x in numpy.array(numpy.meshgrid(*a)).T.reshape(-1,len(a))]
[[ 1, 4, 7], [1, 5, 7], [1, 6, 7], ....]

ORA-01652: unable to extend temp segment by 128 in tablespace SYSTEM: How to extend?

Each tablespace has one or more datafiles that it uses to store data.

The max size of a datafile depends on the block size of the database. I believe that, by default, that leaves with you with a max of 32gb per datafile.

To find out if the actual limit is 32gb, run the following:

select value from v$parameter where name = 'db_block_size';

Compare the result you get with the first column below, and that will indicate what your max datafile size is.

I have Oracle Personal Edition 11g r2 and in a default install it had an 8,192 block size (32gb per data file).

Block Sz   Max Datafile Sz (Gb)   Max DB Sz (Tb)

--------   --------------------   --------------

   2,048                  8,192          524,264

   4,096                 16,384        1,048,528

   8,192                 32,768        2,097,056

  16,384                 65,536        4,194,112

  32,768                131,072        8,388,224

You can run this query to find what datafiles you have, what tablespaces they are associated with, and what you've currrently set the max file size to (which cannot exceed the aforementioned 32gb):

select bytes/1024/1024 as mb_size,
       maxbytes/1024/1024 as maxsize_set,
       x.*
from   dba_data_files x

MAXSIZE_SET is the maximum size you've set the datafile to. Also relevant is whether you've set the AUTOEXTEND option to ON (its name does what it implies).

If your datafile has a low max size or autoextend is not on you could simply run:

alter database datafile 'path_to_your_file\that_file.DBF' autoextend on maxsize unlimited;

However if its size is at/near 32gb an autoextend is on, then yes, you do need another datafile for the tablespace:

alter tablespace system add datafile 'path_to_your_datafiles_folder\name_of_df_you_want.dbf' size 10m autoextend on maxsize unlimited;

git push vs git push origin <branchname>

The first push should be a:

git push -u origin branchname

That would make sure:

Any future git push will, with that default policy, only push the current branch, and only if that branch has an upstream branch with the same name.
that avoid pushing all matching branches (previous default policy), where tons of test branches were pushed even though they aren't ready to be visible on the upstream repo.

Android set height and width of Custom view programmatically

This is a Kotlin based version, assuming that the parent view is an instance of LinearLayout.

someView.layoutParams = LinearLayout.LayoutParams(100, 200)

This allows to set the width and height (100 and 200) in a single line.

Absolute positioning ignoring padding of parent

First, let's see why this is happening.

The reason is that, surprisingly, when a box has position: absolute its containing box is the parent's padding box (that is, the box around its padding). This is surprising because usually (that is, when using static or relative positioning) the containing box is the parent's content box.

Here is the relevant part of the CSS specification:

In the case that the ancestor is an inline element, the containing block is the bounding box around the padding boxes of the first and the last inline boxes generated for that element.... Otherwise, the containing block is formed by the padding edge of the ancestor.

The simplest approach—as suggested in Winter's answer—is to use padding: inherit on the absolutely positioned div. It only works, though, if you don't want the absolutely positioned div to have any additional padding of its own. I think the most general-purpose solutions (in that both elements can have their own independent padding) are:

  1. Add an extra relatively positioned div (with no padding) around the absolutely positioned div. That new div will respect the padding of its parent, and the absolutely positioned div will then fill it.

    The downside, of course, is that you're messing with the HTML simply for presentational purposes.

  2. Repeat the padding (or add to it) on the absolutely positioned element.

    The downside here is that you have to repeat the values in your CSS, which is brittle if you're writing the CSS directly. However, if you're using a pre-processing tool like SASS or LESS you can avoid that problem by using a variable. This is the method I personally use.

Changing navigation title programmatically

Swift 5.1

override func viewDidLoad() {
    super.viewDidLoad()
    navigationItem.title = "What ever you want"
}

Python string prints as [u'String']

[u'ABC'] would be a one-element list of unicode strings. Beautiful Soup always produces Unicode. So you need to convert the list to a single unicode string, and then convert that to ASCII.

I don't know exaxtly how you got the one-element lists; the contents member would be a list of strings and tags, which is apparently not what you have. Assuming that you really always get a list with a single element, and that your test is really only ASCII you would use this:

 soup[0].encode("ascii")

However, please double-check that your data is really ASCII. This is pretty rare. Much more likely it's latin-1 or utf-8.

 soup[0].encode("latin-1")


 soup[0].encode("utf-8")

Or you ask Beautiful Soup what the original encoding was and get it back in this encoding:

 soup[0].encode(soup.originalEncoding)

How to create a simple proxy in C#?

Proxy can work in the following way.

Step1, configure client to use proxyHost:proxyPort.

Proxy is a TCP server that is listening on proxyHost:proxyPort. Browser opens connection with Proxy and sends Http request. Proxy parses this request and tries to detect "Host" header. This header will tell Proxy where to open connection.

Step 2: Proxy opens connection to the address specified in the "Host" header. Then it sends HTTP request to that remote server. Reads response.

Step 3: After response is read from remote HTTP server, Proxy sends the response through an earlier opened TCP connection with browser.

Schematically it will look like this:

Browser                            Proxy                     HTTP server
  Open TCP connection  
  Send HTTP request  ----------->                       
                                 Read HTTP header
                                 detect Host header
                                 Send request to HTTP ----------->
                                 Server
                                                      <-----------
                                 Read response and send
                   <-----------  it back to the browser
Render content

How to name variables on the fly?

Use assign:

assign(paste("orca", i, sep = ""), list_name[[i]])

Is it possible to animate scrollTop with jQuery?

You can just use .animate() the scrollTop property, like this:

$("html, body").animate({ scrollTop: "300px" });

Initializing multiple variables to the same value in Java

Works for primitives and immutable classes like String, Wrapper classes Character, Byte.

int i=0,j=2   
String s1,s2  
s1 = s2 = "java rocks"

For mutable classes

Reference r1 = Reference r2 = Reference r3 = new Object();`  

Three references + one object are created. All references point to the same object and your program will misbehave.

MySQL: How to set the Primary Key on phpMyAdmin?

MySQL can index the first x characters of a column,but a TEXT type is of variable length so mysql cant assure the uniqueness of the column.If you still want text column,use VARCHAR.

What reference do I need to use Microsoft.Office.Interop.Excel in .NET?

Here is super solid solution, you just need have excell.dll in your Debug/Release folder Mine is 77,824 bytes, I downloaded it as a file, this also explain why some people have Debug compiled but Release not or vice versa.

Trento

Get SELECT's value and text in jQuery

<select id="ddlViewBy">
    <option value="value">text</option>
</select>

JQuery

var txt = $("#ddlViewBy option:selected").text();
var val = $("#ddlViewBy option:selected").val();

JS Fiddle DEMO

Finding element in XDocument?

The problem is that Elements only takes the direct child elements of whatever you call it on. If you want all descendants, use the Descendants method:

var query = from c in xmlFile.Descendants("Band")

jQuery append() and remove() element

You can call a reset function before appending. Something like this:

    function resetNewReviewBoardForm() {
    $("#Description").val('');
    $("#PersonName").text('');
    $("#members").empty(); //this one what worked in my case
    $("#EmailNotification").val('False');
}

What precisely does 'Run as administrator' do?

UPDATE

"Run as Aministrator" is just a command, enabling the program to continue some operations that require the Administrator privileges, without displaying the UAC alerts.

Even if your user is a member of administrators group, some applications like yours need the Administrator privileges to continue running, because the application is considered not safe, if it is doing some special operation, like editing a system file or something else. This is the reason why Windows needs the Administrator privilege to execute the application and it notifies you with a UAC alert. Not all applications need an Amnistrator account to run, and some applications, like yours, need the Administrator privileges.

If you execute the application with 'run as administrator' command, you are notifying the system that your application is safe and doing something that requires the administrator privileges, with your confirm.

If you want to avoid this, just disable the UAC on Control Panel.

If you want to go further, read the question Difference between "Run as Administrator" and Windows 7 Administrators Group on Microsoft forum or this SuperUser question.

Activity <App Name> has leaked ServiceConnection <ServiceConnection Name>@438030a8 that was originally bound here

Every service that is bound in activity must be unbind on app close.

So try using

 onPause(){
   unbindService(YOUR_SERVICE);
   super.onPause();
 }

FragmentActivity to Fragment

first of all;

a Fragment must be inside a FragmentActivity, that's the first rule,

a FragmentActivity is quite similar to a standart Activity that you already know, besides having some Fragment oriented methods

second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView, where you inflate your layout, think of it as the setContentLayout

here is an example:

    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {     mView       = inflater.inflate(R.layout.fragment_layout, container, false);       return mView; } 

and continu your work based on that mView, so to find a View by id, call mView.findViewById(..);


for the FragmentActivity part:

the xml part "must" have a FrameLayout in order to inflate a fragment in it

        <FrameLayout             android:id="@+id/content_frame"             android:layout_width="match_parent"             android:layout_height="match_parent"  >         </FrameLayout> 

as for the inflation part

getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();


begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site

Splitting applicationContext to multiple files

@eljenso : intrafest-servlet.xml webapplication context xml will be used if the application uses SPRING WEB MVC.

Otherwise the @kosoant configuration is fine.

Simple example if you dont use SPRING WEB MVC, but want to utitlize SPRING IOC :

In web.xml:

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:application-context.xml</param-value>
</context-param>

Then, your application-context.xml will contain: <import resource="foo-services.xml"/> these import statements to load various application context files and put into main application-context.xml.

Thanks and hope this helps.

gem install: Failed to build gem native extension (can't find header files)

It's necessary to install redhat-rpm-config to. I guess it solve your problem!

SVN change username

I believe you could create you own branch (using your own credential) from the same trunk as your workmate's branch, merge from your workmate's branch to your working copy and then merge from your branch. All future commit should be marked as coming from you.

How to make the tab character 4 spaces instead of 8 spaces in nano?

For future viewers, there is a line in my /etc/nanorc file close to line 153 that says "set tabsize 8". The word might need to be tabsize instead of tabspace. After I replaced 8 with 4 and uncommented the line, it solved my problem.

Getting random numbers in Java

The first solution is to use the java.util.Random class:

import java.util.Random;

Random rand = new Random();

// Obtain a number between [0 - 49].
int n = rand.nextInt(50);

// Add 1 to the result to get a number from the required range
// (i.e., [1 - 50]).
n += 1;

Another solution is using Math.random():

double random = Math.random() * 49 + 1;

or

int random = (int)(Math.random() * 50 + 1);

Add CSS class to a div in code behind

<div runat="server"> is mapped to a HtmlGenericControl. Try using BtnventCss.Attributes.Add("class", "hom_but_a");

Regular Expression to match valid dates

I know this does not answer your question, but why don't you use a date handling routine to check if it's a valid date? Even if you modify the regexp with a negative lookahead assertion like (?!31/0?2) (ie, do not match 31/2 or 31/02) you'll still have the problem of accepting 29 02 on non leap years and about a single separator date format.

The problem is not easy if you want to really validate a date, check this forum thread.

For an example or a better way, in C#, check this link

If you are using another platform/language, let us know

How to make tesseract to recognize only numbers, when they are mixed with letters?

This feature is not supported in version 4. You can still use it via -c tessedit_char_whitelist=0123456789 with "--oem 0" which reverts to the old model.

There is a bounty to fix this issue.

Possible workarounds:

As stated by @amitdo

jQuery - on change input text

This technique is working for me:

$('#myInputFieldId').bind('input',function(){ 
               alert("Hello");
    });

Note that according to this JQuery doc, "on" is recommended rather than bind in newer versions.

Is < faster than <=?

At the very least, if this were true a compiler could trivially optimise a <= b to !(a > b), and so even if the comparison itself were actually slower, with all but the most naive compiler you would not notice a difference.

Is it possible to access to google translate api for free?

Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.

UPD 19.03.2019 Here is a version for browser on GitHub.

javascript - match string against the array of regular expressions

You can join all regular expressions into single one. This way the string is scanned only once. Even with a sligthly more complex regular expression.

var thisExpressions = [ /something/, /something_else/, /and_something_else/];
var thisString = 'else';


function matchInArray(str, expr) {
    var fullExpr = new RegExp(expr
        .map(x=>x.source) // Just if you need to provide RegExp instances instead of strings or ...
        // .map(x=>x.substring(1, x.length -2)  // ...if you need to provide strings enclosed by "/" like in original question.
        .join("|")
    )
    return str.match(fullExpr);

};


if (matchInArray(thisString, thisExpressions)) {
    console.log ("Match!!");
} 

In fact, even with this approach, if you need check the same expression set against multiple strings, this is a few suboptimal because you are building (and compiling) the same regular expression each time the function is called.

Better approach would be to use a function builder like this:

var thisExpressions = [ /something/, /something_else/, /and_something_else/];
var thisString = 'else';

function matchInArray_builder(expr) {
    var fullExpr = new RegExp(expr
        .map(x=>x.source) // Just if you need to provide RegExp instances instead of strings or ...
        // .map(x=>x.substring(1, x.length -2)  // ...if you need to provide strings enclosed by "/" like in original question.
        .join("|")
    )   

    return function (str) {
        return str.match(fullExpr);

    };
};  

var matchInArray = matchInArray_builder(thisExpressions);

if (matchInArray(thisString)) {
    console.log ("Match!!");
} 

internet explorer 10 - how to apply grayscale filter?

Use this jQuery plugin https://gianlucaguarini.github.io/jQuery.BlackAndWhite/

That seems to be the only one cross-browser solution. Plus it has a nice fade in and fade out effect.

$('.bwWrapper').BlackAndWhite({
    hoverEffect : true, // default true
    // set the path to BnWWorker.js for a superfast implementation
    webworkerPath : false,
    // to invert the hover effect
    invertHoverEffect: false,
    // this option works only on the modern browsers ( on IE lower than 9 it remains always 1)
    intensity:1,
    speed: { //this property could also be just speed: value for both fadeIn and fadeOut
        fadeIn: 200, // 200ms for fadeIn animations
        fadeOut: 800 // 800ms for fadeOut animations
    },
    onImageReady:function(img) {
        // this callback gets executed anytime an image is converted
    }
});

Simple prime number generator in Python

SymPy is a Python library for symbolic mathematics. It provides several functions to generate prime numbers.

isprime(n)              # Test if n is a prime number (True) or not (False).

primerange(a, b)        # Generate a list of all prime numbers in the range [a, b).
randprime(a, b)         # Return a random prime number in the range [a, b).
primepi(n)              # Return the number of prime numbers less than or equal to n.

prime(nth)              # Return the nth prime, with the primes indexed as prime(1) = 2. The nth prime is approximately n*log(n) and can never be larger than 2**n.
prevprime(n, ith=1)     # Return the largest prime smaller than n
nextprime(n)            # Return the ith prime greater than n

sieve.primerange(a, b)  # Generate all prime numbers in the range [a, b), implemented as a dynamically growing sieve of Eratosthenes. 

Here are some examples.

>>> import sympy
>>> 
>>> sympy.isprime(5)
True
>>> list(sympy.primerange(0, 100))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
>>> sympy.randprime(0, 100)
83
>>> sympy.randprime(0, 100)
41
>>> sympy.prime(3)
5
>>> sympy.prevprime(50)
47
>>> sympy.nextprime(50)
53
>>> list(sympy.sieve.primerange(0, 100))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

HTML CSS Button Positioning

Use margins instead of line-height and then apply float to the buttons. By default they are displaying as inline-block, so when one is pushed down the hole line is pushed down with him. Float fixes this:

#header button {
    float:left;
}

Here's a working jsfidle.

How to make a WPF window be on top of all other windows of my app (not system wide)?

The best way is set this two events to all of windows of your app:

GotKeyboardFocus
LostKeyboardFocus

in this way:

WiondowOfMyApp_GotKeyboardFocus(object sender, System.Windows.Input.KeyboardFocusChangedEventArgs e)
{
    windowThatShouldBeTopMost.TopMost = true;
}

WiondowOfMyApp_LostKeyboardFocus(object sender, System.Windows.Input.KeyboardFocusChangedEventArgs e)
{
    windowThatShouldBeTopMost.TopMost = false;
}
  • and surely all of the windows that you wanted to be top, should be accessible from other windows of your app. in my case I have a base window and another some windows that should be top of my base window, so this was not bad to my base window has instance of each another windows.

What does 'stale file handle' in Linux mean?

When the directory is deleted, the inode for that directory (and the inodes for its contents) are recycled. The pointer your shell has to that directory's inode (and its contents's inodes) are now no longer valid. When the directory is restored from backup, the old inodes are not (necessarily) reused; the directory and its contents are stored on random inodes. The only thing that stays the same is that the parent directory reuses the same name for the restored directory (because you told it to).

Now if you attempt to access the contents of the directory that your original shell is still pointing to, it communicates that request to the file system as a request for the original inode, which has since been recycled (and may even be in use for something entirely different now). So you get a stale file handle message because you asked for some nonexistent data.

When you perform a cd operation, the shell reevaluates the inode location of whatever destination you give it. Now that your shell knows the new inode for the directory (and the new inodes for its contents), future requests for its contents will be valid.

Check if a number is a perfect square

A variant of @Alex Martelli's solution without set

When x in seen is True:

  • In most cases, it is the last one added, e.g. 1022 produces the x's sequence 511, 256, 129, 68, 41, 32, 31, 31;
  • In some cases (i.e., for the predecessors of perfect squares), it is the second-to-last one added, e.g. 1023 produces 511, 256, 129, 68, 41, 32, 31, 32.

Hence, it suffices to stop as soon as the current x is greater than or equal to the previous one:

def is_square(n):
    assert n > 1
    previous = n
    x = n // 2
    while x * x != n:
        x = (x + (n // x)) // 2
        if x >= previous:
            return False
        previous = x
    return True

x = 12345678987654321234567 ** 2
assert not is_square(x-1)
assert is_square(x)
assert not is_square(x+1)

Equivalence with the original algorithm tested for 1 < n < 10**7. On the same interval, this slightly simpler variant is about 1.4 times faster.

Post an object as data using Jquery Ajax

Is not necessary to pass the data as JSON string, you can pass the object directly, without defining contentType or dataType, like this:

$.ajax({
    type: "POST",
    url: "TelephoneNumbers.aspx/DeleteNumber",
    data: data0,

    success: function(data)
    {
        alert('Done');
    }
});

Check if a string is palindrome

I'm no c++ guy, but you should be able to get the gist from this.

public static string Reverse(string s) {
    if (s == null || s.Length < 2) {
        return s;
    }

    int length = s.Length;
    int loop = (length >> 1) + 1;
    int j;
    char[] chars = new char[length];
    for (int i = 0; i < loop; i++) {
        j = length - i - 1;
        chars[i] = s[j];
        chars[j] = s[i];
    }
    return new string(chars);
}

shell init issue when click tab, what's wrong with getcwd?

Just change the directory to another one and come back. Probably that one has been deleted or moved.

Get Application Name/ Label via ADB Shell or Terminal

adb shell pm list packages will give you a list of all installed package names.

You can then use dumpsys | grep -A18 "Package \[my.package\]" to grab the package information such as version identifiers etc

Excel doesn't update value unless I hit Enter

Found the problem and couldn't find the solution until tried this.

  1. Open Visual Basic from Developer tab (OR right-click at any sheet and click 'View code')
  2. At upper left panel, select 'ThisWorkbook'
  3. At lower left panel, find 'ForceFullCalculation' attribute
  4. Change it from 'False' to 'True' and save it

I'm not sure if this has any side-effect, but it is work for me now.

Does Python have a ternary conditional operator?

Yes, it was added in version 2.5. The expression syntax is:

a if condition else b

First condition is evaluated, then exactly one of either a or b is evaluated and returned based on the Boolean value of condition. If condition evaluates to True, then a is evaluated and returned but b is ignored, or else when b is evaluated and returned but a is ignored.

This allows short-circuiting because when condition is true only a is evaluated and b is not evaluated at all, but when condition is false only b is evaluated and a is not evaluated at all.

For example:

>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'

Note that conditionals are an expression, not a statement. This means you can't use assignment statements or pass or other statements within a conditional expression:

>>> pass if False else x = 3
  File "<stdin>", line 1
    pass if False else x = 3
          ^
SyntaxError: invalid syntax

You can, however, use conditional expressions to assign a variable like so:

x = a if True else b

Think of the conditional expression as switching between two values. It is very useful when you're in a 'one value or another' situation, it but doesn't do much else.

If you need to use statements, you have to use a normal if statement instead of a conditional expression.


Keep in mind that it's frowned upon by some Pythonistas for several reasons:

  • The order of the arguments is different from those of the classic condition ? a : b ternary operator from many other languages (such as C, C++, Go, Perl, Ruby, Java, Javascript, etc.), which may lead to bugs when people unfamiliar with Python's "surprising" behaviour use it (they may reverse the argument order).
  • Some find it "unwieldy", since it goes contrary to the normal flow of thought (thinking of the condition first and then the effects).
  • Stylistic reasons. (Although the 'inline if' can be really useful, and make your script more concise, it really does complicate your code)

If you're having trouble remembering the order, then remember that when read aloud, you (almost) say what you mean. For example, x = 4 if b > 8 else 9 is read aloud as x will be 4 if b is greater than 8 otherwise 9.

Official documentation:

How to access the php.ini file in godaddy shared hosting linux

It's an older question, but if anyone has a problem with setting this, their documentation is outdated. I made a copy of the php.ini file named php5.ini and now it works.

Spaces in URLs?

A URL must not contain a literal space. It must either be encoded using the percent-encoding or a different encoding that uses URL-safe characters (like application/x-www-form-urlencoded that uses + instead of %20 for spaces).

But whether the statement is right or wrong depends on the interpretation: Syntactically, a URI must not contain a literal space and it must be encoded; semantically, a %20 is not a space (obviously) but it represents a space.

How do I set the default font size in Vim?

The other answers are what you asked about, but in case it’s useful to anyone else, here’s how to set the font conditionally from the screen DPI (Windows only):

set guifont=default
if has('windows')
    "get dpi, strip out utf-16 garbage and new lines
    "system() converts 0x00 to 0x01 for 'platform independence'
    "should return something like 'PixelsPerXLogicalInch=192'
    "get the part from the = to the end of the line (eg '=192') and strip
    "the first character
    "and convert to a number
    let dpi = str2nr(strpart(matchstr(substitute(
        \system('wmic desktopmonitor get PixelsPerXLogicalInch /value'),
        \'\%x01\|\%x0a\|\%x0a\|\%xff\|\%xfe', '', 'g'),
        \'=.*$'), 1))
    if dpi > 100
        set guifont=high_dpi_font
    endif
endif

How can I get all sequences in an Oracle database?

select sequence_owner, sequence_name from dba_sequences;


DBA_SEQUENCES -- all sequences that exist 
ALL_SEQUENCES  -- all sequences that you have permission to see 
USER_SEQUENCES  -- all sequences that you own

Note that since you are, by definition, the owner of all the sequences returned from USER_SEQUENCES, there is no SEQUENCE_OWNER column in USER_SEQUENCES.