Programs & Examples On #Commonj

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.

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

You must use a .ts file - e.g. test.ts to get Typescript validation, intellisense typing of vars, return types, as well as "typed" error checking (e.g. passing a string to a method that expects an number param will error out).

It will be transpiled into (standard) .js via tsc.


Update (11/2018):

Clarification needed based on down-votes, very helpful comments and other answers.

types

  • Yes, you can do type checking in VS Code in .js files with @ts-check - as shown in the animation

  • What I originally was referring to for Typescript types is something like this in .ts which isn't quite the same thing:

    hello-world.ts

    function hello(str: string): string {
      return 1;
    }
    
    function foo(str:string):void{
       console.log(str);
    }
    

    This will not compile. Error: Type "1" is not assignable to String

  • if you tried this syntax in a Javascript hello-world.js file:

    //@ts-check
    
    function hello(str: string): string {
      return 1;
    }
    
    function foo(str:string):void{
       console.log(str);
    }
    

    The error message referenced by OP is shown: [js] 'types' can only be used in a .ts file

If there's something I missed that covers this as well as the OP's context, please add. Let's all learn.

How to disable a ts rule for a specific line?

@ts-expect-error

TS 3.9 introduces a new magic comment. @ts-expect-error will:

  • have same functionality as @ts-ignore
  • trigger an error, if actually no compiler error has been suppressed (= indicates useless flag)
if (false) {
  // @ts-expect-error: Let's ignore a single compiler error like this unreachable code 
  console.log("hello"); // compiles
}

// If @ts-expect-error didn't suppress anything at all, we now get a nice warning 
let flag = true;
// ...
if (flag) {
  // @ts-expect-error
  // ^~~~~~~~~~~~~~~^ error: "Unused '@ts-expect-error' directive.(2578)"
  console.log("hello"); 
}

Alternatives

@ts-ignore and @ts-expect-error can be used for all sorts of compiler errors. For type issues (like in OP), I recommend one of the following alternatives due to narrower error suppression scope:

? Use any type

// type assertion for single expression
delete ($ as any).summernote.options.keyMap.pc.TAB;

// new variable assignment for multiple usages
const $$: any = $
delete $$.summernote.options.keyMap.pc.TAB;
delete $$.summernote.options.keyMap.mac.TAB;

? Augment JQueryStatic interface

// ./global.d.ts
interface JQueryStatic {
  summernote: any;
}

// ./main.ts
delete $.summernote.options.keyMap.pc.TAB; // works

In other cases, shorthand module declarations or module augmentations for modules with no/extendable types are handy utilities. A viable strategy is also to keep not migrated code in .js and use --allowJs with checkJs: false.

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

Well, this might be counter-intuitive but I solved this adding esnext to my lib.

{
  "compilerOptions": {
    "lib": [
        "esnext"
    ],
    "target": "es5",
  }
}

The FIX, as suggested by the compiler is to

Try changing the lib compiler option to es2015 or later.

Typescript ReferenceError: exports is not defined

If you are just using interfaces for types, leave out the export keyword and ts can pick up on the types without needing to import. They key is you cannot use import/export anywhere.

export interface Person {
   name: string;
   age: number;
}

into

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

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

I'm not using TypeScript in this project at all so it's quite frustrating having to deal with this. I fixed this by adding a tsconfig.json and an empty file.ts file to the project root. The tsconfig.json contains this:

{
  "compilerOptions": {

    "allowJs": false,
    "noEmit": true // Do not compile the JS (or TS) files in this project on build

  },
  "compileOnSave": false,
  "exclude": [ "src", "wwwroot" ],
  "include": [ "file.ts" ]
}

Visual Studio Code Automatic Imports

I am using 'ImportJS' plugin by Devin Abbott for auto import and you can install this using below code

npm install --global import-js

tsc throws `TS2307: Cannot find module` for a local file

Don't use: import UserController from "api/xxxx" Should be: import UserController from "./api/xxxx"

NPM vs. Bower vs. Browserify vs. Gulp vs. Grunt vs. Webpack

What is webpack & webpack-dev-server? Official documentation says it's a module bundler but for me it's just a task runner. What's the difference?

webpack-dev-server is a live reloading web server that Webpack developers use to get immediate feedback what they do. It should only be used during development.

This project is heavily inspired by the nof5 unit test tool.

Webpack as the name implies will create a SINGLE package for the web. The package will be minimized, and combined into a single file (we still live in HTTP 1.1 age). Webpack does the magic of combining the resources (JavaScript, CSS, images) and injecting them like this: <script src="assets/bundle.js"></script>.

It can also be called module bundler because it must understand module dependencies, and how to grab the dependencies and to bundle them together.

Where would you use browserify? Can't we do the same with node/ES6 imports?

You could use Browserify on the exact same tasks where you would use Webpack. – Webpack is more compact, though.

Note that the ES6 module loader features in Webpack2 are using System.import, which not a single browser supports natively.

When would you use gulp/grunt over npm + plugins?

You can forget Gulp, Grunt, Brokoli, Brunch and Bower. Directly use npm command line scripts instead and you can eliminate extra packages like these here for Gulp:

var gulp        = require('gulp'),
  minifyCSS     = require('gulp-minify-css'),
  sass          = require('gulp-sass'),
  browserify    = require('gulp-browserify'),
  uglify        = require('gulp-uglify'),
  rename        = require('gulp-rename'),
  jshint        = require('gulp-jshint'),
  jshintStyle   = require('jshint-stylish'),
  replace       = require('gulp-replace'),
  notify        = require('gulp-notify'),

You can probably use Gulp and Grunt config file generators when creating config files for your project. This way you don't need to install Yeoman or similar tools.

Webpack not excluding node_modules

Try use absolute path:

exclude:path.resolve(__dirname, "node_modules")

Confusing "duplicate identifier" Typescript error message

If you have installed typings separately under typings folder

{
  "exclude": [
    "node_modules",
    "typings"
  ]
}

Relation between CommonJS, AMD and RequireJS?

CommonJS is more than that - it's a project to define a common API and ecosystem for JavaScript. One part of CommonJS is the Module specification. Node.js and RingoJS are server-side JavaScript runtimes, and yes, both of them implement modules based on the CommonJS Module spec.

AMD (Asynchronous Module Definition) is another specification for modules. RequireJS is probably the most popular implementation of AMD. One major difference from CommonJS is that AMD specifies that modules are loaded asynchronously - that means modules are loaded in parallel, as opposed to blocking the execution by waiting for a load to finish.

AMD is generally more used in client-side (in-browser) JavaScript development due to this, and CommonJS Modules are generally used server-side. However, you can use either module spec in either environment - for example, RequireJS offers directions for running in Node.js and browserify is a CommonJS Module implementation that can run in the browser.

Difference between "module.exports" and "exports" in the CommonJs Module System

node does something like this:

module.exports = exports = {}

module.exports and exports refer to same object.

This is done just for convenience. so instead of writing something like this

module.exports.PI = 3.14

we can write

exports.PI = 3.14

so it is ok to add a property to exports but assigning it to a different object is not ok

exports.add = function(){
.
.
} 

? this is OK and same as module.exports.add = function(){...}

exports = function(){
.
.
} 

? this is not ok and and empty object will be returned as module.exports still refers to {} and exports refer to different object.

How do I define global variables in CoffeeScript?

You can pass -b option when you compile code via coffee-script under node.js. The compiled code will be the same as on coffeescript.org.

How can I reuse a navigation bar on multiple pages?

You can use php for making multi-page website.

  • Create a header.php in which you should put all your html code for menu's and social media etc
  • Insert header.php in your index.php using following code

<? php include 'header.php'; ?>

(Above code will dump all html code before this)Your site body content.

  • Similarly you can create footer and other elements with ease. PHP built-in support html code in their extensions. So, better learn this easy fix.

Print array to a file

test.php

<?php  
return [
   'my_key_1'=>'1111111',
   'my_key_2'=>'2222222',
];

index.php

// Read array from file
$my_arr = include './test.php';

$my_arr["my_key_1"] = "3333333";

echo write_arr_to_file($my_arr, "./test.php");

/**
* @param array $arr <p>array</p>
* @param string $path <p>path to file</p>
* example :: "./test.php"
* @return bool <b>FALSE</b> occurred error
* more info: about "file_put_contents" https://www.php.net/manual/ru/function.file-put-contents.php
**/
function write_arr_to_file($arr, $path){
    $data = "\n";
    foreach ($arr as $key => $value) {
        $data = $data."   '".$key."'=>'".$value."',\n";
    }
    return file_put_contents($path, "<?php  \nreturn [".$data."];");
}

No connection string named 'MyEntities' could be found in the application config file

  1. Add an App.Config file
  2. Set the project as startup project.
  3. Make sure you add the connection strings after entityFramework section:

    <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
    
    </configSections>
    
    <connectionStrings>
       <!-- your connection string goes here, after configSection -->
    </connectionString>
    

phpmailer - The following SMTP Error: Data not accepted

I was hitting this error with phpMailer + Amazon SES. The phpMailer error is not very descriptive:

2: message: SERVER -> CLIENT: 554 Transaction failed: Expected ';', got "\"
1: message: 
2: message: SMTP Error: data not accepted.

For me the issue was simply that I had the following as content type:

$phpmailer->ContentType = 'text/html; charset=utf-8\r\n';

But that it shouldn't have the linebreak in it:

$phpmailer->ContentType = 'text/html; charset=utf-8';

... I suspect this was legacy code from our older version. So basically, triple check every $phpmailer setting you're adding - the smallest detail counts.

Disable cache for some images

i had this problem and overcoming like this.

var newtags='<div class="addedimage"><h5>preview image</h5><img src="'+one+'?nocache='+Math.floor(Math.random() * 1000)+'"></div>';

How do you set CMAKE_C_COMPILER and CMAKE_CXX_COMPILER for building Assimp for iOS?

The cc and cxx is located inside /Applications/Xcode.app. This should find the right paths

export CXX=`xcrun -find c++`
export CC=`xcrun -find cc`

How do I request and process JSON with python?

For anything with requests to URLs you might want to check out requests. For JSON in particular:

>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...

Fully custom validation error message with Rails

One solution might be to change the i18n default error format:

en:
  errors:
    format: "%{message}"

Default is format: %{attribute} %{message}

How to display Toast in Android?

If it's fragment,

Toast.makeText(getActivity(), "this is my Toast message!!! =)",
                   Toast.LENGTH_LONG).show();

How to download the latest artifact from Artifactory repository?

If you want to download the latest jar between 2 repositores, you can use this solution. I actually use it within my Jenkins pipeline, it works perfectly. Let's say you have a plugins-release-local and plugins-snapshot-local and you want to download the latest jar between these. Your shell script should look like this

NOTE : I use jfrog cli and it's configured with my Artifactory server.

Use case : Shell script

# your repo, you can change it then or pass an argument to the script
# repo = $1 this get the first arg passed to the script
repo=plugins-snapshot-local
# change this by your artifact path, or pass an argument $2
artifact=kshuttle/ifrs16
path=$repo/$artifact
echo $path
~/jfrog rt download --flat $path/maven-metadata.xml version/
version=$(cat version/maven-metadata.xml | grep latest | sed "s/.*<latest>\([^<]*\)<\/latest>.*/\1/")
echo "VERSION $version"
~/jfrog rt download --flat $path/$version/maven-metadata.xml build/
build=$(cat  build/maven-metadata.xml | grep '<value>' | head -1 | sed "s/.*<value>\([^<]*\)<\/value>.*/\1/")
echo "BUILD $build"
# change this by your app name, or pass an argument $3
name=ifrs16
jar=$name-$build.jar
url=$path/$version/$jar

# Download
echo $url
~/jfrog rt download --flat $url

Use case : Jenkins Pipeline

def getLatestArtifact(repo, pkg, appName, configDir){
    sh """
        ~/jfrog rt download --flat $repo/$pkg/maven-metadata.xml $configDir/version/
        version=\$(cat $configDir/version/maven-metadata.xml | grep latest | sed "s/.*<latest>\\([^<]*\\)<\\/latest>.*/\\1/")
        echo "VERSION \$version"
        ~/jfrog rt download --flat $repo/$pkg/\$version/maven-metadata.xml $configDir/build/
        build=\$(cat  $configDir/build/maven-metadata.xml | grep '<value>' | head -1 | sed "s/.*<value>\\([^<]*\\)<\\/value>.*/\\1/")
        echo "BUILD \$build"
        jar=$appName-\$build.jar
        url=$repo/$pkg/\$version/\$jar

        # Download
        echo \$url
        ~/jfrog rt download --flat \$url
    """
}

def clearDir(dir){
    sh """
        rm -rf $dir/*
    """

}

node('mynode'){
    stage('mysstage'){
        def repos =  ["plugins-snapshot-local","plugins-release-local"]

        for (String repo in repos) {
            getLatestArtifact(repo,"kshuttle/ifrs16","ifrs16","myConfigDir/")
        }
        //optional
        clearDir("myConfigDir/")
    }
}

This helps alot when you want to get the latest package between 1 or more repos. Hope it helps u too! For more Jenkins scripted pipelines info, visit Jenkins docs.

Ajax using https on an http page

You could attempt to load the the https page in an iframe and route all ajax requests in/out of the frame via some bridge, it's a hackaround but it might work (not sure if it will impose the same access restrictions given the secure context). Otherwise a local http proxy to reroute requests (like any cross domain calls) would be the accepted solution.

Changing button color programmatically

Probably best to change the className:

document.getElementById("button").className = 'button_color';

Then you add a buton style to the CSS where you can set the background color and anything else.

curl usage to get header

google.com is not responding to HTTP HEAD requests, which is why you are seeing a hang for the first command.

It does respond to GET requests, which is why the third command works.

As for the second, curl just prints the headers from a standard request.

How do I calculate the date six months from the current date using the datetime Python module?

I found this solution to be good. (This uses the python-dateutil extension)

from datetime import date
from dateutil.relativedelta import relativedelta

six_months = date.today() + relativedelta(months=+6)

The advantage of this approach is that it takes care of issues with 28, 30, 31 days etc. This becomes very useful in handling business rules and scenarios (say invoice generation etc.)

$ date(2010,12,31)+relativedelta(months=+1)
  datetime.date(2011, 1, 31)

$ date(2010,12,31)+relativedelta(months=+2)
  datetime.date(2011, 2, 28)

Jquery resizing image

Modifying Aleksandar's answer to make it as jquery plugin and accepts maxwidth and maxheight as arguments, suggested by Nathan.

$.fn.resize = function(maxWidth,maxHeight) {
return this.each(function() {
    var ratio = 0;
    var width = $(this).width();
    var height = $(this).height();
    if(width > maxWidth){
        ratio = maxWidth / width;
        $(this).css("width", maxWidth);
        $(this).css("height", height * ratio);
        height = height * ratio;
    }
    var width = $(this).width();
    var height = $(this).height();
    if(height > maxHeight){
        ratio = maxHeight / height;
        $(this).css("height", maxHeight);
        $(this).css("width", width * ratio);
        width = width * ratio;
    }
});
};

Used as $('.imgClass').resize(300,50);

Sending a file over TCP sockets in Python

The problem is extra 13 byte which server.py receives at the start. To resolve that write "l = c.recv(1024)" twice before the while loop as below.

print "Receiving..."
l = c.recv(1024) #this receives 13 bytes which is corrupting the data
l = c.recv(1024) # Now actual data starts receiving
while (l):

This resolves the issue, tried with different format and sizes of files. If anyone knows what this starting 13 bytes refers to, please reply.

Display a float with two decimal places in Python

Using python string formatting.

>>> "%0.2f" % 3
'3.00'

Altering a column: null to not null

In case of FOREIGN KEY CONSTRAINT... there will be a problem if '0' is not present in the column of Primary key table. The solution for that is...

STEP1:

Disable all the constraints using this code :

EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"

STEP2:

RUN UPDATE COMMAND (as mentioned in above comments)
RUN ALTER COMMAND (as mentioned in above comments)

STEP3:

Enable all the constraints using this code :

exec sp_msforeachtable @command1="print '?'", @command2="ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"

How to acces external json file objects in vue.js app

I have recently started working on a project using Vue JS, JSON Schema. I am trying to access nested JSON Objects from a JSON Schema file in the Vue app. I tried the below code and now I can load different JSON objects inside different Vue template tags. In the script tag add the below code

import  {JsonObject1name, JsonObject2name} from 'your Json file path';

Now you can access JsonObject1,2 names in data section of export default part as below:

data: () => ({ 
  
  schema: JsonObject1name,
  schema1: JsonObject2name,   
  
  model: {} 
}),

Now you can load the schema, schema1 data inside Vue template according to your requirement. See below code for example :

      <SchemaForm id="unique name representing your Json object1" class="form"  v-model="model" :schema="schema" :components="components">
      </SchemaForm>  

      <SchemaForm id="unique name representing your Json object2" class="form" v-model="model" :schema="schema1" :components="components">
      </SchemaForm>

SchemaForm is the local variable name for @formSchema/native library. I have implemented the data of different JSON objects through forms in different CSS tabs.

I hope this answer helps someone. I can help if there are any questions.

How to create nested directories using Mkdir in Golang?

os.Mkdir is used to create a single directory. To create a folder path, instead try using:

os.MkdirAll(folderPath, os.ModePerm)

Go documentation

func MkdirAll(path string, perm FileMode) error

MkdirAll creates a directory named path, along with any necessary parents, and returns nil, or else returns an error. The permission bits perm are used for all directories that MkdirAll creates. If path is already a directory, MkdirAll does nothing and returns nil.

Edit:

Updated to correctly use os.ModePerm instead.
For concatenation of file paths, use package path/filepath as described in @Chris' answer.

Favorite Visual Studio keyboard shortcuts

Hopefully this hasn't already been posted, apologies if so. I've just come across a useful keyboard shortcut in Visual Studio 2008. With the QuickWatch window open, highlight a row with a string value in it and hit Space Bar. The text visualiser window will appear with the value in it.

I have found it quite useful for checking jQuery innerText values as the QuickWatch window by default is too small to show longer strings fully.

SQL Server query - Selecting COUNT(*) with DISTINCT

try this:

SELECT
    COUNT(program_name) AS [Count],program_type AS [Type]
    FROM (SELECT DISTINCT program_name,program_type
              FROM cm_production 
              WHERE push_number=@push_number
         ) dt
    GROUP BY program_type

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

You're doing a few things wrong.

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

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

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

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

How can I convert a Unix timestamp to DateTime and vice versa?

Here's what you need:

public static DateTime UnixTimeStampToDateTime( double unixTimeStamp )
{
    // Unix timestamp is seconds past epoch
    System.DateTime dtDateTime = new DateTime(1970,1,1,0,0,0,0,System.DateTimeKind.Utc);
    dtDateTime = dtDateTime.AddSeconds( unixTimeStamp ).ToLocalTime();
    return dtDateTime;
}

Or, for Java (which is different because the timestamp is in milliseconds, not seconds):

public static DateTime JavaTimeStampToDateTime( double javaTimeStamp )
{
    // Java timestamp is milliseconds past epoch
    System.DateTime dtDateTime = new DateTime(1970,1,1,0,0,0,0,System.DateTimeKind.Utc);
    dtDateTime = dtDateTime.AddMilliseconds( javaTimeStamp ).ToLocalTime();
    return dtDateTime;
}

Tomcat is web server or application server?

Tomcat is a web server and a Servlet/JavaServer Pages container. It is often used as an application server for strictly web-based applications but does not include the entire suite of capabilities that a Java EE application server would supply.

Links:

Kotlin - Property initialization using "by lazy" vs. "lateinit"

Additionnally to hotkey's good answer, here is how I choose among the two in practice:

lateinit is for external initialisation: when you need external stuff to initialise your value by calling a method.

e.g. by calling:

private lateinit var value: MyClass

fun init(externalProperties: Any) {
   value = somethingThatDependsOn(externalProperties)
}

While lazy is when it only uses dependencies internal to your object.

Creating an array of objects in Java

The genaral form to declare a new array in java is as follows:

type arrayName[] = new type[numberOfElements];

Where type is a primitive type or Object. numberOfElements is the number of elements you will store into the array and this value can’t change because Java does not support dynamic arrays (if you need a flexible and dynamic structure for holding objects you may want to use some of the Java collections).

Lets initialize an array to store the salaries of all employees in a small company of 5 people:

int salaries[] = new int[5];

The type of the array (in this case int) applies to all values in the array. You can not mix types in one array.

Now that we have our salaries array initialized we want to put some values into it. We can do this either during the initialization like this:

int salaries[] = {50000, 75340, 110500, 98270, 39400};

Or to do it at a later point like this:

salaries[0] = 50000;
salaries[1] = 75340;
salaries[2] = 110500;
salaries[3] = 98270;
salaries[4] = 39400;

More visual example of array creation: enter image description here

To learn more about Arrays, check out the guide.

How to refresh Android listview?

on other option is onWindowFocusChanged method, but sure its sensitive and needs some extra coding for whom is interested

 override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)

       // some controls needed
        programList = usersDBHelper.readProgram(model.title!!)
        notesAdapter = DailyAdapter(this, programList)
        notesAdapter.notifyDataSetChanged()
        listview_act_daily.adapter = notesAdapter
    }

How can I check for existence of element in std::vector, in one line?

int elem = 42;
std::vector<int> v;
v.push_back(elem);
if(std::find(v.begin(), v.end(), elem) != v.end())
{
  //elem exists in the vector
} 

What is the difference between CloseableHttpClient and HttpClient in Apache HttpClient API?

  • The main entry point of the HttpClient API is the HttpClient interface.
  • The most essential function of HttpClient is to execute HTTP methods.
  • Execution of an HTTP method involves one or several HTTP request / HTTP response exchanges, usually handled internally by HttpClient.

  • CloseableHttpClient is an abstract class which is the base implementation of HttpClient that also implements java.io.Closeable.
  • Here is an example of request execution process in its simplest form:

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpget = new HttpGet("http://localhost/");
    CloseableHttpResponse response = httpclient.execute(httpget);
    try {
        //do something
    } finally {
        response.close();
    }

  • HttpClient resource deallocation: When an instance CloseableHttpClient is no longer needed and is about to go out of scope the connection manager associated with it must be shut down by calling the CloseableHttpClient#close() method.

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        //do something
    } finally {
        httpclient.close();
    }

see the Reference to learn fundamentals.


@Scadge Since Java 7, Use of try-with-resources statement ensures that each resource is closed at the end of the statement. It can be used both for the client and for each response

try(CloseableHttpClient httpclient = HttpClients.createDefault()){

    // e.g. do this many times
    try (CloseableHttpResponse response = httpclient.execute(httpget)) {
    //do something
    }

    //do something else with httpclient here
}

SQL Server: Attach incorrect version 661

To clarify, a database created under SQL Server 2008 R2 was being opened in an instance of SQL Server 2008 (the version prior to R2). The solution for me was to simply perform an upgrade installation of SQL Server 2008 R2. I can only speak for the Express edition, but it worked.

Oddly, though, the Web Platform Installer indicated that I had Express R2 installed. The better way to tell is to ask the database server itself:

SELECT @@VERSION

Await operator can only be used within an Async method

You can only use await in an async method, and Main cannot be async.

You'll have to use your own async-compatible context, call Wait on the returned Task in the Main method, or just ignore the returned Task and just block on the call to Read. Note that Wait will wrap any exceptions in an AggregateException.

If you want a good intro, see my async/await intro post.

MySQL table is marked as crashed and last (automatic?) repair failed

I tried the options in the existing answers, mainly the one marked correct which did not work in my scenario. However, what did work was using phpMyAdmin. Select the database and then select the table, from the bottom drop down menu select "Repair table".

  • Server type: MySQL
  • Server version: 5.7.23 - MySQL Community Server (GPL)
  • phpMyAdmin: Version information: 4.7.7

Flask example with POST

Before actually answering your question:

Parameters in a URL (e.g. key=listOfUsers/user1) are GET parameters and you shouldn't be using them for POST requests. A quick explanation of the difference between GET and POST can be found here.

In your case, to make use of REST principles, you should probably have:

http://ip:5000/users
http://ip:5000/users/<user_id>

Then, on each URL, you can define the behaviour of different HTTP methods (GET, POST, PUT, DELETE). For example, on /users/<user_id>, you want the following:

GET /users/<user_id> - return the information for <user_id>
POST /users/<user_id> - modify/update the information for <user_id> by providing the data
PUT - I will omit this for now as it is similar enough to `POST` at this level of depth
DELETE /users/<user_id> - delete user with ID <user_id> 

So, in your example, you want do a POST to /users/user_1 with the POST data being "John". Then the XPath expression or whatever other way you want to access your data should be hidden from the user and not tightly couple to the URL. This way, if you decide to change the way you store and access data, instead of all your URL's changing, you will simply have to change the code on the server-side.

Now, the answer to your question: Below is a basic semi-pseudocode of how you can achieve what I mentioned above:

from flask import Flask
from flask import request

app = Flask(__name__)

@app.route('/users/<user_id>', methods = ['GET', 'POST', 'DELETE'])
def user(user_id):
    if request.method == 'GET':
        """return the information for <user_id>"""
        .
        .
        .
    if request.method == 'POST':
        """modify/update the information for <user_id>"""
        # you can use <user_id>, which is a str but could
        # changed to be int or whatever you want, along
        # with your lxml knowledge to make the required
        # changes
        data = request.form # a multidict containing POST data
        .
        .
        .
    if request.method == 'DELETE':
        """delete user with ID <user_id>"""
        .
        .
        .
    else:
        # POST Error 405 Method Not Allowed
        .
        .
        .

There are a lot of other things to consider like the POST request content-type but I think what I've said so far should be a reasonable starting point. I know I haven't directly answered the exact question you were asking but I hope this helps you. I will make some edits/additions later as well.

Thanks and I hope this is helpful. Please do let me know if I have gotten something wrong.

Aligning textviews on the left and right edges in Android layout

Use a RelativeLayout with layout_alignParentLeft and layout_alignParentRight:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout01" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:padding="10dp">

    <TextView 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true" 
        android:id="@+id/mytextview1"/>

    <TextView 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_alignParentRight="true" 
        android:id="@+id/mytextview2"/>

</RelativeLayout>

Also, you should probably be using dip (or dp) rather than sp in your layout. sp reflect text settings as well as screen density so they're usually only for sizing text items.

console.log showing contents of array object

I warmly recommend this snippet to ensure, accidentally left code pieces don't fail on clients browsers:

/* neutralize absence of firebug */
if ((typeof console) !== 'object' || (typeof console.info) !== 'function') {
    window.console = {};
    window.console.info = window.console.log = window.console.warn = function(msg) {};
    window.console.trace = window.console.error = window.console.assert = function(msg) {};
}

rather than defining an empty function, this snippet is also a good starting point for rolling your own console surrogate if needed, i.e. dumping those infos into a .debug Container, show alerts (could get plenty) or such...

If you do use firefox+firebug, console.dir() is best for dumping array output, see here.

Chrome: Uncaught SyntaxError: Unexpected end of input

Try Firebug for Mozilla - it will show the position of the missing }.

http://getfirebug.com/

In Java, what is the best way to determine the size of an object?

For JSONObject the below code can help you.

`JSONObject.toString().getBytes("UTF-8").length`

returns size in bytes

I checked it with my JSONArray object by writing it to a file. It is giving object size.

Check whether IIS is installed or not?

The quickest way to check is just to write "inetmgr" at run (By pressing Win + R) as a command, if a manager window is appeared then it's installed otherwise it isn't.

Is there a command like "watch" or "inotifywait" on the Mac?

Here's a simple single line alternative for users who don't have the watch command who want to execute a command every 3 seconds:

while :; do your-command; sleep 3; done

It's an infinite loop that is basically the same as doing the following:

watch -n3 your-command

Unable to run 'adb root' on a rooted Android phone

I finally found out how to do this! Basically you need to run adb shell first and then while you're in the shell run su, which will switch the shell to run as root!

$: adb shell
$: su

The one problem I still have is that sqlite3 is not installed so the command is not recognized.

Getting Error:JRE_HOME variable is not defined correctly when trying to run startup.bat of Apache-Tomcat

Got the solution and it's working fine. Set the environment variables as:

  • CATALINA_HOME=C:\Program Files\Java\apache-tomcat-7.0.59\apache-tomcat-7.0.59 (path where your Apache Tomcat is)
  • JAVA_HOME=C:\Program Files\Java\jdk1.8.0_25; (path where your JDK is)
  • JRE_Home=C:\Program Files\Java\jre1.8.0_25; (path where your JRE is)
  • CLASSPATH=%JAVA_HOME%\bin;%JRE_HOME%\bin;%CATALINA_HOME%\lib

How can I flush GPU memory using CUDA (physical reset is unavailable)

First type

nvidia-smi

then select the PID that you want to kill

sudo kill -9 PID

Listing information about all database files in SQL Server

If you want get location of Database you can check Get All DBs Location.
you can use sys.master_files for get location of db and sys.databse to get db name

SELECT
    db.name AS DBName,
    type_desc AS FileType,
    Physical_Name AS Location
FROM
    sys.master_files mf
INNER JOIN 
    sys.databases db ON db.database_id = mf.database_id

What is the difference between ndarray and array in numpy?

numpy.ndarray() is a class, while numpy.array() is a method / function to create ndarray.

In numpy docs if you want to create an array from ndarray class you can do it with 2 ways as quoted:

1- using array(), zeros() or empty() methods: Arrays should be constructed using array, zeros or empty (refer to the See Also section below). The parameters given here refer to a low-level method (ndarray(…)) for instantiating an array.

2- from ndarray class directly: There are two modes of creating an array using __new__: If buffer is None, then only shape, dtype, and order are used. If buffer is an object exposing the buffer interface, then all keywords are interpreted.

The example below gives a random array because we didn't assign buffer value:

np.ndarray(shape=(2,2), dtype=float, order='F', buffer=None)

array([[ -1.13698227e+002,   4.25087011e-303],
       [  2.88528414e-306,   3.27025015e-309]])         #random

another example is to assign array object to the buffer example:

>>> np.ndarray((2,), buffer=np.array([1,2,3]),
...            offset=np.int_().itemsize,
...            dtype=int) # offset = 1*itemsize, i.e. skip first element
array([2, 3])

from above example we notice that we can't assign a list to "buffer" and we had to use numpy.array() to return ndarray object for the buffer

Conclusion: use numpy.array() if you want to make a numpy.ndarray() object"

gem install: Failed to build gem native extension (can't find header files)

MAC users may face this issue when xcode tools are not installed properly. Below is the command to get rid of the issue.

xcode-select --install

"Keep Me Logged In" - the best approach

OK, let me put this bluntly: if you're putting user data, or anything derived from user data into a cookie for this purpose, you're doing something wrong.

There. I said it. Now we can move on to the actual answer.

What's wrong with hashing user data, you ask? Well, it comes down to exposure surface and security through obscurity.

Imagine for a second that you're an attacker. You see a cryptographic cookie set for the remember-me on your session. It's 32 characters wide. Gee. That may be an MD5...

Let's also imagine for a second that they know the algorithm that you used. For example:

md5(salt+username+ip+salt)

Now, all an attacker needs to do is brute force the "salt" (which isn't really a salt, but more on that later), and he can now generate all the fake tokens he wants with any username for his IP address! But brute-forcing a salt is hard, right? Absolutely. But modern day GPUs are exceedingly good at it. And unless you use sufficient randomness in it (make it large enough), it's going to fall quickly, and with it the keys to your castle.

In short, the only thing protecting you is the salt, which isn't really protecting you as much as you think.

But Wait!

All of that was predicated that the attacker knows the algorithm! If it's secret and confusing, then you're safe, right? WRONG. That line of thinking has a name: Security Through Obscurity, which should NEVER be relied upon.

The Better Way

The better way is to never let a user's information leave the server, except for the id.

When the user logs in, generate a large (128 to 256 bit) random token. Add that to a database table which maps the token to the userid, and then send it to the client in the cookie.

What if the attacker guesses the random token of another user?

Well, let's do some math here. We're generating a 128 bit random token. That means that there are:

possibilities = 2^128
possibilities = 3.4 * 10^38

Now, to show how absurdly large that number is, let's imagine every server on the internet (let's say 50,000,000 today) trying to brute-force that number at a rate of 1,000,000,000 per second each. In reality your servers would melt under such load, but let's play this out.

guesses_per_second = servers * guesses
guesses_per_second = 50,000,000 * 1,000,000,000
guesses_per_second = 50,000,000,000,000,000

So 50 quadrillion guesses per second. That's fast! Right?

time_to_guess = possibilities / guesses_per_second
time_to_guess = 3.4e38 / 50,000,000,000,000,000
time_to_guess = 6,800,000,000,000,000,000,000

So 6.8 sextillion seconds...

Let's try to bring that down to more friendly numbers.

215,626,585,489,599 years

Or even better:

47917 times the age of the universe

Yes, that's 47917 times the age of the universe...

Basically, it's not going to be cracked.

So to sum up:

The better approach that I recommend is to store the cookie with three parts.

function onLogin($user) {
    $token = GenerateRandomToken(); // generate a token, should be 128 - 256 bit
    storeTokenForUser($user, $token);
    $cookie = $user . ':' . $token;
    $mac = hash_hmac('sha256', $cookie, SECRET_KEY);
    $cookie .= ':' . $mac;
    setcookie('rememberme', $cookie);
}

Then, to validate:

function rememberMe() {
    $cookie = isset($_COOKIE['rememberme']) ? $_COOKIE['rememberme'] : '';
    if ($cookie) {
        list ($user, $token, $mac) = explode(':', $cookie);
        if (!hash_equals(hash_hmac('sha256', $user . ':' . $token, SECRET_KEY), $mac)) {
            return false;
        }
        $usertoken = fetchTokenByUserName($user);
        if (hash_equals($usertoken, $token)) {
            logUserIn($user);
        }
    }
}

Note: Do not use the token or combination of user and token to lookup a record in your database. Always be sure to fetch a record based on the user and use a timing-safe comparison function to compare the fetched token afterwards. More about timing attacks.

Now, it's very important that the SECRET_KEY be a cryptographic secret (generated by something like /dev/urandom and/or derived from a high-entropy input). Also, GenerateRandomToken() needs to be a strong random source (mt_rand() is not nearly strong enough. Use a library, such as RandomLib or random_compat, or mcrypt_create_iv() with DEV_URANDOM)...

The hash_equals() is to prevent timing attacks. If you use a PHP version below PHP 5.6 the function hash_equals() is not supported. In this case you can replace hash_equals() with the timingSafeCompare function:

/**
 * A timing safe equals comparison
 *
 * To prevent leaking length information, it is important
 * that user input is always used as the second parameter.
 *
 * @param string $safe The internal (safe) value to be checked
 * @param string $user The user submitted (unsafe) value
 *
 * @return boolean True if the two strings are identical.
 */
function timingSafeCompare($safe, $user) {
    if (function_exists('hash_equals')) {
        return hash_equals($safe, $user); // PHP 5.6
    }
    // Prevent issues if string length is 0
    $safe .= chr(0);
    $user .= chr(0);

    // mbstring.func_overload can make strlen() return invalid numbers
    // when operating on raw binary strings; force an 8bit charset here:
    if (function_exists('mb_strlen')) {
        $safeLen = mb_strlen($safe, '8bit');
        $userLen = mb_strlen($user, '8bit');
    } else {
        $safeLen = strlen($safe);
        $userLen = strlen($user);
    }

    // Set the result to the difference between the lengths
    $result = $safeLen - $userLen;

    // Note that we ALWAYS iterate over the user-supplied length
    // This is to prevent leaking length information
    for ($i = 0; $i < $userLen; $i++) {
        // Using % here is a trick to prevent notices
        // It's safe, since if the lengths are different
        // $result is already non-0
        $result |= (ord($safe[$i % $safeLen]) ^ ord($user[$i]));
    }

    // They are only identical strings if $result is exactly 0...
    return $result === 0;
}

Change span text?

document.getElementById("serverTime").innerHTML = ...;

How does HttpContext.Current.User.Identity.Name know which usernames exist?

How does [HttpContext.Current.User] know which usernames exist or do not exist?

Let's look at an example of one way this works. Suppose you are using Forms Authentication and the "OnAuthenticate" event fires. This event occurs "when the application authenticates the current request" (Reference Source).

Up until this point, the application has no idea who you are.

Since you are using Forms Authentication, it first checks by parsing the authentication cookie (usually .ASPAUTH) via a call to ExtractTicketFromCookie. This calls FormsAuthentication.Decrypt (This method is public; you can call this yourself!). Next, it calls Context.SetPrincipalNoDemand, turning the cookie into a user and stuffing it into Context.User (Reference Source).

C# Creating and using Functions

What that build error is telling you, that you have to either have an instance of Program or make Add static.

phpmysql error - #1273 - #1273 - Unknown collation: 'utf8mb4_general_ci'

When you export you use the compatibility system set to MYSQL40. Worked for me.

How to run function in AngularJS controller on document ready?

Angular initializes automatically upon DOMContentLoaded event or when the angular.js script is evaluated if at that time document.readyState is set to 'complete'. At this point Angular looks for the ng-app directive which designates your application root.

https://docs.angularjs.org/guide/bootstrap

This means that the controller code will run after the DOM is ready.

Thus it's just $scope.init().

Converting string to number in javascript/jQuery

var string = 123 (is string),

parseInt(parameter is string);

var string = '123';

var int= parseInt(string );

console.log(int);  //Output will be 123.

How to position a div in bottom right corner of a browser?

I don't have IE8 to test this out, but I'm pretty sure it should work:

<div class="screen">
   <!-- code -->
   <div class="innerdiv">
      text or other content
   </div>
</div>

and the css:

.screen{
position: relative;
}
.innerdiv {
position: absolute;
bottom: 0;
right: 0;
}

This should place the .innerdiv in the bottom-right corner of the .screen class. I hope this helps :)

SQL selecting rows by most recent date with two unique columns

select to.chargeid,t0.po,i.chargetype from invoice i
inner join
(select chargeid,max(servicemonth)po from invoice 
group by chargeid)t0
on i.chargeid=t0.chargeid

The above query will work if the distinct charge id has different chargetype combinations.Hope this simple query helps with little performance time into consideration...

Any way to break if statement in PHP?

i have a simple solution without lot of changes. the initial statement is

I want to break the if statement above and stop executing echo "yes"; or such codes which are no longer necessary to be executed, there may be or may not be an additional condition, is there way to do this?

so, it seem simple. try code like this.

$a="test";
if("test"==$a)
{
  if (1==0){
      echo "yes"; // this line while never be executed. 
      // and can be reexecuted simply by changing if (1==0) to if (1==1) 
  }
}
echo "finish";

if you want to try without this code, it's simple. and you can back when you want. another solution is comment blocks. or simply thinking and try in another separated code and copy paste only the result in your final code. and if a code is no longer nescessary, in your case, the result can be

$a="test";
echo "finish";

with this code, the original statement is completely respected.. :) and more readable!

Finding height in Binary Search Tree

enter image description here

According to "Introduction to Algorithms" by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein, following is the definition of tree height:

The height of a node in a tree is the number of edges on the longest simple downward path from the node to a leaf, and the height of a tree is the height of its root. The height of a tree is also equal to the largest depth of any node in the tree.

Following is my ruby solution. Most of the people forgot about height of empty tree or tree of single node in their implementation.

def height(node, current_height)
  return current_height if node.nil? || (node.left.nil? && node.right.nil?)
  return [height(node.left, current_height + 1), height(node.right, current_height + 1)].max if node.left && node.right
  return height(node.left, current_height + 1) if node.left
  return height(node.right, current_height + 1)
end

How to convert seconds to time format?

ITroubs answer doesn't deal with the left over seconds when you want to use this code to convert an amount of seconds to a time format like hours : minutes : seconds

Here is what I did to deal with this: (This also adds a leading zero to one-digit minutes and seconds)

$seconds = 3921; //example

$hours = floor($seconds / 3600);
$mins = floor(($seconds - $hours*3600) / 60);
$s = $seconds - ($hours*3600 + $mins*60);

$mins = ($mins<10?"0".$mins:"".$mins);
$s = ($s<10?"0".$s:"".$s); 

$time = ($hours>0?$hours.":":"").$mins.":".$s;

$time will contain "1:05:21" in this example.

How can I use xargs to copy files that have spaces and quotes in their names?

This is more efficient as it does not run "cp" multiple times:

find -name '*FooBar*' -print0 | xargs -0 cp -t ~/foo/bar

Uncaught TypeError: Cannot set property 'onclick' of null

Make sure your javascript is being executed after your element(s) have loaded, perhaps try putting the js file call just before the tag or use the defer attribute in your script, like so: <script src="app.js" defer></script> this makes sure that your script will be executed after the dom has loaded.

How to enumerate an enum with String type?

(Improvement on Karthik Kumar answer)

This solution is using the compiler to guarantee you won't miss a case.

enum Suit: String {
    case spades = "?"
    case hearts = "?"
    case diamonds = "?"
    case clubs = "?"

    static var enumerate: [Suit] {
        switch Suit.spades {
        // make sure the two lines are identical ^_^
        case        .spades, .hearts, .diamonds, .clubs:
            return [.spades, .hearts, .diamonds, .clubs]
        }
    }
}

Check if property has attribute

You can use the Attribute.IsDefined method

https://msdn.microsoft.com/en-us/library/system.attribute.isdefined(v=vs.110).aspx

if(Attribute.IsDefined(YourProperty,typeof(YourAttribute)))
{
    //Conditional execution...
}

You could provide the property you're specifically looking for or you could iterate through all of them using reflection, something like:

PropertyInfo[] props = typeof(YourClass).GetProperties();

How to round up the result of integer division?

A variant of Nick Berardi's answer that avoids a branch:

int q = records / recordsPerPage, r = records % recordsPerPage;
int pageCount = q - (-r >> (Integer.SIZE - 1));

Note: (-r >> (Integer.SIZE - 1)) consists of the sign bit of r, repeated 32 times (thanks to sign extension of the >> operator.) This evaluates to 0 if r is zero or negative, -1 if r is positive. So subtracting it from q has the effect of adding 1 if records % recordsPerPage > 0.

Sorting by date & time in descending order?

If you mean you want to sort by date first then by names

SELECT id, name, form_id, DATE(updated_at) as date
  FROM wp_frm_items
  WHERE user_id = 11 && form_id=9
  ORDER BY updated_at DESC,name ASC

This will sort the records by date first, then by names

How do I add a Font Awesome icon to input field?

to work this with unicode or fontawesome, you should add a span with class like below, because input tag not support pseudo classes like :after. this is not a direct solution

in html:

   <span class="button1 search"></span>
<input name="username">

in css:

.button1 {
    background-color: #B9D5AD;
    border-radius: 0.2em 0 0 0.2em;
    box-shadow: 1px 0 0 rgba(0, 0, 0, 0.5), 2px 0 0 rgba(255, 255, 255, 0.5); 
    pointer-events: none;
    margin:1px 12px;    
    border-radius: 0.2em;    
    color: #333333;
    cursor: pointer;
    position: absolute;
    padding: 3px;
    text-decoration: none;   

}

Could not load file or assembly 'Microsoft.Web.Infrastructure,

On my machine the Nuget dependency wasn't downloaded correctly, the lib folder inside the nuget package didn't exist, hence the error.

Before

enter image description here

I renamed the Nuget Package in the packages folder and Nuget redownloaded it correctly with the necessary lib folder.

After enter image description here

Find a string within a cell using VBA

you never change the value of rng so it always points to the initial cell

copy the Set rng = rng.Offset(1, 0) to a new line before loop

also, your InStr test will always fail
True is -1, but the return from InStr will be greater than 0 when the string is found. change the test to remove = True

new code:

Sub IfTest()
 'This should split the information in a table up into cells
 Dim Splitter() As String
 Dim LenValue As Integer     'Gives the number of characters in date string
 Dim LeftValue As Integer    'One less than the LenValue to drop the ")"
 Dim rng As Range, cell As Range
 Set rng = ActiveCell

Do While ActiveCell.Value <> Empty
    If InStr(rng, "%") Then
        ActiveCell.Offset(0, 0).Select
        Splitter = Split(ActiveCell.Value, "% Change")
        ActiveCell.Offset(0, 10).Select
        ActiveCell.Value = Splitter(1)
        ActiveCell.Offset(0, -1).Select
        ActiveCell.Value = "% Change"
        ActiveCell.Offset(1, -9).Select
    Else
        ActiveCell.Offset(0, 0).Select
        Splitter = Split(ActiveCell.Value, "(")
        ActiveCell.Offset(0, 9).Select
        ActiveCell.Value = Splitter(0)
        ActiveCell.Offset(0, 1).Select
        LenValue = Len(Splitter(1))
        LeftValue = LenValue - 1
        ActiveCell.Value = Left(Splitter(1), LeftValue)
        ActiveCell.Offset(1, -10).Select
    End If
Set rng = rng.Offset(1, 0)
Loop

End Sub

Make code in LaTeX look *nice*

It turns out that lstlisting is able to format code nicely, but requires a lot of tweaking.

Wikibooks has a good example for the parameters you can tweak.

How do you update Xcode on OSX to the latest version?

I used the Command_Line_Tools_OS_X_10.XX_for_Xcode_7.2.dmg and therefore had to download the latest version from here.

How do I convert a long to a string in C++?

In C++11, there are actually std::to_string and std::to_wstring functions in <string>.

string to_string(int val);
string to_string(long val);
string to_string(long long val);
string to_string(unsigned val);
string to_string(unsigned long val);
string to_string(unsigned long long val);
string to_string(float val);
string to_string(double val);
string to_string (long double val);

jQuery: Change button text on click

In HTML:

<button type="button" id="AddButton" onclick="AddButtonClick()" class="btn btn-success btn-block ">Add</button> 

In Jquery write this function:

    function AddButtonClick(){ 
      //change text from add to Update
      $("#AddButton").text('Update');
    }

Form submit with AJAX passing form data to PHP without page refresh

$(document).ready(function(){
$('#userForm').on('submit', function(e){
        e.preventDefault();
//I had an issue that the forms were submitted in geometrical progression after the next submit. 
// This solved the problem.
        e.stopImmediatePropagation();
    // show that something is loading
    $('#response').html("<b>Loading data...</b>");

    // Call ajax for pass data to other place
    $.ajax({
    type: 'POST',
    url: 'somephpfile.php',
    data: $(this).serialize() // getting filed value in serialize form
    })
    .done(function(data){ // if getting done then call.

    // show the response
    $('#response').html(data);

    })
    .fail(function() { // if fail then getting message

    // just in case posting your form failed
    alert( "Posting failed." );

    });

    // to prevent refreshing the whole page page
    return false;

    });

How does the enhanced for statement work for arrays, and how to get an iterator for an array?

No, there is no conversion. The JVM just iterates over the array using an index in the background.

Quote from Effective Java 2nd Ed., Item 46:

Note that there is no performance penalty for using the for-each loop, even for arrays. In fact, it may offer a slight performance advantage over an ordinary for loop in some circumstances, as it computes the limit of the array index only once.

So you can't get an Iterator for an array (unless of course by converting it to a List first).

How can I convert an Int to a CString?

Here's one way:

CString str;
str.Format("%d", 5);

In your case, try _T("%d") or L"%d" rather than "%d"

How to plot vectors in python using matplotlib

This may also be achieved using matplotlib.pyplot.quiver, as noted in the linked answer;

plt.quiver([0, 0, 0], [0, 0, 0], [1, -2, 4], [1, 2, -7], angles='xy', scale_units='xy', scale=1)
plt.xlim(-10, 10)
plt.ylim(-10, 10)
plt.show()

mpl output

Add legend to ggplot2 line plot

Since @Etienne asked how to do this without melting the data (which in general is the preferred method, but I recognize there may be some cases where that is not possible), I present the following alternative.

Start with a subset of the original data:

datos <-
structure(list(fecha = structure(c(1317452400, 1317538800, 1317625200, 
1317711600, 1317798000, 1317884400, 1317970800, 1318057200, 1318143600, 
1318230000, 1318316400, 1318402800, 1318489200, 1318575600, 1318662000, 
1318748400, 1318834800, 1318921200, 1319007600, 1319094000), class = c("POSIXct", 
"POSIXt"), tzone = ""), TempMax = c(26.58, 27.78, 27.9, 27.44, 
30.9, 30.44, 27.57, 25.71, 25.98, 26.84, 33.58, 30.7, 31.3, 27.18, 
26.58, 26.18, 25.19, 24.19, 27.65, 23.92), TempMedia = c(22.88, 
22.87, 22.41, 21.63, 22.43, 22.29, 21.89, 20.52, 19.71, 20.73, 
23.51, 23.13, 22.95, 21.95, 21.91, 20.72, 20.45, 19.42, 19.97, 
19.61), TempMin = c(19.34, 19.14, 18.34, 17.49, 16.75, 16.75, 
16.88, 16.82, 14.82, 16.01, 16.88, 17.55, 16.75, 17.22, 19.01, 
16.95, 17.55, 15.21, 14.22, 16.42)), .Names = c("fecha", "TempMax", 
"TempMedia", "TempMin"), row.names = c(NA, 20L), class = "data.frame")

You can get the desired effect by (and this also cleans up the original plotting code):

ggplot(data = datos, aes(x = fecha)) +
  geom_line(aes(y = TempMax, colour = "TempMax")) +
  geom_line(aes(y = TempMedia, colour = "TempMedia")) +
  geom_line(aes(y = TempMin, colour = "TempMin")) +
  scale_colour_manual("", 
                      breaks = c("TempMax", "TempMedia", "TempMin"),
                      values = c("red", "green", "blue")) +
  xlab(" ") +
  scale_y_continuous("Temperatura (C)", limits = c(-10,40)) + 
  labs(title="TITULO")

The idea is that each line is given a color by mapping the colour aesthetic to a constant string. Choosing the string which is what you want to appear in the legend is the easiest. The fact that in this case it is the same as the name of the y variable being plotted is not significant; it could be any set of strings. It is very important that this is inside the aes call; you are creating a mapping to this "variable".

scale_colour_manual can now map these strings to the appropriate colors. The result is enter image description here

In some cases, the mapping between the levels and colors needs to be made explicit by naming the values in the manual scale (thanks to @DaveRGP for pointing this out):

ggplot(data = datos, aes(x = fecha)) +
  geom_line(aes(y = TempMax, colour = "TempMax")) +
  geom_line(aes(y = TempMedia, colour = "TempMedia")) +
  geom_line(aes(y = TempMin, colour = "TempMin")) +
  scale_colour_manual("", 
                      values = c("TempMedia"="green", "TempMax"="red", 
                                 "TempMin"="blue")) +
  xlab(" ") +
  scale_y_continuous("Temperatura (C)", limits = c(-10,40)) + 
  labs(title="TITULO")

(giving the same figure as before). With named values, the breaks can be used to set the order in the legend and any order can be used in the values.

ggplot(data = datos, aes(x = fecha)) +
  geom_line(aes(y = TempMax, colour = "TempMax")) +
  geom_line(aes(y = TempMedia, colour = "TempMedia")) +
  geom_line(aes(y = TempMin, colour = "TempMin")) +
  scale_colour_manual("", 
                      breaks = c("TempMedia", "TempMax", "TempMin"),
                      values = c("TempMedia"="green", "TempMax"="red", 
                                 "TempMin"="blue")) +
  xlab(" ") +
  scale_y_continuous("Temperatura (C)", limits = c(-10,40)) + 
  labs(title="TITULO")

Is div inside list allowed?

Yes it is valid according to xhtml1-strict.dtd. The following XHTML passes the validation:

<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Test</title>
</head>
<body>
<ul>
  <li><div>test</div></li>
</ul>
</body>
</html>

How to save a PNG image server-side, from a base64 data string

You need to extract the base64 image data from that string, decode it and then you can save it to disk, you don't need GD since it already is a png.

$data = 'data:image/png;base64,AAAFBfj42Pj4';

list($type, $data) = explode(';', $data);
list(, $data)      = explode(',', $data);
$data = base64_decode($data);

file_put_contents('/tmp/image.png', $data);

And as a one-liner:

$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data));

An efficient method for extracting, decoding, and checking for errors is:

if (preg_match('/^data:image\/(\w+);base64,/', $data, $type)) {
    $data = substr($data, strpos($data, ',') + 1);
    $type = strtolower($type[1]); // jpg, png, gif

    if (!in_array($type, [ 'jpg', 'jpeg', 'gif', 'png' ])) {
        throw new \Exception('invalid image type');
    }
    $data = str_replace( ' ', '+', $data );
    $data = base64_decode($data);

    if ($data === false) {
        throw new \Exception('base64_decode failed');
    }
} else {
    throw new \Exception('did not match data URI with image data');
}

file_put_contents("img.{$type}", $data);

Using Axios GET with Authorization Header in React-Native App

For anyone else that comes across this post and might find it useful... There is actually nothing wrong with my code. I made the mistake of requesting client_credentials type access code instead of password access code (#facepalms). FYI I am using urlencoded post hence the use of querystring.. So for those that may be looking for some example code.. here is my full request

Big thanks to @swapnil for trying to help me debug this.

   const data = {
      grant_type: USER_GRANT_TYPE,
      client_id: CLIENT_ID,
      client_secret: CLIENT_SECRET,
      scope: SCOPE_INT,
      username: DEMO_EMAIL,
      password: DEMO_PASSWORD
    };



  axios.post(TOKEN_URL, Querystring.stringify(data))   
   .then(response => {
      console.log(response.data);
      USER_TOKEN = response.data.access_token;
      console.log('userresponse ' + response.data.access_token); 
    })   
   .catch((error) => {
      console.log('error ' + error);   
   });



const AuthStr = 'Bearer '.concat(USER_TOKEN); 
axios.get(URL, { headers: { Authorization: AuthStr } })
 .then(response => {
     // If request is good...
     console.log(response.data);
  })
 .catch((error) => {
     console.log('error ' + error);
  });

Windows 7, 64 bit, DLL problems

This contribution does not really answer the initial question, but taking into account the hit-rate of this thread I assume that there are quite a few people dealing with the problem that API-MS-WIN-CORE- libraries cannot be found.

I was able to solve a problem where my application refused to start with the error message that API-MS-WIN-CORE-WINRT-STRING-L1-1-0.DLL is not found by simply updating Visual Studio.

I don't think that my build environment (Windows 7 Pro SP1, Visual Studio Ultimate 2012) was messed up completely, it worked fine for most of my projects. But under some very specific circumstances I got the error message (see below).

After updating Visual Studio 11 from the initial CD-Version (I forgot to look up the version number) to version 11.0.61030.00 Update 4 also the broken project was running again.

Error message at application startup

How to use pip with python 3.4 on windows?

"py -m pip install requests" works fine with Windows and its up gradation. Just change the path after installing Python 3.4 in the command prompt and type in "py -m pip install requests"command prompt. pip install

How can I check if a key exists in a dictionary?

If you want to retrieve the key's value if it exists, you can also use

try:
    value = a[key]
except KeyError:
    # Key is not present
    pass

If you want to retrieve a default value when the key does not exist, use value = a.get(key, default_value). If you want to set the default value at the same time in case the key does not exist, use value = a.setdefault(key, default_value).

Foreach loop in java for a custom object list

If this code fails to operate on every item in the list, it must be because something is throwing an exception before you have completed the list; the likeliest candidate is the method called "insertOrThrow". You could wrap that call in a try-catch structure to handle the exception for whichever items are failing without exiting the loop and the method prematurely.

What's the difference between a word and byte?

In fact, in common usage, word has become synonymous with 16 bits, much like byte has with 8 bits. Can get a little confusing since the "word size" on a 32-bit CPU is 32-bits, but when talking about a word of data, one would mean 16-bits. Microcontrollers with a 32-bit word size have taken to calling their instructions "longs" (supposedly to try and avoid the word/doubleword confusion).

Media Player called in state 0, error (-38,0)

I got this error when I was trying to get the current position (MediaPlayer.getCurrentPosition()) of media player when it wasn't in the prepared stated. I got around this by Keeping track of its state and only calling the getCurrentPosition() method after onPreparedListener is called.

Returning a file to View/Download in ASP.NET MVC

Below code worked for me for getting a pdf file from an API service and response it out to the browser - hope it helps;

public async Task<FileResult> PrintPdfStatements(string fileName)
    {
         var fileContent = await GetFileStreamAsync(fileName);
         var fileContentBytes = ((MemoryStream)fileContent).ToArray();
         return File(fileContentBytes, System.Net.Mime.MediaTypeNames.Application.Pdf);
    }

Clearing NSUserDefaults

I found this:

osascript -e 'tell application "iOS Simulator" to quit'
xcrun simctl list devices | grep -v '^[-=]' | cut -d "(" -f2 | cut -d ")" -f1 | xargs -I {} xcrun simctl erase "{}"

Source: https://gist.github.com/ZevEisenberg/5a172662cb576872d1ab

Can I specify multiple users for myself in .gitconfig?

GIT_AUTHOR_EMAIL + local .bashrc

.bashrc_local: don't track this file, put it only on your work computer:

export GIT_AUTHOR_EMAIL='[email protected]'
export GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL"

.bashrc: track this file, make it the same on both work and home computers:

F="$HOME/.bashrc_local"
if [ -r "$F" ]; then
    . "$F"
fi

I'm using https://github.com/technicalpickles/homesick to sync my dotfiles.

If only gitconfig would accept environment variables: Shell variable expansion in git config

"Specified argument was out of the range of valid values"

try this.

if (ViewState["CurrentTable"] != null)
            {
                DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
                DataRow drCurrentRow = null;
                if (dtCurrentTable.Rows.Count > 0)
                {
                    for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                    {
                        //extract the TextBox values
                        TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("txt_type");
                        TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("txt_total");
                        TextBox box3 = (TextBox)Gridview1.Rows[i].Cells[3].FindControl("txt_max");
                        TextBox box4 = (TextBox)Gridview1.Rows[i].Cells[4].FindControl("txt_min");
                        TextBox box5 = (TextBox)Gridview1.Rows[i].Cells[5].FindControl("txt_rate");

                        drCurrentRow = dtCurrentTable.NewRow();
                        drCurrentRow["RowNumber"] = i + 1;

                        dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
                        dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;
                        dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;
                        dtCurrentTable.Rows[i - 1]["Column4"] = box4.Text;
                        dtCurrentTable.Rows[i - 1]["Column5"] = box5.Text;

                        rowIndex++;
                    }
                    dtCurrentTable.Rows.Add(drCurrentRow);
                    ViewState["CurrentTable"] = dtCurrentTable;

                    Gridview1.DataSource = dtCurrentTable;
                    Gridview1.DataBind();
                }
            }
            else
            {
                Response.Write("ViewState is null");
            }

What is an ORM, how does it work, and how should I use one?

An ORM (Object Relational Mapper) is a piece/layer of software that helps map your code Objects to your database.

Some handle more aspects than others...but the purpose is to take some of the weight of the Data Layer off of the developer's shoulders.

Here's a brief clip from Martin Fowler (Data Mapper):

Patterns of Enterprise Application Architecture Data Mappers

Assigning the return value of new by reference is deprecated

It happened because of PHP 5.3 , which comes in WAMP 2.0i package and not Joomla.

You have two choices to fix it,

either use WAMP 2h (previous version) or download PHP 5.2.9-2 addon from WAMP website.

How to set default value for column of new created table from select statement in 11g

The reason is that CTAS (Create table as select) does not copy any metadata from the source to the target table, namely

  • no primary key
  • no foreign keys
  • no grants
  • no indexes
  • ...

To achieve what you want, I'd either

  • use dbms_metadata.get_ddl to get the complete table structure, replace the table name with the new name, execute this statement, and do an INSERT afterward to copy the data
  • or keep using CTAS, extract the not null constraints for the source table from user_constraints and add them to the target table afterwards

Node.js check if file exists

fs.exists(path, callback) and fs.existsSync(path) are deprecated now, see https://nodejs.org/api/fs.html#fs_fs_exists_path_callback and https://nodejs.org/api/fs.html#fs_fs_existssync_path.

To test the existence of a file synchronously one can use ie. fs.statSync(path). An fs.Stats object will be returned if the file exists, see https://nodejs.org/api/fs.html#fs_class_fs_stats, otherwise an error is thrown which will be catched by the try / catch statement.

var fs = require('fs'),
  path = '/path/to/my/file',
  stats;

try {
  stats = fs.statSync(path);
  console.log("File exists.");
}
catch (e) {
  console.log("File does not exist.");
}

Principal Component Analysis (PCA) in Python

You can find a PCA function in the matplotlib module:

import numpy as np
from matplotlib.mlab import PCA

data = np.array(np.random.randint(10,size=(10,3)))
results = PCA(data)

results will store the various parameters of the PCA. It is from the mlab part of matplotlib, which is the compatibility layer with the MATLAB syntax

EDIT: on the blog nextgenetics I found a wonderful demonstration of how to perform and display a PCA with the matplotlib mlab module, have fun and check that blog!

HTML Submit-button: Different value / button-text?

I don't know if I got you right, but, as I understand, you could use an additional hidden field with the value "add tag" and let the button have the desired text.

Java Web Service client basic authentication

It turned out that there's a simple, standard way to achieve what I wanted:

import java.net.Authenticator;
import java.net.PasswordAuthentication;

Authenticator myAuth = new Authenticator() 
{
    @Override
    protected PasswordAuthentication getPasswordAuthentication()
    {
        return new PasswordAuthentication("german", "german".toCharArray());
    }
};

Authenticator.setDefault(myAuth);

No custom "sun" classes or external dependencies, and no manually encode anything.

I'm aware that BASIC security is not, well, secure, but we are also using HTTPS.

Convert base-2 binary number string to int

If you are using python3.6 or later you can use f-string to do the conversion:

Binary to decimal:

>>> print(f'{0b1011010:#0}')
90

>>> bin_2_decimal = int(f'{0b1011010:#0}')
>>> bin_2_decimal
90

binary to octal hexa and etc.

>>> f'{0b1011010:#o}'
'0o132'  # octal

>>> f'{0b1011010:#x}'
'0x5a'   # hexadecimal

>>> f'{0b1011010:#0}'
'90'     # decimal

Pay attention to 2 piece of information separated by colon.

In this way, you can convert between {binary, octal, hexadecimal, decimal} to {binary, octal, hexadecimal, decimal} by changing right side of colon[:]

:#b -> converts to binary
:#o -> converts to octal
:#x -> converts to hexadecimal 
:#0 -> converts to decimal as above example

Try changing left side of colon to have octal/hexadecimal/decimal.

How to get a variable type in Typescript?

I suspect you can adjust your approach a little and use something along the lines of the example here:

https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards

function isFish(pet: Fish | Bird): pet is Fish {
  return (pet as Fish).swim !== undefined;
}

Radio button checked event handling

Try something like this:

$(function(){
  $('input[type="radio"]').click(function(){
    if ($(this).is(':checked'))
    {
      alert($(this).val());
    }
  });
});

If you give your radio buttons a class then you can replace the code $('input[type="radio"]') with $('.someclass').

Cannot make Project Lombok work on Eclipse

  1. Copy the Lombok jar into your eclipse based IDE (Eclipse/STS etc-) install folder

    • note that the install folder is the folder that has the .ini file for your IDE
    • if you use Maven to pull in the jar, then get it from your m2 repository
    • cp ~/.m2/repository/projectlombork/lombork-1.x.jar /path/to/IDE/lombok.jar
  2. Edit the .ini file in the install folder of your IDE and add the following lines below -vmargs.

    • -javaagent:lombok.jar -Xbootclasspath/a:lombok.jar
    • note that the jar should be in the same folder as the .ini file and the name of the jar lombok.jar
  3. Restart your IDE and rebuild/maven-update your project

VirtualBox error "Failed to open a session for the virtual machine"

maybe it is caused by privilege, please try this:

#sudo chmod 755 /Applications 
#sudo chmod 755 /Applications/Virtualbox.app

Turn off deprecated errors in PHP 5.3

In file wp-config.php you can find constant WP_DEBUG. Make sure it is set to false.

define('WP_DEBUG', false);

This is for WordPress 3.x.

android EditText - finished typing event

I ended her with the same problem and I could not use the the solution with onEditorAction or onFocusChange and did not want to try the timer. A timer is too dangerous for may taste, because of all the threads and too unpredictable, as you do not know when you code is executed.

The onEditorAction do not catch when the user leave without using a button and if you use it please notice that KeyEvent can be null. The focus is unreliable at both ends the user can get focus and leave without enter any text or selecting the field and the user do not need to leave the last EditText field.

My solution use onFocusChange and a flag set when the user starts editing text and a function to get the text from the last focused view, which I call when need.

I just clear the focus on all my text fields to tricker the leave text view code, The clearFocus code is only executed if the field has focus. I call the function in onSaveInstanceState so I do not have to save the flag (mEditing) as a state of the EditText view and when important buttons is clicked and when the activity is closed.

Be careful with TexWatcher as it is call often I use the condition on focus to not react when the onRestoreInstanceState code entering text. I

final EditText mEditTextView = (EditText) getView();

    mEditTextView.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (!mEditing && mEditTextView.hasFocus()) {
                mEditing = true;
            }
        }
    });
    mEditTextView.setOnFocusChangeListener(new View.OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus && mEditing) {
                mEditing = false;
                ///Do the thing
            }
        }
    });
protected void saveLastOpenField(){
    for (EditText view:getFields()){
            view.clearFocus();
    }
}

How could I use requests in asyncio?

There is a good case of async/await loops and threading in an article by Pimin Konstantin Kefaloukos Easy parallel HTTP requests with Python and asyncio:

To minimize the total completion time, we could increase the size of the thread pool to match the number of requests we have to make. Luckily, this is easy to do as we will see next. The code listing below is an example of how to make twenty asynchronous HTTP requests with a thread pool of twenty worker threads:

# Example 3: asynchronous requests with larger thread pool
import asyncio
import concurrent.futures
import requests

async def main():

    with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:

        loop = asyncio.get_event_loop()
        futures = [
            loop.run_in_executor(
                executor, 
                requests.get, 
                'http://example.org/'
            )
            for i in range(20)
        ]
        for response in await asyncio.gather(*futures):
            pass


loop = asyncio.get_event_loop()
loop.run_until_complete(main())

In PowerShell, how can I test if a variable holds a numeric value?

$itisint=$true
try{
 [int]$vartotest
}catch{
 "error converting to int"
 $itisint=$false
}

this is more universal, because this way you can test also strings (read from a file for example) if they represent number. The other solutions using -is [int] result in false if you would have "123" as string in a variable. This also works on machines with older powershell then 5.1

Babel command not found

To install version 7+ of Babel run:

npm install -g @babel/cli
npm install -g @babel/core

HttpClient 4.0.1 - how to release connection?

I've got this problem when I use HttpClient in Multithread envirnoment (Servlets). One servlet still holds connection and another one want to get connection.

Solution:

version 4.0 use ThreadSafeClientConnManager

version 4.2 use PoolingClientConnectionManager

and set this two setters:

setDefaultMaxPerRoute
setMaxTotal

Why are my CSS3 media queries not working on mobile devices?

It may also happen if the browser zoom level is not correct. Your browser window zoom should be 100%. In Chrome use Ctrl + 0 to reset the zoom level.

PHP DateTime __construct() Failed to parse time string (xxxxxxxx) at position x

$start_date = new DateTime();
$start_date->setTimestamp($dbResult->db_timestamp);

Is <img> element block level or inline level?

is an inline element ..but in css you can change it simply by:- img{display:inline-block;} or img{display:inline-block;} or img{display:inliblock;}

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

Go To Setting > Android SDK > SDK Tools > Google Play Services

enter image description here

How to remove text from a string?

This doesn't have anything to do with jQuery. You can use the JavaScript replace function for this:

var str = "data-123";
str = str.replace("data-", "");

You can also pass a regex to this function. In the following example, it would replace everything except numerics:

str = str.replace(/[^0-9\.]+/g, "");

Count the number of all words in a string

I use the str_count function from the stringr library with the escape sequence \w that represents:

any ‘word’ character (letter, digit or underscore in the current locale: in UTF-8 mode only ASCII letters and digits are considered)

Example:

> str_count("How many words are in this sentence", '\\w+')
[1] 7

Of all other 9 answers that I was able to test, only two (by Vincent Zoonekynd, and by petermeissner) worked for all inputs presented here so far, but they also require stringr.

But only this solution works with all inputs presented so far, plus inputs such as "foo+bar+baz~spam+eggs" or "Combien de mots sont dans cette phrase ?".

Benchmark:

library(stringr)

questions <-
  c(
    "", "x", "x y", "x y!", "x y! z",
    "foo+bar+baz~spam+eggs",
    "one,   two three 4,,,, 5 6",
    "How many words are in this sentence",
    "How  many words    are in this   sentence",
    "Combien de mots sont dans cette phrase ?",
    "
    Day after day, day after day,
    We stuck, nor breath nor motion;
    "
  )

answers <- c(0, 1, 2, 2, 3, 5, 6, 7, 7, 7, 12)

score <- function(f) sum(unlist(lapply(questions, f)) == answers)

funs <-
  c(
    function(s) sapply(gregexpr("\\W+", s), length) + 1,
    function(s) sapply(gregexpr("[[:alpha:]]+", s), function(x) sum(x > 0)),
    function(s) vapply(strsplit(s, "\\W+"), length, integer(1)),
    function(s) length(strsplit(gsub(' {2,}', ' ', s), ' ')[[1]]),
    function(s) length(str_match_all(s, "\\S+")[[1]]),
    function(s) str_count(s, "\\S+"),
    function(s) sapply(gregexpr("\\W+", s), function(x) sum(x > 0)) + 1,
    function(s) length(unlist(strsplit(s," "))),
    function(s) sapply(strsplit(s, " "), length),
    function(s) str_count(s, '\\w+')
  )

unlist(lapply(funs, score))

Output:

6 10 10  8  9  9  7  6  6 11

How to call a stored procedure from Java and JPA

  1. For a simple stored procedure that using IN/OUT parameters like this

    CREATE OR REPLACE PROCEDURE count_comments (  
       postId IN NUMBER,  
       commentCount OUT NUMBER )  
    AS 
    BEGIN 
        SELECT COUNT(*) INTO commentCount  
        FROM post_comment  
        WHERE post_id = postId; 
    END;
    

    You can call it from JPA as follows:

    StoredProcedureQuery query = entityManager
        .createStoredProcedureQuery("count_comments")
        .registerStoredProcedureParameter(1, Long.class, 
            ParameterMode.IN)
        .registerStoredProcedureParameter(2, Long.class, 
            ParameterMode.OUT)
        .setParameter(1, 1L);
    
    query.execute();
    
    Long commentCount = (Long) query.getOutputParameterValue(2);
    
  2. For a stored procedure which uses a SYS_REFCURSOR OUT parameter:

    CREATE OR REPLACE PROCEDURE post_comments ( 
       postId IN NUMBER, 
       postComments OUT SYS_REFCURSOR ) 
    AS 
    BEGIN
        OPEN postComments FOR
        SELECT *
        FROM post_comment 
        WHERE post_id = postId; 
    END;
    

    You can call it as follows:

    StoredProcedureQuery query = entityManager
        .createStoredProcedureQuery("post_comments")
        .registerStoredProcedureParameter(1, Long.class, 
             ParameterMode.IN)
        .registerStoredProcedureParameter(2, Class.class, 
             ParameterMode.REF_CURSOR)
        .setParameter(1, 1L);
    
    query.execute();
    
    List<Object[]> postComments = query.getResultList();
    
  3. For a SQL function that looks as follows:

    CREATE OR REPLACE FUNCTION fn_count_comments ( 
        postId IN NUMBER ) 
        RETURN NUMBER 
    IS
        commentCount NUMBER; 
    BEGIN
        SELECT COUNT(*) INTO commentCount 
        FROM post_comment 
        WHERE post_id = postId; 
        RETURN( commentCount ); 
    END;
    

    You can call it like this:

    BigDecimal commentCount = (BigDecimal) entityManager
    .createNativeQuery(
        "SELECT fn_count_comments(:postId) FROM DUAL"
    )
    .setParameter("postId", 1L)
    .getSingleResult();
    

    At least when using Hibernate 4.x and 5.x because the JPA StoredProcedureQuery does not work for SQL FUNCTIONS.

For more details about how to call stored procedures and functions when using JPA and Hibernate, check out the following articles

Histogram Matplotlib

I just realized that the hist documentation is explicit about what to do when you already have an np.histogram

counts, bins = np.histogram(data)
plt.hist(bins[:-1], bins, weights=counts)

The important part here is that your counts are simply the weights. If you do it like that, you don't need the bar function anymore

AngularJS Error: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https

RootCause:

File protocol does not support cross origin request for Chrome

Solution 1:

use http protocol instead of file, meaning: set up a http server, such as apache, or nodejs+http-server

Sotution 2:

Add --allow-file-access-from-files after Chrome`s shortcut target, and open new browse instance using this shortcut

enter image description here

Solution 3:

use Firefox instead

The Web Application Project [...] is configured to use IIS. The Web server [...] could not be found.

Cause: The IISURL inside project.csproj is not correctly reflected in the project setting, and the virtual directory was not created.

Solution: Change the Project URL to correct PORT and create the Virtual Directory to make the missing PORT available.


Follow Below Steps:

Step 1: Right click on the project file to Edit the project.csproj file. enter image description here

Step 2: Search IIS and modify from <UseIIS>True</UseIIS> to <UseIIS>False</UseIIS> enter image description here

Step 3: Right Click Project to Reload the Project. After Reload successfully, right click Project and select Properties. enter image description here

Step 4: Locate Project URL option under Properties => Web enter image description here

Step 5: Change the Project URL to IIS URL indicated both on the Error Message and on the <IISURL>http://localhost:8086 </IISURL> from project.csproj file. Then Click Create Virtual Directory. Save All enter image description here enter image description here

Step 6: Redo Step 2 so it doesn't impact the remote codebase and the server deployment settings.

What does 'x packages are looking for funding' mean when running `npm install`?

When you run npm update in the command prompt, when it is done it will recommend you type a new command called npm fund.

When you run npm fund it will list all the modules and packages you have installed that were created by companies or organizations that need money for their IT projects. You will see a list of webpages where you can send them money. So "funds" means "Angular packages you installed that could use some money from you as an option to help support their businesses".

It's basically a list of the modules you have that need contributions or donations of money to their projects and which list websites where you can enter a credit card to help pay for them.

Is there an easy way to strike through text in an app widget?

It is really easy if you are using strings:

<string name="line"> Not crossed <strike> crossed </strike> </string>

And then just:

<TextView 
        ...
         android:text="@string/line"
 />

PHP, MySQL error: Column count doesn't match value count at row 1

The number of column parameters in your insert query is 9, but you've only provided 8 values.

INSERT INTO dbname (id, Name, Description, shortDescription, Ingredients, Method, Length, dateAdded, Username) VALUES ('', '%s', '%s', '%s', '%s', '%s', '%s', '%s')

The query should omit the "id" parameter, because it is auto-generated (or should be anyway):

INSERT INTO dbname (Name, Description, shortDescription, Ingredients, Method, Length, dateAdded, Username) VALUES ('', '%s', '%s', '%s', '%s', '%s', '%s', '%s')

rails + MySQL on OSX: Library not loaded: libmysqlclient.18.dylib

I was working with the rails g model command and I got this error:

Library not loaded: libmysqlclient.18.dylib

I have tried this and it functioned for me. I was using Mavericks 10.9.5

sudo ln -s /usr/local/mysql-5.6.19-osx10.7-x86_64/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib

Thanks!

Now I'm using Yosemite 10.10.5 and I got the same error, so I just ran this command on the terminal an it was successfully fixed up.

$ sudo ln -s /usr/local/mysql-5.6.26-osx10.8-x86_64/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib

also you can try:

sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib

Both of them work fine for me. Hope it could be useful!

Determining if a number is prime

If you know the range of the inputs (which you do since your function takes an int), you can precompute a table of primes less than or equal to the square root of the max input (2^31-1 in this case), and then test for divisibility by each prime in the table less than or equal to the square root of the number given.

SQL get the last date time record

Try this:

SELECT filename,Dates,Status 
FROM TableName 
WHERE Dates In (SELECT MAX(Dates) FROM TableName GROUP BY filename)

javascript check for not null

Use !== as != will get you into a world of nontransitive JavaScript truth table weirdness.

Cannot find mysql.sock

I couldn't find mysql socket at all so reinstalled mysql server(all tables and phpmyadmin settings were preserved). Here are the commands:

1) Install

sudo apt-get install mysql-server

2) Follow terminal configuration steps

sudo mysql_secure_installation

3) Check status: (Should return "Active: active (running)")

systemctl status mysql.service

MySQL: Cloning a MySQL database on the same MySql instance

This statement was added in MySQL 5.1.7 but was found to be dangerous and was removed in MySQL 5.1.23. It was intended to enable upgrading pre-5.1 databases to use the encoding implemented in 5.1 for mapping database names to database directory names. However, use of this statement could result in loss of database contents, which is why it was removed. Do not use RENAME DATABASE in earlier versions in which it is present.

To perform the task of upgrading database names with the new encoding, use ALTER DATABASE db_name UPGRADE DATA DIRECTORY NAME instead: http://dev.mysql.com/doc/refman/5.1/en/alter-database.html

Assign an initial value to radio button as checked

You can just use:

<input type="radio" checked />

Using just the attribute checked without stating a value is the same as checked="checked".

'Class' does not contain a definition for 'Method'

I just ran into this problem; the issue seems different from the other answers posted here, so I'll mention it in case it helps someone.

In my case, I have an internal base class defined in one assembly ("A"), an internal derived class defined in a second assembly ("B"), and a test assembly ("TEST"). I exposed internals defined in assembly "B" to "TEST" using InternalsVisibleToAttribute, but neglected to do so for assembly "A". This produced the error mentioned at top with no further indication of the problem; using InternalsVisibleToAttribute to expose assembly "A" to "TEST" resolved the issue.

AppStore - App status is ready for sale, but not in app store

you must change Territory and click on save, after one minute your app will be available. No need to Remove from sale

Still Reachable Leak detected by Valgrind

You don't appear to understand what still reachable means.

Anything still reachable is not a leak. You don't need to do anything about it.

Strange Jackson exception being thrown when serializing Hibernate object

It's not ideal, but you could disable Jackson's auto-discovery of JSON properties, using @JsonAutoDetect at the class level. This would prevent it from trying to handle the Javassist stuff (and failing).

This means that you then have to annotate each getter manually (with @JsonProperty), but that's not necessarily a bad thing, since it keeps things explicit.

How can I iterate over files in a given directory?

I really like using the scandir directive that is built into the os library. Here is a working example:

import os

i = 0
with os.scandir('/usr/local/bin') as root_dir:
    for path in root_dir:
        if path.is_file():
            i += 1
            print(f"Full path is: {path} and just the name is: {path.name}")
print(f"{i} files scanned successfully.")

jQuery get input value after keypress

You have to interrupt the execution thread to allow the input to update.

  $(document).ready(function(event) {
       $("#dSuggest").keypress(function() {
           //Interrupt the execution thread to allow input to update
               setTimeout(function() {
                   var dInput = $('input:text[name=dSuggest]').val();
                   console.log(dInput);
                   $(".dDimension:contains('" + dInput + "')").css("display","block");
               }, 0);
       });
  });

How to place a JButton at a desired location in a JFrame using Java

Use child.setLocation(0, 0) on the button, and parent.setLayout(null). Instead of using setBounds(...) on the JFrame to size it, consider using just setSize(...) and letting the OS position the frame.

//JPanel
JPanel pnlButton = new JPanel();
//Buttons
JButton btnAddFlight = new JButton("Add Flight");

public Control() {

    //JFrame layout
    this.setLayout(null);

    //JPanel layout
    pnlButton.setLayout(null);

    //Adding to JFrame
    pnlButton.add(btnAddFlight);
    add(pnlButton);

    // postioning
    pnlButton.setLocation(0,0);

C read file line by line

void readLine(FILE* file, char* line, int limit)
{
    int i;
    int read;

    read = fread(line, sizeof(char), limit, file);
    line[read] = '\0';

    for(i = 0; i <= read;i++)
    {
        if('\0' == line[i] || '\n' == line[i] || '\r' == line[i])
        {
            line[i] = '\0';
            break;
        }
    }

    if(i != read)
    {
        fseek(file, i - read + 1, SEEK_CUR);
    }
}

what about this one?

3-dimensional array in numpy

Read this article for better insight. Note: Numpy reports the shape of 3D arrays in the order layers, rows, columns.

https://opensourceoptions.com/blog/numpy-array-shapes-and-reshaping-arrays/#:~:text=3D%20arrays,order%20layers%2C%20rows%2C%20columns.

Converting bytes to megabytes

Divide by 2 to the power of 20, (1024*1024) bytes = 1 megabyte

1024*1024 = 1,048,576   
2^20 = 1,048,576
1,048,576/1,048,576 = 1  

It is the same thing.

Disable hover effects on mobile browsers

In my project we solved this issue using https://www.npmjs.com/package/postcss-hover-prefix and https://modernizr.com/ First we post-process output css files with postcss-hover-prefix. It adds .no-touch for all css hover rules.

const fs = require("fs");
const postcss = require("postcss");
const hoverPrfx = require("postcss-hover-prefix");

var css = fs.readFileSync(cssFileName, "utf8").toString();
postcss()
   .use(hoverPrfx("no-touch"))
   .process(css)
   .then((result) => {
      fs.writeFileSync(cssFileName, result);
   });

css

a.text-primary:hover {
  color: #62686d;
}

becomes

.no-touch a.text-primary:hover {
  color: #62686d;
}

At runtime Modernizr automatically adds css classes to html tag like this

<html class="wpfe-full-height js flexbox flexboxlegacy canvas canvastext webgl 
  no-touch 
  geolocation postmessage websqldatabase indexeddb hashchange
  history draganddrop websockets rgba hsla multiplebgs backgroundsize borderimage
  borderradius boxshadow textshadow opacity cssanimations csscolumns cssgradients
  cssreflections csstransforms csstransforms3d csstransitions fontface
  generatedcontent video audio localstorage sessionstorage webworkers
  applicationcache svg inlinesvg smil svgclippaths websocketsbinary">

Such post-processing of css plus Modernizr disables hover for touch devices and enables for others. In fact this approach was inspired by Bootstrap 4, how they solve the same issue: https://v4-alpha.getbootstrap.com/getting-started/browsers-devices/#sticky-hoverfocus-on-mobile

Is it possible to log all HTTP request headers with Apache?

Here is a list of all http-headers: http://en.wikipedia.org/wiki/List_of_HTTP_header_fields

And here is a list of all apache-logformats: http://httpd.apache.org/docs/2.0/mod/mod_log_config.html#formats

As you did write correctly, the code for logging a specific header is %{foobar}i where foobar is the name of the header. So, the only solution is to create a specific format string. When you expect a non-standard header like x-my-nonstandard-header, then use %{x-my-nonstandard-header}i. If your server is going to ignore this non-standard-header, why should you want to write it to your logfile? An unknown header has absolutely no effect to your system.

An established connection was aborted by the software in your host machine

This problem can be simply solved by closing Eclipse and restarting it. Eclipse sometimes fails to establish a connection with the Emulator, so this can happen in some cases.

Simplest code for array intersection in javascript

How about just using associative arrays?

function intersect(a, b) {
    var d1 = {};
    var d2 = {};
    var results = [];
    for (var i = 0; i < a.length; i++) {
        d1[a[i]] = true;
    }
    for (var j = 0; j < b.length; j++) {
        d2[b[j]] = true;
    }
    for (var k in d1) {
        if (d2[k]) 
            results.push(k);
    }
    return results;
}

edit:

// new version
function intersect(a, b) {
    var d = {};
    var results = [];
    for (var i = 0; i < b.length; i++) {
        d[b[i]] = true;
    }
    for (var j = 0; j < a.length; j++) {
        if (d[a[j]]) 
            results.push(a[j]);
    }
    return results;
}

What is an example of the simplest possible Socket.io example?

Edit: I feel it's better for anyone to consult the excellent chat example on the Socket.IO getting started page. The API has been quite simplified since I provided this answer. That being said, here is the original answer updated small-small for the newer API.

Just because I feel nice today:

index.html

<!doctype html>
<html>
    <head>
        <script src='/socket.io/socket.io.js'></script>
        <script>
            var socket = io();

            socket.on('welcome', function(data) {
                addMessage(data.message);

                // Respond with a message including this clients' id sent from the server
                socket.emit('i am client', {data: 'foo!', id: data.id});
            });
            socket.on('time', function(data) {
                addMessage(data.time);
            });
            socket.on('error', console.error.bind(console));
            socket.on('message', console.log.bind(console));

            function addMessage(message) {
                var text = document.createTextNode(message),
                    el = document.createElement('li'),
                    messages = document.getElementById('messages');

                el.appendChild(text);
                messages.appendChild(el);
            }
        </script>
    </head>
    <body>
        <ul id='messages'></ul>
    </body>
</html>

app.js

var http = require('http'),
    fs = require('fs'),
    // NEVER use a Sync function except at start-up!
    index = fs.readFileSync(__dirname + '/index.html');

// Send index.html to all requests
var app = http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(index);
});

// Socket.io server listens to our app
var io = require('socket.io').listen(app);

// Send current time to all connected clients
function sendTime() {
    io.emit('time', { time: new Date().toJSON() });
}

// Send current time every 10 secs
setInterval(sendTime, 10000);

// Emit welcome message on connection
io.on('connection', function(socket) {
    // Use socket to communicate with this particular client only, sending it it's own id
    socket.emit('welcome', { message: 'Welcome!', id: socket.id });

    socket.on('i am client', console.log);
});

app.listen(3000);

What is default color for text in textview?

You could use TextView.setTag/getTag to store original color before making changes. I would suggest to create an unique id resource in ids.xml to differentiate other tags if you have.

before setting to other colors:

if (textView.getTag(R.id.txt_default_color) == null) {
    textView.setTag(R.id.txt_default_color, textView.currentTextColor)
}

Changing back:

textView.getTag(R.id.txt_default_color) as? Int then {
    textView.setTextColor(this)
}

Generating statistics from Git repository

git-bars can show you "commits per day/week/year/etc".

You can install it with pip install git-bars (cf. https://github.com/knadh/git-bars)

The output looks like this:

$ git-bars -p month
370 commits over 19 month(s)
2019-10  7    ¯¯¯¯¯¯
2019-09  36   ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
2019-08  7    ¯¯¯¯¯¯
2019-07  10   ¯¯¯¯¯¯¯¯
2019-05  4    ¯¯¯
2019-04  2    ¯
2019-03  28   ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
2019-02  32   ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
2019-01  16   ¯¯¯¯¯¯¯¯¯¯¯¯¯¯
2018-12  41   ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
2018-11  52   ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
2018-10  57   ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
2018-09  37   ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
2018-08  17   ¯¯¯¯¯¯¯¯¯¯¯¯¯¯
2018-07  1    
2018-04  7    ¯¯¯¯¯¯
2018-03  12   ¯¯¯¯¯¯¯¯¯¯
2018-02  2    ¯
2016-01  2    ¯

How to loop through all elements of a form jQuery

Do one of the two jQuery serializers inside your form submit to get all inputs having a submitted value.

var criteria = $(this).find('input,select').filter(function () {
    return ((!!this.value) && (!!this.name));
}).serializeArray();

var formData = JSON.stringify(criteria);

serializeArray() will produce an array of names and values

0: {name: "OwnLast", value: "Bird"}
1: {name: "OwnFirst", value: "Bob"}
2: {name: "OutBldg[]", value: "PDG"}
3: {name: "OutBldg[]", value: "PDA"}

var criteria = $(this).find('input,select').filter(function () {
    return ((!!this.value) && (!!this.name));
}).serialize();

serialize() creates a text string in standard URL-encoded notation

"OwnLast=Bird&OwnFirst=Bob&OutBldg%5B%5D=PDG&OutBldg%5B%5D=PDA"

I want to vertical-align text in select box

I stumbled across this set of css properties which seem to vertically align the text in sized select elements in Firefox:

select
{
    box-sizing: content-box;
    -moz-box-sizing:content-box;
    -webkit-box-sizing:content-box;
}

If anything, though, it pushes the text down even farther in IE8. If I set the box-sizing property back to border-box, it at least doesn't make IE8 any worse (and FF still applies the -moz-box-sizing property). It would be nice to find a solution for IE, but I'm not holding my breath.

Edit: Nix this. It doesn't work after testing. For anyone interested, though, the problem seems to stem from built-in styles in FF's forms.css file affecting input and select elements. The property in question is line-height:normal !important. It cannot be overridden. I've tried. I discovered that if I delete the built-in property in Firebug I get a select element with reasonably vertically-centered text.

Pipe output and capture exit status in Bash

By combining PIPESTATUS[0] and the result of executing the exit command in a subshell, you can directly access the return value of your initial command:

command | tee ; ( exit ${PIPESTATUS[0]} )

Here's an example:

# the "false" shell built-in command returns 1
false | tee ; ( exit ${PIPESTATUS[0]} )
echo "return value: $?"

will give you:

return value: 1

Facebook Open Graph not clearing cache

We just ran into this, as it turns out, we weren't linting the right url, since the real url had a query string (duh, different page as far as a bot is concerned).

http://example.com/

!==

http://example.com/?utm_campaign=foo

The linter will recache your page, you don't have to wait.

do { ... } while (0) — what is it good for?

It's the only construct in C that you can use to #define a multistatement operation, put a semicolon after, and still use within an if statement. An example might help:

#define FOO(x) foo(x); bar(x)

if (condition)
    FOO(x);
else // syntax error here
    ...;

Even using braces doesn't help:

#define FOO(x) { foo(x); bar(x); }

Using this in an if statement would require that you omit the semicolon, which is counterintuitive:

if (condition)
    FOO(x)
else
    ...

If you define FOO like this:

#define FOO(x) do { foo(x); bar(x); } while (0)

then the following is syntactically correct:

if (condition)
    FOO(x);
else
    ....

Apache Spark: map vs mapPartitions?

Map :

  1. It processes one row at a time , very similar to map() method of MapReduce.
  2. You return from the transformation after every row.

MapPartitions

  1. It processes the complete partition in one go.
  2. You can return from the function only once after processing the whole partition.
  3. All intermediate results needs to be held in memory till you process the whole partition.
  4. Provides you like setup() map() and cleanup() function of MapReduce

Map Vs mapPartitions http://bytepadding.com/big-data/spark/spark-map-vs-mappartitions/

Spark Map http://bytepadding.com/big-data/spark/spark-map/

Spark mapPartitions http://bytepadding.com/big-data/spark/spark-mappartitions/

How to run a Maven project from Eclipse?

(Alt + Shift + X) , then M to Run Maven Build. You will need to specify the Maven goals you want on Run -> Run Configurations

How to consume a SOAP web service in Java

I will use CXF also you can think of AXIS 2 .

The best way to do it may be using JAX RS Refer this example

Example:

wsimport -p stockquote http://stockquote.xyz/quote?wsdl

This will generate the Java artifacts and compile them by importing the http://stockquote.xyz/quote?wsdl.

I

How can I get a count of the total number of digits in a number?

dividing a number by 10 will give you the left most digit then doing a mod 10 on the number gives the number without the first digit and repeat that till you have all the digits

Mailbox unavailable. The server response was: 5.7.1 Unable to relay for [email protected]

I was facing the identical problem and followed the (very clearly spelled out) steps in Vinod's reply, however this then created a different error:

Unable to read data from the transport connection: net_io_connectionclosed

I did a bit more digging and poking around and (while I'm not sure why this worked) I solved it by:
- Going back into IIS6.0 management console
- Open SMTP Virtual Server properties
- On General tab, changing the 'IP Address:' setting back to '(All Unassigned)'

Not sure why this works, but hopefully will help out someone facing the same problem in the future.

Creating an instance using the class name and calling constructor

If class has only one empty constructor (like Activity or Fragment etc, android classes):

Class<?> myClass = Class.forName("com.example.MyClass");    
Constructor<?> constructor = myClass.getConstructors()[0];

collapse cell in jupyter notebook

I had a similar issue and the "nbextensions" pointed out by @Energya worked very well and effortlessly. The install instructions are straight forward (I tried with anaconda on Windows) for the notebook extensions and for their configurator.

That said, I would like to add that the following extensions should be of interest.

  • Hide Input | This extension allows hiding of an individual codecell in a notebook. This can be achieved by clicking on the toolbar button: Hide Input

  • Collapsible Headings | Allows notebook to have collapsible sections, separated by headings Collapsible Headings

  • Codefolding | This has been mentioned but I add it for completeness Codefolding

How to declare an ArrayList with values?

Use this one:

ArrayList<String> x = new ArrayList(Arrays.asList("abc", "mno"));

Sorting multiple keys with Unix sort

Note that is may also be desired to stabilize the sort with the -s switch, so that equally ranked lines maintain their original relative order in the output too.

How to "set a breakpoint in malloc_error_break to debug"

In your screenshot, you didn't specify any module: try setting "libsystem_c.dylib"

enter image description here

I did that, and it works : breakpoint stops here (although the stacktrace often rise from some obscure system lib...)

Getting a link to go to a specific section on another page

I tried the above answer - using page.html#ID_name it gave me a 404 page doesn't exist error.

Then instead of using .html, I simply put a slash / before the # and that worked fine. So my example on the sending page between the link tags looks like:

<a href= "http://my website.com/target-page/#El_Chorro">El Chorro</a>

Just use / instead of .html.

How to use npm with ASP.NET Core

Instead of trying to serve the node modules folder, you can also use Gulp to copy what you need to wwwroot.

https://docs.asp.net/en/latest/client-side/using-gulp.html

This might help too

Visual Studio 2015 ASP.NET 5, Gulp task not copying files from node_modules

Setting up foreign keys in phpMyAdmin?

Step 1: You have to add the line: default-storage-engine = InnoDB under the [mysqld] section of your mysql config file (my.cnf or my.ini depending on your OS) and restart the mysqld service. enter image description here

Step 2: Now when you create the table you will see the type of table is: InnoDB

enter image description here

Step 3: Create both Parent and Child table. Now open the Child table and select the column U like to have the Foreign Key: Select the Index Key from Action Label as shown below.

enter image description here

Step 4: Now open the Relation View in the same child table from bottom near the Print View as shown below.

enter image description here Step 5: Select the column U like to have the Foreign key as Select the Parent column from the drop down. dbName.TableName.ColumnName

Select appropriate Values for ON DELETE and ON UPDATE enter image description here

Programmatically register a broadcast receiver

for LocalBroadcastManager

   Intent intent = new Intent("any.action.string");
   LocalBroadcastManager.getInstance(context).
                                sendBroadcast(intent);

and register in onResume

LocalBroadcastManager.getInstance(
                    ActivityName.this).registerReceiver(chatCountBroadcastReceiver, filter);

and Unregister it onStop

LocalBroadcastManager.getInstance(
                ActivityName.this).unregisterReceiver(chatCountBroadcastReceiver);

and recieve it ..

mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e("mBroadcastReceiver", "onReceive");
        }
    };

where IntentFilter is

 new IntentFilter("any.action.string")

Couldn't load memtrack module Logcat Error

I faced the same problem but When I changed the skin of AVD device to HVGA, it worked.

CSS horizontal scroll

Here's a solution with flexbox for images with variable width and height:

.container {
  display: flex;
  flex-wrap: no-wrap;
  overflow-x: auto;
  margin: 20px;
}
img {
  flex: 0 0 auto;
  width: auto;
  height: 100px;
  max-width: 100%;
  margin-right: 10px;
}

Example: JsFiddle

Get 2 Digit Number For The Month

append 0 before it by checking if the value falls between 1 and 9 by first casting it to varchar

select case when DATEPART(month, getdate()) between 1 and 9 
then '0' else '' end + cast(DATEPART(month, getdate()) as varchar(2))

Convert PEM traditional private key to PKCS8 private key

Try using following command. I haven't tried it but I think it should work.

openssl pkcs8 -topk8 -inform PEM -outform DER -in filename -out filename -nocrypt

#define macro for debug printing in C?

This is what I use:

#if DBG
#include <stdio.h>
#define DBGPRINT printf
#else
#define DBGPRINT(...) /**/  
#endif

It has the nice benefit to handle printf properly, even without additional arguments. In case DBG ==0, even the dumbest compiler gets nothing to chew upon, so no code is generated.

Easy way to print Perl array? (with a little formatting)

Just use join():

# assuming @array is your array:
print join(", ", @array);

Using jquery to get all checked checkboxes with a certain class name

$('.theClass:checkbox:checked') will give you all the checked checkboxes with the class theClass.

Fix CSS hover on iPhone/iPad/iPod

Some people don't know about this. You can apply it on div:hover and working on iPhone .

Add the following css to the element with :hover effect

.mm {
    cursor: pointer;
}

Good ways to manage a changelog using git?

I let the CI server pipe the following into a file named CHANGELOG for a each new release with the date set in the release-filename:

>git log --graph --all --date=relative --pretty=format:"%x09 %ad %d %s (%aN)"

JPA With Hibernate Error: [PersistenceUnit: JPA] Unable to build EntityManagerFactory

It worked for me after adding the following dependency in pom,

<dependency>
 <groupId>org.hibernate</groupId>
 <artifactId>hibernate-validator</artifactId>
 <version>4.3.0.Final</version>
</dependency>

No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain'

I know this is an older question, but I felt the answer from t3chb0t led me to the best path and felt like sharing. You don't even need to go so far as implementing all the formatter's methods. I did the following for the content-type "application/vnd.api+json" being returned by an API I was using:

public class VndApiJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
    public VndApiJsonMediaTypeFormatter()
    {
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/vnd.api+json"));
    }
}

Which can be used simply like the following:

HttpClient httpClient = new HttpClient("http://api.someaddress.com/");
HttpResponseMessage response = await httpClient.GetAsync("person");

List<System.Net.Http.Formatting.MediaTypeFormatter> formatters = new List<System.Net.Http.Formatting.MediaTypeFormatter>();
formatters.Add(new System.Net.Http.Formatting.JsonMediaTypeFormatter());
formatters.Add(new VndApiJsonMediaTypeFormatter());

var responseObject = await response.Content.ReadAsAsync<Person>(formatters);

Super simple and works exactly as I expected.

Where does MySQL store database files on Windows and what are the names of the files?

You can check my.ini file to see where the data folder is located.

Usually there is a folder {mysqlDirectory}/data

MySQL data storage:

Commands.frm
Commands.myd
Commands.myi

The *.frm files contain the table definitions. Your *.myi files are MyISAM index files. Your *.myd files contain the table data.

Edit/Update. Because of the interest shown in the question here is more info which is found also in the comments.

In Windows 8.1, the MySQL databases are stored (by default) here: C:\ProgramData\MySQL\MySQL Server 5.6\data

The folder C:\ProgramData is a hidden folder, so you must type it into Windows Explorer address to get there. In that data folder, the databases are named /{database_name_folder}/{database_tables_and_files}.

For instance,

C:\ProgramData\MySQL\MySQL Server 5.6\data\mydatabase\mytable.frm
C:\ProgramData\MySQL\MySQL Server 5.6\data\mydatabase\mytable.ibd 

Thank @marty-mcgee for this content

VARCHAR to DECIMAL

In case you need to ROUND the result, not truncate, can use this:

select convert(decimal(38,4), round(convert(decimal(38,10), '123456789.1234567'),4))

This will return the following:

'123456789.1235' for '123456789.1234567'
'123456789.1234' for '123456789.1234467'

How to get Printer Info in .NET?

I know it's an old posting, but nowadays the easier/quicker option is to use the enhanced printing services offered by the WPF framework (usable by non-WPF apps).

http://msdn.microsoft.com/en-us/library/System.Printing(v=vs.110).aspx

An example to retrieve the status of the printer queue and first job..

var queue = new LocalPrintServer().GetPrintQueue("Printer Name");
var queueStatus = queue.QueueStatus;
var jobStatus = queue.GetPrintJobInfoCollection().FirstOrDefault().JobStatus

Delete all objects in a list

If the goal is to delete the objects a and b themselves (which appears to be the case), forming the list [a, b] is not helpful. Instead, one should keep a list of strings used as the names of those objects. These allow one to delete the objects in a loop, by accessing the globals() dictionary.

c = ['a', 'b']
# create and work with a and b    
for i in c:
    del globals()[i]

PHP string "contains"

You can use stristr() or strpos(). Both return false if nothing is found.

The equivalent of wrap_content and match_parent in flutter?

Stack(
  children: [
    Container(color:Colors.red, height:200.0, width:200.0),
    Positioned.fill(
      child: Container(color: Colors. yellow),
    )
  ]
),

How to display a range input slider vertically

Without changing the position to absolute, see below. This supports all recent browsers as well.

_x000D_
_x000D_
.vranger {_x000D_
  margin-top: 50px;_x000D_
   transform: rotate(270deg);_x000D_
  -moz-transform: rotate(270deg); /*do same for other browsers if required*/_x000D_
}
_x000D_
<input type="range" class="vranger"/>
_x000D_
_x000D_
_x000D_

for very old browsers, you can use -sand-transform: rotate(10deg); from CSS sandpaper

or use

prefix selector such as -ms-transform: rotate(270deg); for IE9

Android View shadow

Create background drawable like this to show rounded shadow.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Drop Shadow Stack -->
    <item>
        <shape>
            <corners android:radius="4dp" />
            <padding android:bottom="1dp" android:left="1dp"
                     android:right="1dp"  android:top="1dp" />
            <solid android:color="#00CCCCCC" />
        </shape>
    </item>
    <item>
        <shape>
            <corners android:radius="4dp" />
            <padding android:bottom="1dp" android:left="1dp"
                     android:right="1dp"  android:top="1dp" />
            <solid android:color="#10CCCCCC" />
        </shape>
    </item>
    <item>
        <shape>
            <corners android:radius="4dp" />
            <padding android:bottom="1dp" android:left="1dp"
                     android:right="1dp"  android:top="1dp" />
            <solid android:color="#20d5d5d5" />
        </shape>
    </item>
    <item>
        <shape>
            <corners android:radius="6dp" />
            <padding android:bottom="1dp" android:left="1dp"
                     android:right="1dp"  android:top="1dp" />
            <solid android:color="#30cbcbcb" />
        </shape>
    </item>
    <item>
        <shape>
            <corners android:radius="4dp" />
            <padding android:bottom="1dp" android:left="1dp"
                     android:right="1dp"  android:top="1dp" />
            <solid android:color="#50bababa" />
        </shape>
    </item>

    <!-- Background -->
    <item>
        <shape>
            <solid android:color="@color/gray_100" />
            <corners android:radius="4dp" />
        </shape>
    </item>
</layer-list>

Swift Bridging Header import issue

After initial few days of struggle, I finally managed to successfully integrate Facebook signup to my iOS app. Here are the steps(I am assuming you have already installed Facebook SDK v4.1 or above in your machines):

  1. Add the Facebook frameworks - FBSDKCoreKit,FBSDKLoginKit under your project.
  2. Make no changes in the Build settings as FB SDK v4.1 and above doesn't need anymore bridging header files.
  3. Import the FBSDKCorekit, FBSDKLoginKit in ViewController.swift, AppDelegate.swift files
  4. Add informations in the pList as mentioned here

  5. Build your app. And wohoo! no compile time errors.

SameSite warning Chrome 77

When it comes to Google Analytics I found raik's answer at Secure Google tracking cookies very useful. It set secure and samesite to a value.

ga('create', 'UA-XXXXX-Y', {
    cookieFlags: 'max-age=7200;secure;samesite=none'
});

Also more info in this blog post

How to open child forms positioned within MDI parent in VB.NET?

Try Making the Child Form's StartPosition Property set to Center Parent. This you can select from the form Properties.

Convert tabs to spaces in Notepad++

The easy way:

  1. Highlight a single tab area
  2. Copy
  3. Bring up find/replace
  4. Paste into the find field
  5. Click into the replace field and hit the space bar
  6. Then replace all.

In Linux, how to tell how much memory processes are using?

More elegant approach:

echo "Memory usage for PID <>:"; for mem in {Private,Rss,Shared,Swap,Pss};do grep $mem /proc/<pid>/smaps | awk -v mem_type="$mem" '{i=i+$2} END {print mem_type,"memory usage:"i}' ;done

How to Specify "Vary: Accept-Encoding" header in .htaccess

I guess it's meant that you enable gzip compression for your css and js files, because that will enable the client to receive both gzip-encoded content and a plain content.

This is how to do it in apache2:

<IfModule mod_deflate.c>
    #The following line is enough for .js and .css
    AddOutputFilter DEFLATE js css

    #The following line also enables compression by file content type, for the following list of Content-Type:s
    AddOutputFilterByType DEFLATE text/html text/plain text/xml application/xml

    #The following lines are to avoid bugs with some browsers
    BrowserMatch ^Mozilla/4 gzip-only-text/html
    BrowserMatch ^Mozilla/4\.0[678] no-gzip
    BrowserMatch \bMSIE !no-gzip !gzip-only-text/html 
</IfModule>

And here's how to add the Vary Accept-Encoding header: [src]

<IfModule mod_headers.c>
  <FilesMatch "\.(js|css|xml|gz)$">
    Header append Vary: Accept-Encoding
  </FilesMatch>
</IfModule>

The Vary: header tells the that the content served for this url will vary according to the value of a certain request header. Here it says that it will serve different content for clients who say they Accept-Encoding: gzip, deflate (a request header), than the content served to clients that do not send this header. The main advantage of this, AFAIK, is to let intermediate caching proxies know they need to have two different versions of the same url because of such change.

How to change visibility of layout programmatically

TextView view = (TextView) findViewById(R.id.textView);
view.setText("Add your text here");
view.setVisibility(View.VISIBLE);

how to always round up to the next integer

I think the easiest way is to divide two integers and increase by one :

int r = list.Count() / 10;
r += (list.Count() % 10 == 0 ? 0 : 1);

No need of libraries or functions.

edited with the right code.

What does a circled plus mean?

People are saying that the symbol doesn't mean addition. This is true, but doesn't explain why a plus-like symbol is used for something that isn't addition.

The answer is that for modulo addition of 1-bit values, 0+0 == 1+1 == 0, and 0+1 == 1+0 == 1. Those are the same values as XOR.

So, plus in a circle in this context means "bitwise addition modulo-2". Which is, as everyone says, XOR for integers. It's common in mathematics to use plus in a circle for an operation which is a sort of addition, but isn't regular integer addition.

VBA error 1004 - select method of range class failed

You can't select a range without having first selected the sheet it is in. Try to select the sheet first and see if you still get the problem:

sourceSheetSum.Select
sourceSheetSum.Range("C3").Select

Why is SQL server throwing this error: Cannot insert the value NULL into column 'id'?

You need to set autoincrement property of id column to true when you create the table or you can alter your existing table to do this.

How to select current date in Hive SQL

To extract the year from current date

SELECT YEAR(CURRENT_DATE())

IBM Netezza

extract(year from now())

HIVE

SELECT YEAR(CURRENT_DATE())

nginx upload client_max_body_size issue

From the documentation:

It is necessary to keep in mind that the browsers do not know how to correctly show this error.

I suspect this is what's happening, if you inspect the HTTP to-and-fro using tools such as Firebug or Live HTTP Headers (both Firefox extensions) you'll be able to see what's really going on.