Programs & Examples On #Rs485

RS-485 (aka TIA-485-A, ANSI/TIA/EIA-485, TIA/EIA-485, EIA-485) is a standard defining the electrical characteristics of drivers and receivers for use in balanced digital multipoint systems.

Function to Calculate a CRC16 Checksum

There are several different varieties of CRC-16. See wiki page.

Every of those will return different results from the same input.

So you must carefully select correct one for your program.

POST Content-Length exceeds the limit

8388608 bytes is 8M, the default limit in PHP. Those changes to php.ini should indeed solve the problem (make sure your restart your Apache server after making them).

Memory limit shouldn't need to be changed here.

how to get the value of a textarea in jquery?

Value of textarea is also taken with val method:

var message = $('textarea#message').val();

Find integer index of rows with NaN in pandas dataframe

For DataFrame df:

import numpy as np
index = df['b'].index[df['b'].apply(np.isnan)]

will give you back the MultiIndex that you can use to index back into df, e.g.:

df['a'].ix[index[0]]
>>> 1.452354

For the integer index:

df_index = df.index.values.tolist()
[df_index.index(i) for i in index]
>>> [3, 6]

Jquery - animate height toggle

You can use the toggle-event(docs) method to assign 2 (or more) handlers that toggle with each click.

Example: http://jsfiddle.net/SQHQ2/1/

$("#topbar").toggle(function(){
    $(this).animate({height:40},200);
},function(){
    $(this).animate({height:10},200);
});

or you could create your own toggle behavior:

Example: http://jsfiddle.net/SQHQ2/

$("#topbar").click((function() {
    var i = 0;
    return function(){
        $(this).animate({height:(++i % 2) ? 40 : 10},200);
    }
})());

Understanding dict.copy() - shallow or deep?

It's not a matter of deep copy or shallow copy, none of what you're doing is deep copy.

Here:

>>> new = original 

you're creating a new reference to the the list/dict referenced by original.

while here:

>>> new = original.copy()
>>> # or
>>> new = list(original) # dict(original)

you're creating a new list/dict which is filled with a copy of the references of objects contained in the original container.

What is the difference between linear regression and logistic regression?

In case of Linear Regression the outcome is continuous while in case of Logistic Regression outcome is discrete (not continuous)

To perform Linear regression we require a linear relationship between the dependent and independent variables. But to perform Logistic regression we do not require a linear relationship between the dependent and independent variables.

Linear Regression is all about fitting a straight line in the data while Logistic Regression is about fitting a curve to the data.

Linear Regression is a regression algorithm for Machine Learning while Logistic Regression is a classification Algorithm for machine learning.

Linear regression assumes gaussian (or normal) distribution of dependent variable. Logistic regression assumes binomial distribution of dependent variable.

how to make jni.h be found?

Above answers give you a hardcoded path solution. This is bad on so many levels (java version change, OS change, etc).

Cleaner solution is to add:

JAVA_HOME = $(shell dirname $$(readlink -f $$(which java))|sed 's^jre/bin^^')

near the top of your makefile, then add:

-I$(JAVA_HOME)/include

To your include flags.

I am posting this because I ran into the same problem and spent too much time googling for wrong answers (I am building an app on multiple platforms so the build environment needs to be transportable).

Make a UIButton programmatically in Swift

Swift "Button factory" extension for UIButton (and while we're at it) also for UILabel like so:

extension UILabel
{
// A simple UILabel factory function
// returns instance of itself configured with the given parameters

// use example (in a UIView or any other class that inherits from UIView):

//   addSubview(   UILabel().make(     x: 0, y: 0, w: 100, h: 30,
//                                   txt: "Hello World!",
//                                 align: .center,
//                                   fnt: aUIFont,
//                              fntColor: UIColor.red)                 )
//

func make(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat,
          txt: String,
          align: NSTextAlignment,
          fnt: UIFont,
          fntColor: UIColor)-> UILabel
{
    frame = CGRect(x: x, y: y, width: w, height: h)
    adjustsFontSizeToFitWidth = true
    textAlignment = align
    text = txt
    textColor = fntColor
    font = fnt
    return self
}
// Of course, you can make more advanced factory functions etc.
// Also one could subclass UILabel, but this seems to be a     convenient case for an extension.
}


extension UIButton
{
// UIButton factory returns instance of UIButton
//usage example:

// addSubview(UIButton().make(x: btnx, y:100, w: btnw, h: btnh,
// title: "play", backColor: .red,
// target: self,
// touchDown: #selector(play), touchUp: #selector(stopPlay)))


func make(   x: CGFloat,y: CGFloat,
             w: CGFloat,h: CGFloat,
                  title: String, backColor: UIColor,
                  target: UIView,
                  touchDown:  Selector,
                  touchUp:    Selector ) -> UIButton
{
    frame = CGRect(x: x, y: y, width: w, height: h)
    backgroundColor = backColor
    setTitle(title, for: .normal)
    addTarget(target, action: touchDown, for: .touchDown)
    addTarget(target, action: touchUp  , for: .touchUpInside)
    addTarget(target, action: touchUp  , for: .touchUpOutside)

    return self
}
}

Tested in Swift in Xcode Version 9.2 (9C40b) Swift 4.x

Capturing URL parameters in request.GET

You have two common ways to do that in case your URL looks like that:

https://domain/method/?a=x&b=y

Version 1:

If a specific key is mandatory you can use:

key_a = request.GET['a']

This will return a value of a if the key exists and an exception if not.

Version 2:

If your keys are optional:

request.GET.get('a')

You can try that without any argument and this will not crash. So you can wrap it with try: except: and return HttpResponseBadRequest() in example. This is a simple way to make your code less complex, without using special exceptions handling.

How can I find the location of origin/master in git, and how do I change it?

I came to this question looking for an explanation about what the message "your branch is ahead by..." means, in the general scheme of git. There was no answer to that here, but since this question currently shows up at the top of Google when you search for the phrase "Your branch is ahead of 'origin/master'", and I have since figured out what the message really means, I thought I'd post the info here.

So, being a git newbie, I can see that the answer I needed was a distinctly newbie answer. Specifically, what the "your branch is ahead by..." phrase means is that there are files you've added and committed to your local repository, but have never pushed to the origin. The intent of this message is further obfuscated by the fact that "git diff", at least for me, showed no differences. It wasn't until I ran "git diff origin/master" that I was told that there were differences between my local repository, and the remote master.

So, to be clear:


"your branch is ahead by..." => You need to push to the remote master. Run "git diff origin/master" to see what the differences are between your local repository and the remote master repository.


Hope this helps other newbies.

(Also, I recognize that there are configuration subtleties that may partially invalidate this solution, such as the fact that the master may not actually be "remote", and that "origin" is a reconfigurable name used by convention, etc. But newbies do not care about that sort of thing. We want simple, straightforward answers. We can read about the subtleties later, once we've solved the pressing problem.)

Earl

ionic 2 - Error Could not find an installed version of Gradle either in Android Studio

@Ghandi: Could someone let me know why this answer is downvoted? Yeah, why? It has finally solved this problem ...

In my mind there is a bug when gradle or sdk or android studio is installed in a different directory then the standard one. I have S:\android\Android Studio and S:\android\sdk.

The solution by Ghandi installed gradle somewhere one more time, but I was really exasperated for this: one or two "gradle" more doesn't hurt me anymore

How do I configure git to ignore some files locally?

You can install some git aliases to make this process simpler. This edits the [alias] node of your .gitconfig file.

git config --global alias.ignore 'update-index --skip-worktree'
git config --global alias.unignore 'update-index --no-skip-worktree'
git config --global alias.ignored '!git ls-files -v | grep "^S"'

The shortcuts this installs for you are as follows:

  • git ignore config.xml
    • git will pretend that it doesn't see any changes upon config.xml — preventing you from accidentally committing those changes.
  • git unignore config.xml
    • git will resume acknowledging your changes to config.xml — allowing you again to commit those changes.
  • git ignored
    • git will list all the files which you are "ignoring" in the manner described above.

I built these by referring to phatmann's answer — which presents an --assume-unchanged version of the same.

The version I present uses --skip-worktree for ignoring local changes. See Borealid's answer for a full explanation of the difference, but essentially --skip-worktree's purpose is for developers to change files without the risk of committing their changes.

The git ignored command presented here uses git ls-files -v, and filters the list to show just those entries beginning with the S tag. The S tag denotes a file whose status is "skip worktree". For a full list of the file statuses shown by git ls-files: see the documentation for the -t option on git ls-files.

How to stash my previous commit?

It's works for me;

  1. Checkout on commit that is a origin of current branch.
  2. Create new branch from this commit.
  3. Checkout to new branch.
  4. Merge branch with code for stash in new branch.
  5. Make soft reset in new branch.
  6. Stash your target code.
  7. Remove new branch.

I recommend use something like a SourceTree for this.

Returning a promise in an async function in TypeScript

When you do new Promise((resolve)... the type inferred was Promise<{}> because you should have used new Promise<number>((resolve).

It is interesting that this issue was only highlighted when the async keyword was added. I would recommend reporting this issue to the TS team on GitHub.

There are many ways you can get around this issue. All the following functions have the same behavior:

const whatever1 = () => {
    return new Promise<number>((resolve) => {
        resolve(4);
    });
};

const whatever2 = async () => {
    return new Promise<number>((resolve) => {
        resolve(4);
    });
};

const whatever3 = async () => {
    return await new Promise<number>((resolve) => {
        resolve(4);
    });
};

const whatever4 = async () => {
    return Promise.resolve(4);
};

const whatever5 = async () => {
    return await Promise.resolve(4);
};

const whatever6 = async () => Promise.resolve(4);

const whatever7 = async () => await Promise.resolve(4);

In your IDE you will be able to see that the inferred type for all these functions is () => Promise<number>.

How can I pull from remote Git repository and override the changes in my local repository?

Provided that the remote repository is origin, and that you're interested in master:

git fetch origin
git reset --hard origin/master

This tells it to fetch the commits from the remote repository, and position your working copy to the tip of its master branch.

All your local commits not common to the remote will be gone.

Creating files in C++

#include <iostream>
#include <fstream>

int main() {
  std::ofstream o("Hello.txt");

  o << "Hello, World\n" << std::endl;

  return 0;
}

parent & child with position fixed, parent overflow:hidden bug

Fixed position elements are positioned relative to the browser window, so the parent element is basically irrelevant.

To get the effect you want, where the overflow on the parent clips the child, use position: absolute instead: http://jsfiddle.net/DBHUv/1/

Set default heap size in Windows

Try setting a Windows System Environment variable called _JAVA_OPTIONS with the heap size you want. Java should be able to find it and act accordingly.

python numpy machine epsilon

Another easy way to get epsilon is:

In [1]: 7./3 - 4./3 -1
Out[1]: 2.220446049250313e-16

remove duplicates from sql union

Union will remove duplicates. Union All does not.

IO Error: The Network Adapter could not establish the connection

I had the same problem, and this is how I fixed it. I was using the wrong port for my connection.

private final String DB_URL  = "jdbc:oracle:thin:@localhost:1521:orcll"; // 1521 my wrong port
  • go to your localhost
  • (my localhost address) : https://localhost:1158/em

  • login

    • user name
    • password
    • connect as --> normal
  • Below 'General' click on LISTENER_localhost

  • look at you port number
    • Net Address (ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1522)) Connect to port 1522
  • Edit you connection change port 1521 to 1522.

    • done

GitHub Error Message - Permission denied (publickey)

In case you are not accessing your own repository, or cloning inside a cloned repository (using some "git submodule... " commands):

In the home directory of your repository:

$ ls -a

1. Open ".gitmodules", and you will find something like this:

[submodule "XXX"]
    path = XXX
    url = [email protected]:YYY/XXX.git

Change the last line to be the HTTPS of the repository you need to pull:

[submodule "XXX"]
    path = XXX
    https://github.com/YYY/XXX.git

Save ".gitmodules", and run the command for submodules, and ".git" will be updated.

2. Open ".git", go to "config" file, and you will find something like this:

[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    ignorecase = true
    precomposeunicode = true
[remote "origin"]
    url = https://github.com/YYY/XXX.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master
[submodule "XXX"]
    url = [email protected]:YYY/XXX.git

Change the last line to be the HTTPS of the repository you need to pull:

    url = https://github.com/YYY/XXX.git

So, in this case, the main problem is simply with the url. HTTPS of any repository can be found now on top of the repository page.

Click events on Pie Charts in Chart.js

Chart.js 2.0 has made this even easier.

You can find it under common chart configuration in the documentation. Should work on more then pie graphs.

options:{
    onClick: graphClickEvent
}

function graphClickEvent(event, array){
    if(array[0]){
        foo.bar; 
    }
}

It triggers on the entire chart, but if you click on a pie the model of that pie including index which can be used to get the value.

How to search JSON tree with jQuery

There are some js-libraries that could help you with it:

You might also want to take a look at Lawnchair, which is a JSON-Document-Store which works in the browser and has all sorts of querying-mechanisms.

What does this symbol mean in JavaScript?

See the documentation on MDN about expressions and operators and statements.

Basic keywords and general expressions

this keyword:

var x = function() vs. function x() — Function declaration syntax

(function(){})() — IIFE (Immediately Invoked Function Expression)

someFunction()() — Functions which return other functions

=> — Equal sign, greater than: arrow function expression syntax

|> — Pipe, greater than: Pipeline operator

function*, yield, yield* — Star after function or yield: generator functions

[], Array() — Square brackets: array notation

If the square brackets appear on the left side of an assignment ([a] = ...), or inside a function's parameters, it's a destructuring assignment.

{key: value} — Curly brackets: object literal syntax (not to be confused with blocks)

If the curly brackets appear on the left side of an assignment ({ a } = ...) or inside a function's parameters, it's a destructuring assignment.

`${}` — Backticks, dollar sign with curly brackets: template literals

// — Slashes: regular expression literals

$ — Dollar sign in regex replace patterns: $$, $&, $`, $', $n

() — Parentheses: grouping operator


Property-related expressions

obj.prop, obj[prop], obj["prop"] — Square brackets or dot: property accessors

?., ?.[], ?.() — Question mark, dot: optional chaining operator

:: — Double colon: bind operator

new operator

...iter — Three dots: spread syntax; rest parameters


Increment and decrement

++, -- — Double plus or minus: pre- / post-increment / -decrement operators


Unary and binary (arithmetic, logical, bitwise) operators

delete operator

void operator

+, - — Plus and minus: addition or concatenation, and subtraction operators; unary sign operators

|, &, ^, ~ — Single pipe, ampersand, circumflex, tilde: bitwise OR, AND, XOR, & NOT operators

% — Percent sign: remainder operator

&&, ||, ! — Double ampersand, double pipe, exclamation point: logical operators

?? — Double question mark: nullish-coalescing operator

** — Double star: power operator (exponentiation)


Equality operators

==, === — Equal signs: equality operators

!=, !== — Exclamation point and equal signs: inequality operators


Bit shift operators

<<, >>, >>> — Two or three angle brackets: bit shift operators


Conditional operator

?:… — Question mark and colon: conditional (ternary) operator


Assignment operators

= — Equal sign: assignment operator

%= — Percent equals: remainder assignment

+= — Plus equals: addition assignment operator

&&=, ||=, ??= — Double ampersand, pipe, or question mark, followed by equal sign: logical assignments

Destructuring


Comma operator

, — Comma operator


Control flow

{} — Curly brackets: blocks (not to be confused with object literal syntax)

Declarations

var, let, const — Declaring variables


Label

label: — Colon: labels


# — Hash (number sign): Private methods or private fields

Add support library to Android Studio project

In Android Studio 1.0, this worked for me :-
Open the build.gradle (Module : app) file and paste this (at the end) :-

dependencies {
    compile "com.android.support:appcompat-v7:21.0.+"
}

Note that this dependencies is different from the dependencies inside buildscript in build.gradle (Project)
When you edit the gradle file, a message shows that you must sync the file. Press "Sync now"

Source : https://developer.android.com/tools/support-library/setup.html#add-library

jQuery hasAttr checking to see if there is an attribute on an element

Object.prototype.hasAttr = function(attr) {
    if(this.attr) {
        var _attr = this.attr(attr);
    } else {
        var _attr = this.getAttribute(attr);
    }
    return (typeof _attr !== "undefined" && _attr !== false && _attr !== null);      
};

I came a crossed this while writing my own function to do the same thing... I though I'd share in case someone else stumbles here. I added null because getAttribute() will return null if the attribute does not exist.

This method will allow you to check jQuery objects and regular javascript objects.

Network tools that simulate slow network connection

I've successfully used TMnetSim (bottom of the page, under “Other Tools” - the link says something like “ZIP: TMnetSim Network Simulator version 2.4 32-bit (600KB)”

It's not just for websites - you can slow connections to any TCP port. I was using it to simulate a slow SQL Server (port 1433).

How many bytes does one Unicode character take?

Unicode is a standard which provides a unique number for every character. These unique numbers are called code points (which is just unique code) to all characters existing in the world (some's are still to be added).

For different purposes, you might need to represent this code points in bytes (most programming languages do so), and here's where Character Encoding kicks in.

UTF-8, UTF-16, UTF-32 and so on are all Character Encodings, and Unicode's code points are represented in these encodings, in different ways.


UTF-8 encoding has a variable-width length, and characters, encoded in it, can occupy 1 to 4 bytes inclusive;

UTF-16 has a variable length and characters, encoded in it, can take either 1 or 2 bytes (which is 8 or 16 bits). This represents only part of all Unicode characters called BMP (Basic Multilingual Plane) and it's enough for almost all the cases. Java uses UTF-16 encoding for its strings and characters;

UTF-32 has fixed length and each character takes exactly 4 bytes (32 bits).

Spring @Autowired and @Qualifier

@Autowired to autowire(or search) by-type
@Qualifier to autowire(or search) by-name
Other alternate option for @Qualifier is @Primary

@Component
@Qualifier("beanname")
public class A{}

public class B{

//Constructor
@Autowired  
public B(@Qualifier("beanname")A a){...} //  you need to add @autowire also 

//property
@Autowired
@Qualifier("beanname")
private A a;

}

//If you don't want to add the two annotations, we can use @Resource
public class B{

//property
@Resource(name="beanname")
private A a;

//Importing properties is very similar
@Value("${property.name}")  //@Value know how to interpret ${}
private String name;
}

more about @value

Determine if Python is running inside virtualenv

Try using pip -V (notice capital V)

If you are running the virtual env. it'll show the path to the env.'s location.

jQuery - how can I find the element with a certain id?

As all html ids are unique in a valid html document why not search for the ID directly? If you're concerned if they type in an id that isn't a table then you can inspect the tag type that way?

Just an idea!

S

password-check directive in angularjs

The following is my take on the problem. This directive would compare against a form value instead of the scope.

'use strict';
(function () {
    angular.module('....').directive('equals', function ($timeout) {
        return {
            restrict: 'A',
            require: ['^form', 'ngModel'],
            scope: false,
            link: function ($scope, elem, attrs, controllers) {
                var validationKey = 'equals';
                var form = controllers[0];
                var ngModel = controllers[1];

                if (!ngModel) {
                    return;
                }

                //run after view has rendered
                $timeout(function(){
                    $scope.$watch(attrs.ngModel, validate);

                    $scope.$watch(form[attrs.equals], validate);
                }, 0);

                var validate = function () {
                    var value1 = ngModel.$viewValue;
                    var value2 = form[attrs.equals].$viewValue;
                    var validity = !value1 || !value2 || value1 === value2;
                    ngModel.$setValidity(validationKey, validity);
                    form[attrs.equals].$setValidity(validationKey,validity);
                };
            }
        };
    });
})();

in the HTML one now refers to the actual form instead of the scoped value:

<form name="myForm">
  <input type="text" name="value1" equals="value2">
  <input type="text" name="value2" equals="value1">
  <div ng-show="myForm.$invalid">The form is invalid!</div>
</form>

Android Studio is slow (how to speed up)?

Adding more memory helped me:

  1. Click "Help"
  2. Edit Custom VM Options

Android Studio 2.1.2 Edit Custom VM Options:

  1. Change values

like below:

-Xms512m    
-Xmx2560m   
-XX:MaxPermSize=700m    
-XX:ReservedCodeCacheSize=480m    
-XX:+UseCompressedOops
  1. Restart Android Studio

Making a Windows shortcut start relative to where the folder is?

You can make a relative shortcut manually by changing the file path. First in the usual context-menu you create a new shortcut of Windows for your file and in the properties -> location of your file:

%windir%\explorer.exe "..\data\run.bat"

How to view Plugin Manager in Notepad++

I changed the plugin folder name. Restart Notepad ++ It works now, a

How to get height of Keyboard?

Swift 4 and Constraints

To your tableview add a bottom constraint relative to the bottom safe area. In my case the constraint is called tableViewBottomLayoutConstraint.

@IBOutlet weak var tableViewBottomLayoutConstraint: NSLayoutConstraint!

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillAppear(notification:)), name: .UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillDisappear(notification:)), name: .UIKeyboardWillHide, object: nil)
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow , object: nil)
    NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide , object: nil)
}

@objc 
func keyboardWillAppear(notification: NSNotification?) {

    guard let keyboardFrame = notification?.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue else {
        return
    }

    let keyboardHeight: CGFloat
    if #available(iOS 11.0, *) {
        keyboardHeight = keyboardFrame.cgRectValue.height - self.view.safeAreaInsets.bottom
    } else {
        keyboardHeight = keyboardFrame.cgRectValue.height
    }

    tableViewBottomLayoutConstraint.constant = keyboardHeight
}

@objc 
func keyboardWillDisappear(notification: NSNotification?) {
    tableViewBottomLayoutConstraint.constant = 0.0
}

How do I set up a private Git repository on GitHub? Is it even possible?

Since January 7th, 2019, it is possible: unlimited free private repositories on GitHub!
... But for up to three collaborators per private repository.

Nat Friedman just announced it by twitter:

Today(!) we’re thrilled to announce unlimited free private repos for all GitHub users, and a new simplified Enterprise offering:

"New year, new GitHub: Announcing unlimited free private repos and unified Enterprise offering"

For the first time, developers can use GitHub for their private projects with up to three collaborators per repository for free.

Many developers want to use private repos to apply for a job, work on a side project, or try something out in private before releasing it publicly.
Starting today, those scenarios, and many more, are possible on GitHub at no cost.

Public repositories are still free (of course—no changes there) and include unlimited collaborators.

Make absolute positioned div expand parent div height

I had a similar problem. To solve this (instead of calculate the iframe's height using the body, document or window) I created a div that wraps the whole page content (a div with an id="page" for example) and then I used its height.

Sanitizing strings to make them URL and filename safe?

// CLEAN ILLEGAL CHARACTERS
function clean_filename($source_file)
{
    $search[] = " ";
    $search[] = "&";
    $search[] = "$";
    $search[] = ",";
    $search[] = "!";
    $search[] = "@";
    $search[] = "#";
    $search[] = "^";
    $search[] = "(";
    $search[] = ")";
    $search[] = "+";
    $search[] = "=";
    $search[] = "[";
    $search[] = "]";

    $replace[] = "_";
    $replace[] = "and";
    $replace[] = "S";
    $replace[] = "_";
    $replace[] = "";
    $replace[] = "";
    $replace[] = "";
    $replace[] = "";
    $replace[] = "";
    $replace[] = "";
    $replace[] = "";
    $replace[] = "";
    $replace[] = "";
    $replace[] = "";

    return str_replace($search,$replace,$source_file);

} 

jQuery autoComplete view all on click?

I can't see an obvious way to do that in the docs, but you try triggering the focus (or click) event on the autocomplete enabled textbox:

$('#myButton').click(function() {
   $('#autocomplete').trigger("focus"); //or "click", at least one should work
});

What is the difference between a token and a lexeme?

Lexeme is basically the unit of a token and it is basically sequence of characters that matches the token and helps to break the source code into tokens.

For example: If the source is x=b, then the lexemes would be x, =, b and the tokens would be <id, 0>, <=>, <id, 1>.

Failed to build gem native extension — Rails install

sudo apt-get install ruby-dev

worked for me

Excel Macro - Select all cells with data and format as table

Try this one for current selection:

Sub A_SelectAllMakeTable2()
    Dim tbl As ListObject
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

or equivalent of your macro (for Ctrl+Shift+End range selection):

Sub A_SelectAllMakeTable()
    Dim tbl As ListObject
    Dim rng As Range

    Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

How do I get a list of files in a directory in C++?

Here's an example in C on Linux. That's if, you're on Linux and don't mind doing this small bit in ANSI C.

#include <dirent.h>

DIR *dpdf;
struct dirent *epdf;

dpdf = opendir("./");
if (dpdf != NULL){
   while (epdf = readdir(dpdf)){
      printf("Filename: %s",epdf->d_name);
      // std::cout << epdf->d_name << std::endl;
   }
}
closedir(dpdf);

How can I use the HTML5 canvas element in IE?

If you need to use IE8, you can try this JavaScript library for vector graphics. It is like solving the "canvas" and "SVG" incompatibilities of IE8 at the same time.

Raphaël

I have just try it in a fast example and it works correctly. I don't know how legible is the source code but I hope it helps you. As they said in its site, the library is compatible with very old explorers.

Raphaël currently supports Firefox 3.0+, Safari 3.0+, Chrome 5.0+, Opera 9.5+ and Internet Explorer 6.0+.

How do I put an image into my picturebox using ImageLocation?

Setting the image using picture.ImageLocation() works fine, but you are using a relative path. Check your path against the location of the .exe after it is built.

For example, if your .exe is located at:

<project folder>/bin/Debug/app.exe

The image would have to be at:

<project folder>/bin/Image/1.jpg


Of course, you could just set the image at design-time (the Image property on the PictureBox property sheet).

If you must set it at run-time, one way to make sure you know the location of the image is to add the image file to your project. For example, add a new folder to your project, name it Image. Right-click the folder, choose "Add existing item" and browse to your image (be sure the file filter is set to show image files). After adding the image, in the property sheet set the Copy to Output Directory to Copy if newer.

At this point the image file will be copied when you build the application and you can use

picture.ImageLocation = @"Image\1.jpg"; 

Setting a backgroundImage With React Inline Styles

You Can try usimg

backgroundImage: url(process.env.PUBLIC_URL + "/      assets/image_location")

display html page with node.js

If your goal is to simply display some static files you can use the Connect package. I have had some success (I'm still pretty new to NodeJS myself), using it and the twitter bootstrap API in combination.

at the command line

:\> cd <path you wish your server to reside>
:\> npm install connect

Then in a file (I named) Server.js

var connect = require('connect'),
   http = require('http');
connect()
   .use(connect.static('<pathyouwishtoserve>'))
   .use(connect.directory('<pathyouwishtoserve>'))
   .listen(8080);

Finally

:\>node Server.js

Caveats:

If you don't want to display the directory contents, exclude the .use(connect.directory line.

So I created a folder called "server" placed index.html in the folder and the bootstrap API in the same folder. Then when you access the computers IP:8080 it's automagically going to use the index.html file.

If you want to use port 80 (so just going to http://, and you don't have to type in :8080 or some other port). you'll need to start node with sudo, I'm not sure of the security implications but if you're just using it for an internal network, I don't personally think it's a big deal. Exposing to the outside world is another story.

Update 1/28/2014:

I haven't had to do the following on my latest versions of things, so try it out like above first, if it doesn't work (and you read the errors complaining it can't find nodejs), go ahead and possibly try the below.

End Update

Additionally when running in ubuntu I ran into a problem using nodejs as the name (with NPM), if you're having this problem, I recommend using an alias or something to "rename" nodejs to node.

Commands I used (for better or worse):

Create a new file called node

:\>gedit /usr/local/bin/node
#!/bin/bash
exec /nodejs "$@"

sudo chmod -x /usr/local/bin/node

That ought to make

node Server.js 

work just fine

How to connect Robomongo to MongoDB

If there is no authentication enabled (username/password) and still unable to connect. Just use localhost and default port. Click Test and Save, if test connection is successful.

enter image description here

enter image description here

enter image description here

enter image description here

Regards Jagdish

How can I list all foreign keys referencing a given table in SQL Server?

Not sure why no one suggested but I use sp_fkeys to query foreign keys for a given table:

EXEC sp_fkeys 'TableName'

You can also specify the schema:

EXEC sp_fkeys @pktable_name = 'TableName', @pktable_owner = 'dbo'

Without specifying the schema, the docs state the following:

If pktable_owner is not specified, the default table visibility rules of the underlying DBMS apply.

In SQL Server, if the current user owns a table with the specified name, that table's columns are returned. If pktable_owner is not specified and the current user does not own a table with the specified pktable_name, the procedure looks for a table with the specified pktable_name owned by the database owner. If one exists, that table's columns are returned.

How to comment out particular lines in a shell script

Yes (although it's a nasty hack). You can use a heredoc thus:

#!/bin/sh

# do valuable stuff here
touch /tmp/a

# now comment out all the stuff below up to the EOF
echo <<EOF
...
...
...
EOF

What's this doing ? A heredoc feeds all the following input up to the terminator (in this case, EOF) into the nominated command. So you can surround the code you wish to comment out with

echo <<EOF
...
EOF

and it'll take all the code contained between the two EOFs and feed them to echo (echo doesn't read from stdin so it all gets thrown away).

Note that with the above you can put anything in the heredoc. It doesn't have to be valid shell code (i.e. it doesn't have to parse properly).

This is very nasty, and I offer it only as a point of interest. You can't do the equivalent of C's /* ... */

Java program to find the largest & smallest number in n numbers without using arrays

Try this :

int smallest = Integer.MAX_VALUE;
for(int i=0;i<n;i++)
{
   num=input.nextInt();
   if(num>large)
   {
       large=num;
   }
   if(num<smallest){
       smallest=num;
   }

Is there a need for range(len(a))?

I have an use case I don't believe any of your examples cover.

boxes = [b1, b2, b3]
items = [i1, i2, i3, i4, i5]
for j in range(len(boxes)):
    boxes[j].putitemin(items[j])

I'm relatively new to python though so happy to learn a more elegant approach.

How to assign multiple classes to an HTML container?

you need to put a dot between the class like

class="column.wrapper">

CSS selector for "foo that contains bar"?

Only thing that comes even close is the :contains pseudo class in CSS3, but that only selects textual content, not tags or elements, so you're out of luck.

A simpler way to select a parent with specific children in jQuery can be written as (with :has()):

$('#parent:has(#child)');

Difference between two dates in MySQL

This function takes the difference between two dates and shows it in a date format yyyy-mm-dd. All you need is to execute the code below and then use the function. After executing you can use it like this

SELECT datedifference(date1, date2)
FROM ....
.
.
.
.


DELIMITER $$

CREATE FUNCTION datedifference(date1 DATE, date2 DATE) RETURNS DATE
NO SQL

BEGIN
    DECLARE dif DATE;
    IF DATEDIFF(date1, DATE(CONCAT(YEAR(date1),'-', MONTH(date1), '-', DAY(date2)))) < 0    THEN
                SET dif=DATE_FORMAT(
                                        CONCAT(
                                            PERIOD_DIFF(date_format(date1, '%y%m'),date_format(date2, '%y%m'))DIV 12 , 
                                            '-',
                                            PERIOD_DIFF(date_format(date1, '%y%m'),date_format(date2, '%y%m'))% 12 , 
                                            '-',
                                            DATEDIFF(date1, DATE(CONCAT(YEAR(date1),'-', MONTH(DATE_SUB(date1, INTERVAL 1 MONTH)), '-', DAY(date2))))),
                                        '%Y-%m-%d');
    ELSEIF DATEDIFF(date1, DATE(CONCAT(YEAR(date1),'-', MONTH(date1), '-', DAY(date2)))) < DAY(LAST_DAY(DATE_SUB(date1, INTERVAL 1 MONTH))) THEN
                SET dif=DATE_FORMAT(
                                        CONCAT(
                                            PERIOD_DIFF(date_format(date1, '%y%m'),date_format(date2, '%y%m'))DIV 12 , 
                                            '-',
                                            PERIOD_DIFF(date_format(date1, '%y%m'),date_format(date2, '%y%m'))% 12 , 
                                            '-',
                                            DATEDIFF(date1, DATE(CONCAT(YEAR(date1),'-', MONTH(date1), '-', DAY(date2))))),
                                        '%Y-%m-%d');
    ELSE
                SET dif=DATE_FORMAT(
                                        CONCAT(
                                            PERIOD_DIFF(date_format(date1, '%y%m'),date_format(date2, '%y%m'))DIV 12 , 
                                            '-',
                                            PERIOD_DIFF(date_format(date1, '%y%m'),date_format(date2, '%y%m'))% 12 , 
                                            '-',
                                            DATEDIFF(date1, DATE(CONCAT(YEAR(date1),'-', MONTH(date1), '-', DAY(date2))))),
                                        '%Y-%m-%d');
    END IF;

RETURN dif;
END $$
DELIMITER;

Regular Expression Validation For Indian Phone Number and Mobile number

This works really fine:

\+?\d[\d -]{8,12}\d

Matches:

03598245785
9775876662
0 9754845789
0-9778545896
+91 9456211568
91 9857842356
919578965389
987-98723-9898
+91 98780 98802
06421223054
9934-05-4851
WAQU9876567892
ABCD9876541212
98723-98765

Does NOT match:

2343
234-8700
1 234 765

Getting "Lock wait timeout exceeded; try restarting transaction" even though I'm not using a transaction

In my instance, I was running an abnormal query to fix data. If you lock the tables in your query, then you won't have to deal with the Lock timeout:

LOCK TABLES `customer` WRITE;
update customer set account_import_id = 1;
UNLOCK TABLES;

This is probably not a good idea for normal use.

For more info see: MySQL 8.0 Reference Manual

declaring a priority_queue in c++ with a custom comparator

In case this helps anyone :

static bool myFunction(Node& p1, Node& p2) {}
priority_queue <Node, vector<Node>, function<bool(Node&, Node&)>> pq1(myFunction);

Using onBackPressed() in Android Fragments

I found a new way to do it without interfaces. You only need to add the below code to the Fragment’s onCreate() method:

//overriding the fragment's oncreate 
override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        //calling onBackPressedDispatcher and adding call back

        requireActivity().onBackPressedDispatcher.addCallback(this) {

      //do stuff here
            
        }
    }

How to add new elements to an array?

Use a List<String>, such as an ArrayList<String>. It's dynamically growable, unlike arrays (see: Effective Java 2nd Edition, Item 25: Prefer lists to arrays).

import java.util.*;
//....

List<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
System.out.println(list); // prints "[1, 2, 3]"

If you insist on using arrays, you can use java.util.Arrays.copyOf to allocate a bigger array to accomodate the additional element. This is really not the best solution, though.

static <T> T[] append(T[] arr, T element) {
    final int N = arr.length;
    arr = Arrays.copyOf(arr, N + 1);
    arr[N] = element;
    return arr;
}

String[] arr = { "1", "2", "3" };
System.out.println(Arrays.toString(arr)); // prints "[1, 2, 3]"
arr = append(arr, "4");
System.out.println(Arrays.toString(arr)); // prints "[1, 2, 3, 4]"

This is O(N) per append. ArrayList, on the other hand, has O(1) amortized cost per operation.

See also

How to get Spinner selected item value to string?

Try this:

String text = mySpinner.getSelectedItem().toString();

Like this you can get value for different Spinners.

Event detect when css property changed using Jquery

You can't. CSS does not support "events". Dare I ask what you need it for? Check out this post here on SO. I can't think of a reason why you would want to hook up an event to a style change. I'm assuming here that the style change is triggered somwhere else by a piece of javascript. Why not add extra logic there?

Maximum on http header values?

I also found that in some cases the reason for 502/400 in case of many headers could be because of a large number of headers without regard to size. from the docs

tune.http.maxhdr Sets the maximum number of headers in a request. When a request comes with a number of headers greater than this value (including the first line), it is rejected with a "400 Bad Request" status code. Similarly, too large responses are blocked with "502 Bad Gateway". The default value is 101, which is enough for all usages, considering that the widely deployed Apache server uses the same limit. It can be useful to push this limit further to temporarily allow a buggy application to work by the time it gets fixed. Keep in mind that each new header consumes 32bits of memory for each session, so don't push this limit too high.

https://cbonte.github.io/haproxy-dconv/configuration-1.5.html#3.2-tune.http.maxhdr

How do I manually configure a DataSource in Java?

One thing you might want to look at is the Commons DBCP project. It provides a BasicDataSource that is configured fairly similarly to your example. To use that you need the database vendor's JDBC JAR in your classpath and you have to specify the vendor's driver class name and the database URL in the proper format.

Edit:

If you want to configure a BasicDataSource for MySQL, you would do something like this:

BasicDataSource dataSource = new BasicDataSource();

dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUsername("username");
dataSource.setPassword("password");
dataSource.setUrl("jdbc:mysql://<host>:<port>/<database>");
dataSource.setMaxActive(10);
dataSource.setMaxIdle(5);
dataSource.setInitialSize(5);
dataSource.setValidationQuery("SELECT 1");

Code that needs a DataSource can then use that.

difference between new String[]{} and new String[] in java

You have a choice, when you create an object array (as opposed to an array of primitives).

One option is to specify a size for the array, in which case it will just contain lots of nulls.

String[] array = new String[10]; // Array of size 10, filled with nulls.

The other option is to specify what will be in the array.

String[] array = new String[] {"Larry", "Curly", "Moe"};  // Array of size 3, filled with stooges.

But you can't mix the two syntaxes. Pick one or the other.

Can a relative sitemap url be used in a robots.txt?

Google crawlers are not smart enough, they can't crawl relative URLs, that's why it's always recommended to use absolute URL's for better crawlability and indexability.

Therefore, you can not use this variation

> sitemap: /sitemap.xml

Recommended syntax is

Sitemap: https://www.yourdomain.com/sitemap.xml

Note:

  • Don't forgot to capitalise the first letter in "sitemap"
  • Don't forgot to put space after "Sitemap:"

Passing variables to the next middleware using next() in Express.js

Attach your variable to the req object, not res.

Instead of

res.somevariable = variable1;

Have:

req.somevariable = variable1;

As others have pointed out, res.locals is the recommended way of passing data through middleware.

Set disable attribute based on a condition for Html.TextBoxFor

I like Darin method. But quick way to solve this,

Html.TextBox("Expiry", null, new { style = "width: 70px;", maxlength = "10", id = "expire-date", disabled = "disabled" }).ToString().Replace("disabled=\"disabled\"", (1 == 2 ? "" : "disabled=\"disabled\""))

How do I create a copy of an object in PHP?

If you want to fully copy properties of an object in a different instance, you may want to use this technique:

Serialize it to JSON and then de-serialize it back to Object.

Batch command date and time in file name

So you want to generate date in format YYYYMMDD_hhmmss. As %date% and %time% formats are locale dependant you might need more robust ways to get a formatted date.

Here's one option:

@if (@X)==(@Y) @end /*
    @cscript //E:JScript //nologo "%~f0"
    @exit /b %errorlevel%
@end*/
var todayDate = new Date();
todayDate = "" + 
    todayDate.getFullYear() + 
    ("0" + (todayDate.getMonth() + 1)).slice(-2) +
    ("0" + todayDate.getDate()).slice(-2) + 
    "_" + 
    ("0" + todayDate.getHours()).slice(-2) +
    ("0" + todayDate.getMinutes()).slice(-2) +
    ("0" + todayDate.getSeconds()).slice(-2) ;
WScript.Echo(todayDate);

and if you save the script as jsdate.bat you can assign it as a value :

for /f %%a in ('jsdate.bat') do @set "fdate=%%a"
echo %fdate%

or directly from command prompt:

for /f %a in ('jsdate.bat') do @set "fdate=%a"

Or you can use powershell which probably is the way that requires the less code:

for /f %%# in ('powershell Get-Date -Format "yyyyMMdd_HHmmss"') do set "fdate=%%#"

How to set thousands separator in Java?

This should work (untested, based on JavaDoc):

DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance(Locale.US);
DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();

symbols.setGroupingSeparator(' ');
formatter.setDecimalFormatSymbols(symbols);
System.out.println(formatter.format(bd.longValue()));

According to the JavaDoc, the cast in the first line should be save for most locales.

Cloud Firestore collection count

As with many questions, the answer is - It depends.

You should be very careful when handling large amounts of data on the front end. On top of making your front end feel sluggish, Firestore also charges you $0.60 per million reads you make.


Small collection (less than 100 documents)

Use with care - Frontend user experience may take a hit

Handling this on the front end should be fine as long as you are not doing too much logic with this returned array.

db.collection('...').get().then(snap => {
   size = snap.size // will return the collection size
});

Medium collection (100 to 1000 documents)

Use with care - Firestore read invocations may cost a lot

Handling this on the front end is not feasible as it has too much potential to slow down the users system. We should handle this logic server side and only return the size.

The drawback to this method is you are still invoking firestore reads (equal to the size of your collection), which in the long run may end up costing you more than expected.

Cloud Function:

...
db.collection('...').get().then(snap => {
    res.status(200).send({length: snap.size});
});

Front End:

yourHttpClient.post(yourCloudFunctionUrl).toPromise().then(snap => {
     size = snap.length // will return the collection size
})

Large collection (1000+ documents)

Most scalable solution


FieldValue.increment()

As of April 2019 Firestore now allows incrementing counters, completely atomically, and without reading the data prior. This ensures we have correct counter values even when updating from multiple sources simultaneously (previously solved using transactions), while also reducing the number of database reads we perform.


By listening to any document deletes or creates we can add to or remove from a count field that is sitting in the database.

See the firestore docs - Distributed Counters Or have a look at Data Aggregation by Jeff Delaney. His guides are truly fantastic for anyone using AngularFire but his lessons should carry over to other frameworks as well.

Cloud Function:

export const documentWriteListener = 
    functions.firestore.document('collection/{documentUid}')
    .onWrite((change, context) => {

    if (!change.before.exists) {
        // New document Created : add one to count

        db.doc(docRef).update({numberOfDocs: FieldValue.increment(1)});
    
    } else if (change.before.exists && change.after.exists) {
        // Updating existing document : Do nothing

    } else if (!change.after.exists) {
        // Deleting document : subtract one from count

        db.doc(docRef).update({numberOfDocs: FieldValue.increment(-1)});

    }

return;
});

Now on the frontend you can just query this numberOfDocs field to get the size of the collection.

How to efficiently check if variable is Array or Object (in NodeJS & V8)?

All objects are instances of at least one class – Object – in ECMAScript. You can only differentiate between instances of built-in classes and normal objects using Object#toString. They all have the same level of complexity, for instance, whether they are created using {} or the new operator.

Object.prototype.toString.call(object) is your best bet to differentiate between normal objects and instances of other built-in classes, as object === Object(object) doesn't work here. However, I can't see a reason why you would need to do what you're doing, so perhaps if you share the use case I can offer a little more help.

android pick images from gallery

Just to offer an update to the answer for people with API min 19, per the docs:

On Android 4.4 (API level 19) and higher, you have the additional option of using the ACTION_OPEN_DOCUMENT intent, which displays a system-controlled picker UI controlled that allows the user to browse all files that other apps have made available. From this single UI, the user can pick a file from any of the supported apps.

On Android 5.0 (API level 21) and higher, you can also use the ACTION_OPEN_DOCUMENT_TREE intent, which allows the user to choose a directory for a client app to access.

Open files using storage access framework - Android Docs

     val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
     intent.type = "image/*"
     startActivityForResult(intent, PICK_IMAGE_REQUEST_CODE)

Cant get text of a DropDownList in code - can get value but not text

What about

lstCountry.Items[lstCountry.SelectedIndex].Text;

How to enable production mode?

My Angular 2 project doesn't have the "main.ts" file mentioned other answers, but it does have a "boot.ts" file, which seems to be about the same thing. (The difference is probably due to different versions of Angular.)

Adding these two lines after the last import directive in "boot.ts" worked for me:

import { enableProdMode } from "@angular/core";
enableProdMode();

Google maps responsive resize

After few years, I moved to leaflet map and I have fixed this issue completely, the following could be applied to google maps too:

    var headerHeight = $("#navMap").outerHeight();
    var footerHeight = $("footer").outerHeight();
    var windowHeight = window.innerHeight;
    var mapContainerHeight = headerHeight + footerHeight;
    var totalMapHeight = windowHeight - mapContainerHeight;
    $("#map").css("margin-top", headerHeight);
    $("#map").height(totalMapHeight);

    $(window).resize(function(){
        var headerHeight = $("#navMap").outerHeight();
        var footerHeight = $("footer").outerHeight();
        var windowHeight = window.innerHeight;
        var mapContainerHeight = headerHeight + footerHeight;
        var totalMapHeight = windowHeight - mapContainerHeight;
        $("#map").css("margin-top", headerHeight);
        $("#map").height(totalMapHeight);
        map.fitBounds(group1.getBounds());
    });

Troubleshooting BadImageFormatException

What I found worked was checking the "Use the 64 bit version of IIS Express for Web Sites and Projects" option under the Projects and Solutions => Web Projects section under the Tools=>Options menu.

Webpack - webpack-dev-server: command not found

For global installation : npm install webpack-dev-server -g

For local installation npm install --save-dev webpack

When you refer webpack in package.json file, it tries to look it in location node_modules\.bin\

After local installation, file wbpack will get created in location: \node_modules\.bin\webpack

int to hex string

Try the following:

ToString("X4")

See The X format specifier on MSDN.

The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files

I've seen occasional problems with Eclipse forgetting that built-in classes (including Object and String) exist. The way I've resolved them is to:

  • On the Project menu, turn off "Build Automatically"
  • Quit and restart Eclipse
  • On the Project menu, choose "Clean…" and clean all projects
  • Turn "Build Automatically" back on and let it rebuild everything.

This seems to make Eclipse forget whatever incorrect cached information it had about the available classes.

Insert the same fixed value into multiple rows

UPDATE `table` SET table_column='test';

What is a Y-combinator?

Here is a JavaScript implementation of the Y-Combinator and the Factorial function (from Douglas Crockford's article, available at: http://javascript.crockford.com/little.html).

function Y(le) {
    return (function (f) {
        return f(f);
    }(function (f) {
        return le(function (x) {
            return f(f)(x);
        });
    }));
}

var factorial = Y(function (fac) {
    return function (n) {
        return n <= 2 ? n : n * fac(n - 1);
    };
});

var number120 = factorial(5);

Global variables in AngularJS

If you just want to store a value, according to the Angular documentation on Providers, you should use the Value recipe:

var myApp = angular.module('myApp', []);
myApp.value('clientId', 'a12345654321x');

Then use it in a controller like this:

myApp.controller('DemoController', ['clientId', function DemoController(clientId) {
    this.clientId = clientId;
}]);

The same thing can be achieved using a Provider, Factory, or Service since they are "just syntactic sugar on top of a provider recipe" but using Value will achieve what you want with minimal syntax.

The other option is to use $rootScope, but it's not really an option because you shouldn't use it for the same reasons you shouldn't use global variables in other languages. It's advised to be used sparingly.

Since all scopes inherit from $rootScope, if you have a variable $rootScope.data and someone forgets that data is already defined and creates $scope.data in a local scope you will run into problems.


If you want to modify this value and have it persist across all your controllers, use an object and modify the properties keeping in mind Javascript is pass by "copy of a reference":

myApp.value('clientId', { value: 'a12345654321x' });
myApp.controller('DemoController', ['clientId', function DemoController(clientId) {
    this.clientId = clientId;
    this.change = function(value) {
        clientId.value = 'something else';
    }
}];

JSFiddle example

datatable jquery - table header width not aligned with body width

I was facing the same issue. I added the scrollX: true property for the dataTable and it worked. There is no need to change the CSS for datatable

jQuery('#myTable').DataTable({
                            "fixedHeader":true,
                            "scrollY":"450px",
                            "scrollX":true,
                            "paging":   false,
                            "ordering": false,
                            "info":     false,
                            "searching": false,
                            "scrollCollapse": true
                            });

How to add new line into txt file

Why not do it with one method call:

File.AppendAllLines("file.txt", new[] { DateTime.Now.ToString() });

which will do the newline for you, and allow you to insert multiple lines at once if you want.

How to Find Item in Dictionary Collection?

thisTag = _tags.FirstOrDefault(t => t.Key == tag);

is an inefficient and a little bit strange way to find something by key in a dictionary. Looking things up for a Key is the basic function of a Dictionary.

The basic solution would be:

if (_tags.Containskey(tag)) { string myValue = _tags[tag]; ... }

But that requires 2 lookups.

TryGetValue(key, out value) is more concise and efficient, it only does 1 lookup. And that answers the last part of your question, the best way to do a lookup is:

string myValue;
if (_tags.TryGetValue(tag, out myValue)) { /* use myValue */ }

VS 2017 update, for C# 7 and beyond we can declare the result variable inline:

if (_tags.TryGetValue(tag, out string myValue))
{
    // use myValue;
}
// use myValue, still in scope, null if not found

Add directives from directive in AngularJS

I wanted to add my solution since the accepted one didn't quite work for me.

I needed to add a directive but also keep mine on the element.

In this example I am adding a simple ng-style directive to the element. To prevent infinite compile loops and allowing me to keep my directive I added a check to see if what I added was present before recompiling the element.

angular.module('some.directive', [])
.directive('someDirective', ['$compile',function($compile){
    return {
        priority: 1001,
        controller: ['$scope', '$element', '$attrs', '$transclude' ,function($scope, $element, $attrs, $transclude) {

            // controller code here

        }],
        compile: function(element, attributes){
            var compile = false;

            //check to see if the target directive was already added
            if(!element.attr('ng-style')){
                //add the target directive
                element.attr('ng-style', "{'width':'200px'}");
                compile = true;
            }
            return {
                pre: function preLink(scope, iElement, iAttrs, controller) {  },
                post: function postLink(scope, iElement, iAttrs, controller) {
                    if(compile){
                        $compile(iElement)(scope);
                    }
                }
            };
        }
    };
}]);

How to get JSON Key and Value?

$.each(result, function(key, value) {
  console.log(key+ ':' + value);
});

Woocommerce get products

<?php  
    $args = array(
        'post_type'      => 'product',
        'posts_per_page' => 10,
        'product_cat'    => 'hoodies'
    );

    $loop = new WP_Query( $args );

    while ( $loop->have_posts() ) : $loop->the_post();
        global $product;
        echo '<br /><a href="'.get_permalink().'">' . woocommerce_get_product_thumbnail().' '.get_the_title().'</a>';
    endwhile;

    wp_reset_query();
?>

This will list all product thumbnails and names along with their links to product page. change the category name and posts_per_page as per your requirement.

Object of class stdClass could not be converted to string - laravel

This is easy all you need to do is something like this Grab your contents like this

  $result->get(filed1) = 'some modification';
  $result->get(filed2) = 'some modification2';

How do you select a particular option in a SELECT element in jQuery?

Answering my own question for documentation. I'm sure there are other ways to accomplish this, but this works and this code is tested.

<html>
<head>
<script language="Javascript" src="javascript/jquery-1.2.6.min.js"></script>
<script type="text/JavaScript">

$(function() {
    $(".update").bind("click",      // bind the click event to a div
        function() {
            var selectOption = $('.selDiv').children('.opts') ;
            var _this = $(this).next().children(".opts") ;

            $(selectOption).find("option[index='0']").attr("selected","selected");
//          $(selectOption).find("option[value='DEFAULT']").attr("selected","selected");
//          $(selectOption).find("option[text='Default']").attr("selected","selected");


//          $(_this).find("option[value='DEFAULT']").attr("selected","selected");
//          $(_this).find("option[text='Default']").attr("selected","selected");
//          $(_this).find("option[index='0']").attr("selected","selected");

    }); // END Bind
}); // End eventlistener

</script>
</head>
<body>
<div class="update" style="height:50px; color:blue; cursor:pointer;">Update</div>
<div class="selDiv">
        <select class="opts">
            <option selected value="DEFAULT">Default</option>
            <option value="SEL1">Selection 1</option>
            <option value="SEL2">Selection 2</option>
        </select>
    </div>
</body>
</html>

Map to String in Java

Use Object#toString().

String string = map.toString();

That's after all also what System.out.println(object) does under the hoods. The format for maps is described in AbstractMap#toString().

Returns a string representation of this map. The string representation consists of a list of key-value mappings in the order returned by the map's entrySet view's iterator, enclosed in braces ("{}"). Adjacent mappings are separated by the characters ", " (comma and space). Each key-value mapping is rendered as the key followed by an equals sign ("=") followed by the associated value. Keys and values are converted to strings as by String.valueOf(Object).

How do I load a file from resource folder?

Non spring project:

String filePath = Objects.requireNonNull(getClass().getClassLoader().getResource("any.json")).getPath();

Stream<String> lines = Files.lines(Paths.get(filePath));

Or

String filePath = Objects.requireNonNull(getClass().getClassLoader().getResource("any.json")).getPath();

InputStream in = new FileInputStream(filePath);

For spring projects, you can also use one line code to get any file under resources folder:

File file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "any.json");

String content = new String(Files.readAllBytes(file.toPath()));

Safari 3rd party cookie iframe trick no longer working?

I used modified (added signed_request param to the link) Whiteagle's trick and it worked ok for safari, but IE is constantly refreshing the page in that case. So my solution for safari and internet explorer is:

$fbapplink = 'https://apps.facebook.com/[appnamespace]/';
$isms = stripos($_SERVER['HTTP_USER_AGENT'], 'msie') !== false;

// safari fix
if(! $isms  && !isset($_SESSION['signed_request'])) {

    if (isset($_GET["start_session"])) {
        $_SESSION['signed_request'] = $_GET['signed_request'];
        die(header("Location:" . $fbapplink ));

    }
    if (!isset($_GET["sid"])) {
        die(header("Location:?sid=" . session_id() . '&signed_request='.$_REQUEST['signed_request']));
    }
    $sid = session_id();
    if (empty($sid) || $_GET["sid"] != $sid) {
    ?>
    <script>
        top.window.location="?start_session=true";
    </script>
    <?php
    exit;
    }
}

// IE fix
header('P3P: CP="CAO PSA OUR"');
header('P3P: CP="HONK"');


.. later in the code

$sr = $_REQUEST['signed_request'];
if($sr) {
        $_SESSION['signed_request'] = $sr;
} else {
        $sr = $_SESSION['signed_request'];
}

How to export a Vagrant virtual machine to transfer it

You have two ways to do this, I'll call it dirty way and clean way:

1. The dirty way

Create a box from your current virtual environment, using vagrant package command:

http://docs.vagrantup.com/v2/cli/package.html

Then copy the box to the other pc, add it using vagrant box add and run it using vagrant up as usual.

Keep in mind that files in your working directory (the one with the Vagrantfile) are shared when the virtual machine boots, so you need to copy it to the other pc as well.

2. The clean way

Theoretically it should never be necessary to do export/import with Vagrant. If you have the foresight to use provisioning for configuring the virtual environment (chef, puppet, ansible), and a version control system like git for your working directory, copying an environment would be at this point simple as running:

git clone <your_repo>
vagrant up

Ionic 2: Cordova is not available. Make sure to include cordova.js or run in a device/simulator (running in emulator)

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { EmailComposer } from '@ionic-native/email-composer';

@Component({
  selector: 'page-about',
  templateUrl: 'about.html'
})
export class AboutPage {
  sendObj = {
    to: '',
    cc: '',
    bcc: '',
    attachments:'',
    subject:'',
    body:''
  }

  constructor(public navCtrl: NavController,private emailComposer: EmailComposer) {}

  sendEmail(){
  let email = {
    to: this.sendObj.to,
    cc: this.sendObj.cc,
    bcc: this.sendObj.bcc,
    attachments: [this.sendObj.attachments],
    subject: this.sendObj.subject,
    body: this.sendObj.body,
    isHtml: true
  }; 
  this.emailComposer.open(email);
  }  
 }

starts here html about

<ion-header>
  <ion-navbar>
    <ion-title>
      Send Invoice
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <ion-item>
    <ion-label stacked>To</ion-label>
    <ion-input [(ngModel)]="sendObj.to"></ion-input>
  </ion-item>
  <ion-item>
    <ion-label stacked>CC</ion-label>
    <ion-input [(ngModel)]="sendObj.cc"></ion-input>
  </ion-item>
  <ion-item>
    <ion-label stacked>BCC</ion-label>
    <ion-input [(ngModel)]="sendObj.bcc"></ion-input>
  </ion-item>
  <ion-item>
    <ion-label stacked>Add pdf</ion-label>
    <ion-input [(ngModel)]="sendObj.attachments" type="file"></ion-input>
  </ion-item>
  <ion-item>
    <ion-label stacked>Subject</ion-label>
    <ion-input [(ngModel)]="sendObj.subject"></ion-input>
  </ion-item>
  <ion-item>
    <ion-label stacked>Text message</ion-label>
    <ion-input [(ngModel)]="sendObj.body"></ion-input>
  </ion-item>

  <button ion-button full (click)="sendEmail()">Send Email</button>

</ion-content>


other stuff here

import { NgModule, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';

import { AboutPage } from '../pages/about/about';
import { ContactPage } from '../pages/contact/contact';
import { HomePage } from '../pages/home/home';
import { TabsPage } from '../pages/tabs/tabs';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

import { File } from '@ionic-native/file';
import { FileOpener } from '@ionic-native/file-opener';
import { EmailComposer } from '@ionic-native/email-composer';

@NgModule({
  declarations: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    TabsPage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    TabsPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    EmailComposer,
    {provide: ErrorHandler, useClass: IonicErrorHandler},  
    File,
    FileOpener
  ]
})
export class AppModule {}

Simple working Example of json.net in VB.net

Your class JSON_result does not match your JSON string. Note how the object JSON_result is going to represent is wrapped in another property named "Venue".

So either create a class for that, e.g.:

Public Class Container
    Public Venue As JSON_result
End Class

Public Class JSON_result
    Public ID As Integer
    Public Name As String
    Public NameWithTown As String
    Public NameWithDestination As String
    Public ListingType As String
End Class

Dim obj = JsonConvert.DeserializeObject(Of Container)(...your_json...)

or change your JSON string to

{
    "ID": 3145,
    "Name": "Big Venue, Clapton",
    "NameWithTown": "Big Venue, Clapton, London",
    "NameWithDestination": "Big Venue, Clapton, London",
    "ListingType": "A",
    "Address": {
        "Address1": "Clapton Raod",
        "Address2": "",
        "Town": "Clapton",
        "County": "Greater London",
        "Postcode": "PO1 1ST",
        "Country": "United Kingdom",
        "Region": "Europe"
    },
    "ResponseStatus": {
        "ErrorCode": "200",
        "Message": "OK"
    }
}

or use e.g. a ContractResolver to parse the JSON string.

Android fade in and fade out with ImageView

I used used fadeIn animation to replace new image for old one

ObjectAnimator.ofFloat(imageView, View.ALPHA, 0.2f, 1.0f).setDuration(1000).start();

Things possible in IntelliJ that aren't possible in Eclipse?

CTRL-click works anywhere

CTRL-click that brings you to where clicked object is defined works everywhere - not only in Java classes and variables in Java code, but in Spring configuration (you can click on class name, or property, or bean name), in Hibernate (you can click on property name or class, or included resource), you can navigate within one click from Java class to where it is used as Spring or Hibernate bean; clicking on included JSP or JSTL tag also works, ctrl-click on JavaScript variable or function brings you to the place it is defined or shows a menu if there are more than one place, including other .js files and JS code in HTML or JSP files.

Autocomplete for many languagues

Hibernate

Autocomplete in HSQL expressions, in Hibernate configuration (including class, property and DB column names), in Spring configuration

<property name="propName" ref="<hit CTRL-SPACE>"

and it will show you list of those beans which you can inject into that property.

Java

Very smart autocomplete in Java code:

interface Person {
    String getName();
    String getAddress();
    int getAge();
}
//---
Person p;
String name = p.<CTRL-SHIFT-SPACE>

and it shows you ONLY getName(), getAddress() and toString() (only they are compatible by type) and getName() is first in the list because it has more relevant name. Latest version 8 which is still in EAP has even more smart autocomplete.

interface Country{
}
interface Address {
    String getStreetAddress();
    String getZipCode();
    Country getCountry();
}
interface Person {
    String getName();
    Address getAddress();
    int getAge();
}
//--- 
Person p;
Country c = p.<CTRL-SHIFT-SPACE>

and it will silently autocomplete it to

Country c = p.getAddress().getCountry();

Javascript

Smart autocomplete in JavaScript.

function Person(name,address) {
    this.getName = function() { return name };
    this.getAddress = function() { return address };
}

Person.prototype.hello = function() {
    return "I'm " + this.getName() + " from " + this.get<CTRL-SPACE>;
}

and it shows ONLY getName() and getAddress(), no matter how may get* methods you have in other JS objects in your project, and ctrl-click on this.getName() brings you to where this one is defined, even if there are some other getName() functions in your project.

HTML

Did I mention autocomplete and ctrl-clicking in paths to files, like <script src="", <img src="", etc?

Autocomplete in HTML tag attributes. Autocomplete in style attribute of HTML tags, both attribute names and values. Autocomplete in class attributes as well.
Type <div class="<CTRL-SPACE> and it will show you list of CSS classes defined in your project. Pick one, ctrl-click on it and you will be redirected to where it is defined.

Easy own language higlighting

Latest version has language injection, so you can declare that you custom JSTL tag usually contains JavaScript and it will highlight JavaScript inside it.

<ui:obfuscateJavaScript>function something(){...}</ui:obfuscateJavaScript>

Indexed search across all project.

You can use Find Usages of any Java class or method and it will find where it is used including not only Java classes but Hibernate, Spring, JSP and other places. Rename Method refactoring renames method not only in Java classes but anywhere including comments (it can not be sure if string in comments is really method name so it will ask). And it will find only your method even if there are methods of another class with same name. Good source control integration (does SVN support changelists? IDEA support them for every source control), ability to create a patch with your changes so you can send your changes to other team member without committing them.

Improved debugger

When I look at HashMap in debugger's watch window, I see logical view - keys and values, last time I did it in Eclipse it was showing entries with hash and next fields - I'm not really debugging HashMap, I just want to look at it contents.

Spring & Hibernate configuration validation

It validates Spring and Hibernate configuration right when you edit it, so I do not need to restart server to know that I misspelled class name, or added constructor parameter so my Spring cfg is invalid.

Last time I tried, I could not run Eclipse on Windows XP x64.

and it will suggest you person.name or person.address. Ctrl-click on person.name and it will navigate you to getName() method of Person class.

Type Pattern.compile(""); put \\ there, hit CTRL-SPACE and see helpful hint about what you can put into your regular expression. You can also use language injection here - define your own method that takes string parameter, declare in IntelliLang options dialog that your parameter is regular expression - and it will give you autocomplete there as well. Needless to say it highlights incorrect regular expressions.

Other features

There are few features which I'm not sure are present in Eclipse or not. But at least each member of our team who uses Eclipse, also uses some merging tool to merge local changes with changes from source control, usually WinMerge. I never need it - merging in IDEA is enough for me. By 3 clicks I can see list of file versions in source control, by 3 more clicks I can compare previous versions, or previous and current one and possibly merge.

It allows to to specify that I need all .jars inside WEB-INF\lib folder, without picking each file separately, so when someone commits new .jar into that folder it picks it up automatically.

Mentioned above is probably 10% of what it does. I do not use Maven, Flex, Swing, EJB and a lot of other stuff, so I can not tell how it helps with them. But it does.

How to directly move camera to current location in Google Maps Android API v2?

The above answer is not according to what Google Doc Referred for Location Tracking in Google api v2.

I just followed the official tutorial and ended up with this class that is fetching the current location and centring the map on it as soon as i get that.

you can extend this class to have LocationReciever to have periodic Location Update. I just executed this code on api level 7

http://developer.android.com/training/location/retrieve-current.html

Here it goes.

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;


public class MainActivity extends FragmentActivity implements 
    GooglePlayServicesClient.ConnectionCallbacks, 
    GooglePlayServicesClient.OnConnectionFailedListener{

private SupportMapFragment mapFragment;
private GoogleMap map;
private LocationClient mLocationClient;
/*
 * Define a request code to send to Google Play services
 * This code is returned in Activity.onActivityResult
 */
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;

// Define a DialogFragment that displays the error dialog
public static class ErrorDialogFragment extends DialogFragment {

    // Global field to contain the error dialog
    private Dialog mDialog;

    // Default constructor. Sets the dialog field to null
    public ErrorDialogFragment() {
        super();
        mDialog = null;
    }

    // Set the dialog to display
    public void setDialog(Dialog dialog) {
        mDialog = dialog;
    }

    // Return a Dialog to the DialogFragment.
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return mDialog;
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);

    mLocationClient = new LocationClient(this, this, this);

    mapFragment = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map));
    map = mapFragment.getMap();

    map.setMyLocationEnabled(true);

}

/*
 * Called when the Activity becomes visible.
 */
@Override
protected void onStart() {
    super.onStart();
    // Connect the client.
    if(isGooglePlayServicesAvailable()){
        mLocationClient.connect();
    }

}

/*
 * Called when the Activity is no longer visible.
 */
@Override
protected void onStop() {
    // Disconnecting the client invalidates it.
    mLocationClient.disconnect();
    super.onStop();
}

/*
 * Handle results returned to the FragmentActivity
 * by Google Play services
 */
@Override
protected void onActivityResult(
                int requestCode, int resultCode, Intent data) {
    // Decide what to do based on the original request code
    switch (requestCode) {

        case CONNECTION_FAILURE_RESOLUTION_REQUEST:
            /*
             * If the result code is Activity.RESULT_OK, try
             * to connect again
             */
            switch (resultCode) {
                case Activity.RESULT_OK:
                    mLocationClient.connect();
                    break;
            }

    }
}

private boolean isGooglePlayServicesAvailable() {
    // Check that Google Play services is available
    int resultCode =  GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    // If Google Play services is available
    if (ConnectionResult.SUCCESS == resultCode) {
        // In debug mode, log the status
        Log.d("Location Updates", "Google Play services is available.");
        return true;
    } else {
        // Get the error dialog from Google Play services
        Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog( resultCode,
                                                                                                              this,
                                                                                                              CONNECTION_FAILURE_RESOLUTION_REQUEST);

        // If Google Play services can provide an error dialog
        if (errorDialog != null) {
            // Create a new DialogFragment for the error dialog
            ErrorDialogFragment errorFragment = new ErrorDialogFragment();
            errorFragment.setDialog(errorDialog);
            errorFragment.show(getSupportFragmentManager(), "Location Updates");
        }

        return false;
    }
}

/*
 * Called by Location Services when the request to connect the
 * client finishes successfully. At this point, you can
 * request the current location or start periodic updates
 */
@Override
public void onConnected(Bundle dataBundle) {
    // Display the connection status
    Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
    Location location = mLocationClient.getLastLocation();
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 17);
    map.animateCamera(cameraUpdate);
}

/*
 * Called by Location Services if the connection to the
 * location client drops because of an error.
 */
@Override
public void onDisconnected() {
    // Display the connection status
    Toast.makeText(this, "Disconnected. Please re-connect.",
            Toast.LENGTH_SHORT).show();
}

/*
 * Called by Location Services if the attempt to
 * Location Services fails.
 */
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    /*
     * Google Play services can resolve some errors it detects.
     * If the error has a resolution, try sending an Intent to
     * start a Google Play services activity that can resolve
     * error.
     */
    if (connectionResult.hasResolution()) {
        try {
            // Start an Activity that tries to resolve the error
            connectionResult.startResolutionForResult(
                    this,
                    CONNECTION_FAILURE_RESOLUTION_REQUEST);
            /*
            * Thrown if Google Play services canceled the original
            * PendingIntent
            */
        } catch (IntentSender.SendIntentException e) {
            // Log the error
            e.printStackTrace();
        }
    } else {
       Toast.makeText(getApplicationContext(), "Sorry. Location services not available to you", Toast.LENGTH_LONG).show();
    }
}

}

How can I specify a local gem in my Gemfile?

In order to use local gem repository in a Rails project, follow the steps below:

  1. Check if your gem folder is a git repository (the command is executed in the gem folder)

    git rev-parse --is-inside-work-tree
    
  2. Getting repository path (the command is executed in the gem folder)

    git rev-parse --show-toplevel
    
  3. Setting up a local override for the rails application

    bundle config local.GEM_NAME /path/to/local/git/repository
    

    where GEM_NAME is the name of your gem and /path/to/local/git/repository is the output of the command in point 2

  4. In your application Gemfile add the following line:

    gem 'GEM_NAME', :github => 'GEM_NAME/GEM_NAME', :branch => 'master'
    
  5. Running bundle install should give something like this:

    Using GEM_NAME (0.0.1) from git://github.com/GEM_NAME/GEM_NAME.git (at /path/to/local/git/repository) 
    

    where GEM_NAME is the name of your gem and /path/to/local/git/repository from point 2

  6. Finally, run bundle list, not gem list and you should see something like this:

    GEM_NAME (0.0.1 5a68b88)
    

    where GEM_NAME is the name of your gem


A few important cases I am observing using:

Rails 4.0.2  
ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-linux] 
Ubuntu 13.10  
RubyMine 6.0.3
  • It seems RubyMine is not showing local gems as an external library. More information about the bug can be found here and here
  • When I am changing something in the local gem, in order to be loaded in the rails application I should stop/start the rails server
  • If I am changing the version of the gem, stopping/starting the Rails server gives me an error. In order to fix it, I am specifying the gem version in the rails application Gemfile like this:

    gem 'GEM_NAME', '0.0.2', :github => 'GEM_NAME/GEM_NAME', :branch => 'master'
    

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

You should use setTimestamp instead, if you hardcode it:

$start_date = new DateTime();
$start_date->setTimestamp(1372622987);

in your case

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

ASP.Net 2012 Unobtrusive Validation with jQuery

It seems like there is a lot of incorrect information about the ValidationSettings:UnobtrusiveValidationMode value. To Disable it you need to do the following.

<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />

The word None, not WebForms should be used to disable this feature.

Razor view engine - How can I add Partial Views

You partial looks much like an editor template so you could include it as such (assuming of course that your partial is placed in the ~/views/controllername/EditorTemplates subfolder):

@Html.EditorFor(model => model.SomePropertyOfTypeLocaleBaseModel)

Or if this is not the case simply:

@Html.Partial("nameOfPartial", Model)

Get current category ID of the active page

If it is a category page,you can get id of current category by:

$category = get_category( get_query_var( 'cat' ) );
$cat_id = $category->cat_ID;

If you want to get category id of any particular category on any page, try using :

$category_id = get_cat_ID('Category Name');

How to remove responsive features in Twitter Bootstrap 3?

Look at www.goo.gl/2SIOJj it is a work in progress but it may help you.

I use cookie to define if i want desktop or responsive version. In the footer of the page you can find two spans and in general.js is the script to handle the clicks.

        <div class="col-xs-6" style="text-align:center;"><span class="make_desktop">Desktop</span></div>
        <div class="col-xs-6" style="text-align:center;"><span class="make_responsive">Mobile</span></div>

function setMobDeskCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays === null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value + "; path=/";
    window.location.reload();
}

$(function() {
    $(".make_desktop").click(function() {
        setMobDeskCookie('deskmob', 1, 3650);
    });
    $(".make_responsive").click(function() {
        setMobDeskCookie('deskmob', 0, 3650);
    });
});`enter code here`

i ended up splitting all my custom css into two files i don't use bootstrap navigation but my own so that is majority of my custom styles, so it will not resolve your entire problem but it works for me

and i also created non-responsive.css that forces the grid to maintain the large screen version

in case u select mobile i would load / echo

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">  
<!-- Bootstrap core CSS and JS -->
        <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
        <link href="/themes/responsive_lime/bootstrap-3_1_1/css/bootstrap.css" rel="stylesheet">
        <script src="/themes/responsive_lime/bootstrap-3_1_1/js/bootstrap.min.js"></script>

and load these stylesheets
<link rel="stylesheet" type="text/css" media="screen,print" href="/themes/responsive_lime/css/style.css?modified=14-06-2014-12-27-40" />
<link rel="stylesheet" type="text/css" media="screen,print" href="/themes/responsive_lime/css/style-responsive.css?modified=1402758346" />

in case you select desktop i would load /echo

<meta name="viewport" content="width=1024">    


        <!-- Bootstrap core CSS and JS -->
        <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
        <link href="/themes/responsive_lime/bootstrap-3_1_1/css/bootstrap.css" rel="stylesheet">
        <script src="/themes/responsive_lime/bootstrap-3_1_1/js/bootstrap.min.js"></script>

        <!-- Main CSS -->
        <link rel="stylesheet" type="text/css" media="screen,print" href="/themes/responsive_lime/css/style.css?modified=14-06-2014-12-27-40" />
<link rel="stylesheet" type="text/css" media="screen,print" href="/themes/responsive_lime/css/non-responsive.css?modified=1402758635" />

the non-responsive.css is the one that has overrides for bootstrap my concern is layout so there is not much in there, given that i handle the navigation in my own way so css for it and the other bits is in my other css files

please note that my setup does behave as desktop even on desktop browsers unlike some other solutions i have seen that will only ignore the viewport that seems to have wotked only on mobile devices for me

java.lang.NoClassDefFoundError: org/json/JSONObject

Please add the following dependency http://mvnrepository.com/artifact/org.json/json/20080701

<dependency>
   <groupId>org.json</groupId>
   <artifactId>json</artifactId>
   <version>20080701</version>
</dependency>

Set width of dropdown element in HTML select dropdown options

On the server-side:

  1. Define a max length of the string
  2. Clip the string
  3. (optional) append horizontal ellipsis

Alternative solution: the select element is in your case (only guessing) a single-choice form control and you could use a group of radio buttons instead. These you could then style with better control. If you have a select[@multiple] you could do the same with a group of checkboxes instead as they can both be seen as a multiple-choice form control.

iOS8 Beta Ad-Hoc App Download (itms-services)

Specify a 'display-image' and 'full-size-image' as described here: http://www.informit.com/articles/article.aspx?p=1829415&seqNum=16

iOS8 requires these images

Write to file, but overwrite it if it exists

If your environment doesn't allow overwriting with >, use pipe | and tee instead as follows:

echo "text" | tee 'Users/Name/Desktop/TheAccount.txt'

Note this will also print to the stdout. In case this is unwanted, you can redirect the output to /dev/null as follows:

echo "text" | tee 'Users/Name/Desktop/TheAccount.txt' > /dev/null

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.

How to normalize a histogram in MATLAB?

[f,x]=hist(data)

The area for each individual bar is height*width. Since MATLAB will choose equidistant points for the bars, so the width is:

delta_x = x(2) - x(1)

Now if we sum up all the individual bars the total area will come out as

A=sum(f)*delta_x

So the correctly scaled plot is obtained by

bar(x, f/sum(f)/(x(2)-x(1)))

What is the right way to populate a DropDownList from a database?

I hope I am not overstating the obvious, but why not do it directly in the ASP side? Unless you are dynamically altering the SQL based on certain conditions in your program, you should avoid codebehind as much as possible.

You could do the above all in ASP directly without code using the SqlDataSource control and a property in your dropdownlist.

<asp:GridView ID="gvSubjects" runat="server" DataKeyNames="SubjectID" OnRowDataBound="GridView_RowDataBound" OnDataBound="GridView_DataBound">
    <Columns>
        <asp:TemplateField HeaderText="Subjects">
            <ItemTemplate>
                <asp:DropDownList ID="ddlSubjects" runat="server" DataSourceID="sdsSubjects" DataTextField="SubjectName" DataValueField="SubjectID">
                </asp:DropDownList>
                <asp:SqlDataSource ID="sdsSubjects" runat="server"
                    SelectCommand="SELECT SubjectID,SubjectName FROM Students.dbo.Subjects"></asp:SqlDataSource>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

How can I make a list of lists in R?

As other answers pointed out in a more complicated way already, you did already create a list of lists! It's just the odd output of R that confuses (everybody?). Try this:

> str(list_all)
List of 2
 $ :List of 2
  ..$ : num 1
  ..$ : num 2
 $ :List of 2
  ..$ : chr "a"
  ..$ : chr "b"

And the most simple construction would be this:

> str(list(list(1, 2), list("a", "b")))
List of 2
 $ :List of 2
  ..$ : num 1
  ..$ : num 2
 $ :List of 2
  ..$ : chr "a"
  ..$ : chr "b"

LINK : fatal error LNK1104: cannot open file 'D:\...\MyProj.exe'

I've concluded this is some kind of Visual Studio bug. Perhaps C Johnson is right - perhaps the build process keeps the file locked.

I do have a workaround which works - each time this happens - I change the Target Name of the executable under the Project's properties (right click the project, then Properties\Configuration Properties\General\Target Name).

In this fashion VS creates a new executable and the problem is worked around. Every few times I do this I return to the original name, thus cycling through ~3 names.

If someone will find the reason for this and a solution, please do answer and I may move the answer to yours, as mine is a workaround.

How to access single elements in a table in R

That is so basic that I am wondering what book you are using to study? Try

data[1, "V1"]  # row first, quoted column name second, and case does matter

Further note: Terminology in discussing R can be crucial and sometimes tricky. Using the term "table" to refer to that structure leaves open the possibility that it was either a 'table'-classed, or a 'matrix'-classed, or a 'data.frame'-classed object. The answer above would succeed with any of them, while @BenBolker's suggestion below would only succeed with a 'data.frame'-classed object.

I am unrepentant in my phrasing despite the recent downvote. There is a ton of free introductory material for beginners in R: https://cran.r-project.org/other-docs.html

Is it safe to clean docker/overlay2/

I recently had a similar issue, overlay2 grew bigger and bigger, But I couldn’t figure out what consumed the bulk of the space.

df showed me that overlay2 was about 24GB in size.

With du I tried to figure out what occupied the space… and failed.

The difference came from the fact that deleted files (mostly log files in my case) where still being used by a process (Docker). Thus the file doesn’t show up with du but the space it occupies will show with df.

A reboot of the host machine helped. Restarting the docker container would probably have helped already… This article on linuxquestions.org helped me to figure that out.

Multiple try codes in one block

You could try a for loop


for func,args,kwargs in zip([a,b,c,d], 
                            [args_a,args_b,args_c,args_d],
                            [kw_a,kw_b,kw_c,kw_d]):
    try:
       func(*args, **kwargs)
       break
    except:
       pass

This way you can loop as many functions as you want without making the code look ugly

Return 0 if field is null in MySQL

Yes IFNULL function will be working to achieve your desired result.

SELECT uo.order_id, uo.order_total, uo.order_status,
        (SELECT IFNULL(SUM(uop.price * uop.qty),0) 
         FROM uc_order_products uop 
         WHERE uo.order_id = uop.order_id
        ) AS products_subtotal,
        (SELECT IFNULL(SUM(upr.amount),0) 
         FROM uc_payment_receipts upr 
         WHERE uo.order_id = upr.order_id
        ) AS payment_received,
        (SELECT IFNULL(SUM(uoli.amount),0) 
         FROM uc_order_line_items uoli 
         WHERE uo.order_id = uoli.order_id
        ) AS line_item_subtotal
        FROM uc_orders uo
        WHERE uo.order_status NOT IN ("future", "canceled")
        AND uo.uid = 4172;

What is the difference between HTTP status code 200 (cache) vs status code 304?

HTTP 304 is "not modified". Your web server is basically telling the browser "this file hasn't changed since the last time you requested it." Whereas an HTTP 200 is telling the browser "here is a successful response" - which should be returned when it's either the first time your browser is accessing the file or the first time a modified copy is being accessed.

For more info on status codes check out http://en.wikipedia.org/wiki/List_of_HTTP_status_codes.

Python: convert string from UTF-8 to Latin-1

If the previous answers do not solve your problem, check the source of the data that won't print/convert properly.

In my case, I was using json.load on data incorrectly read from file by not using the encoding="utf-8". Trying to de-/encode the resulting string to latin-1 just does not help...

How much memory can a 32 bit process access on a 64 bit operating system?

Nobody seems to touch upon the fact that if you have many different 32-bit applications, the wow64 subsystem can map them anywhere in memory above 4G, so on a 64-bit windows with sufficient memory, you can run many more 32-bit applications than on a native 32-bit system.

use video as background for div

I believe this is what you're looking for. It automatically scaled the video to fit the container.

DEMO: http://jsfiddle.net/t8qhgxuy/

Video need to have height and width always set to 100% of the parent.

HTML:

<div class="one"> CONTENT OVER VIDEO
    <video class="video-background" no-controls autoplay src="https://dl.dropboxusercontent.com/u/8974822/cloud-troopers-video.mp4" poster="http://thumb.multicastmedia.com/thumbs/aid/w/h/t1351705158/1571585.jpg"></video>
</div>

<div class="two">
    <video class="video-background" no-controls autoplay src="https://dl.dropboxusercontent.com/u/8974822/cloud-troopers-video.mp4" poster="http://thumb.multicastmedia.com/thumbs/aid/w/h/t1351705158/1571585.jpg"></video> CONTENT OVER VIDEO
</div>

CSS:

body {
    overflow: scroll;
    padding:  60px 20px;
}

.one {
    width: 90%;
    height: 30vw;
    overflow: hidden;
    border: 15px solid red;
    margin-bottom: 40px;
    position: relative;
}

.two{
    width: 30%;
    height: 300px;
    overflow: hidden;
    border: 15px solid blue;
    position: relative;
}

.video-background { /* class name used in javascript too */
    width: 100%; /* width needs to be set to 100% */
    height: 100%; /* height needs to be set to 100% */
    position: absolute;
    left: 0;
    top: 0;
    z-index: -1;
}

JS:

function scaleToFill() {
    $('video.video-background').each(function(index, videoTag) {
       var $video = $(videoTag),
           videoRatio = videoTag.videoWidth / videoTag.videoHeight,
           tagRatio = $video.width() / $video.height(),
           val;

       if (videoRatio < tagRatio) {
           val = tagRatio / videoRatio * 1.02; <!-- size increased by 2% because value is not fine enough and sometimes leaves a couple of white pixels at the edges -->
       } else if (tagRatio < videoRatio) {
           val = videoRatio / tagRatio * 1.02;
       }

       $video.css('transform','scale(' + val  + ',' + val + ')');

    });    
}

$(function () {
    scaleToFill();

    $('.video-background').on('loadeddata', scaleToFill);

    $(window).resize(function() {
        scaleToFill();
    });
});

Overwriting txt file in java

The easiest way to overwrite a text file is to use a public static field.

this will overwrite the file every time because your only using false the first time through.`

public static boolean appendFile;

Use it to allow only one time through the write sequence for the append field of the write code to be false.

// use your field before processing the write code

appendFile = False;

File fnew=new File("../playlist/"+existingPlaylist.getText()+".txt");
String source = textArea.getText();
System.out.println(source);
FileWriter f2;

try {
     //change this line to read this

    // f2 = new FileWriter(fnew,false);

    // to read this
    f2 = new FileWriter(fnew,appendFile); // important part
    f2.write(source);

    // change field back to true so the rest of the new data will
    // append to the new file.

    appendFile = true;

    f2.close();
 } catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
 }           

How to find sitemap.xml path on websites?

Use Google Search Operators to find it for you

search google with the below code..

inurl:domain.com filetype:xml click on this to view sitemap search example

change domain.com to the domain you want to find the sitemap. this should list all the xml files listed for the given domain.. including all sitemaps :)

How do I center this form in css?

_x000D_
_x000D_
body {_x000D_
    text-align: center;_x000D_
}_x000D_
form {_x000D_
    width:90%;_x000D_
    background-color: #c0d7f8;_x000D_
}
_x000D_
<body>_x000D_
  <form>_x000D_
    <input type="text" value="abc">_x000D_
  </form>_x000D_
</body>
_x000D_
_x000D_
_x000D_

mongod command not recognized when trying to connect to a mongodb server

You need to add Mongo's bin folder to the "Path" Environment Variable

Here's how on Windows 10:

  1. Find Mongo's bin folder.

If you're not sure where it is, it's probably in C:\Program Files\MongoDB\Server\3.4\ 3.4 was the latest stable version at the time, this will be different for you probably.

It should look like this:

This is what Mongo's bin folder looked like for version 3.4, the important thing is it's whatever folder contains mongod.exe. Notice this is the path to mongo.exe and mongod.exe. Adding this folder to the Path variable is telling Windows to search in this folder for executables matching your command when you run something in cmd. The search starts with the current working dir, and if it doesn't find your exe, goes on to search all the paths in Path till it finds it or it doesn't and it gives you that error you saw.

  1. Copy the path to the bin folder. It should be C:\Program Files\MongoDB\Server\3.4\bin\ (Or whatever version you're using)

  2. Press win, type env, Windows will suggest "Edit the System Environment Variables", click that.

How to find the system environment variables.

  1. On the Advanced tab, click "Environment Variables"

The Advanced tab in System Properties contains the Environment Variables.

  1. Highlight the "Path" variable, click "Edit":

You want to edit the Path variable to add Mongo's bin folder to it.

  1. This will bring up the "Edit environment variable" window, click "New"

Add a new folder to the Path variable

  1. This will start a new line in the list of folders:

A new line in the Path variable.

  1. Paste your path to the bin folder. Make sure it ends with a \ like so:

Paste the location of the bin folder.

  1. Press "OK", "OK", "OK"

Now you should be able to run mongod and mongo from anywhere in a command window.

How can I get a specific parameter from location.search?

The easiest way is to have

if (document.location.search.indexOf('yourtext=') >= 0) {
    // your code
} else {
    // what happens?
}

indexOf()

The indexOf(text) function returns

  • A WHOLE NUMBER BELOW 0 when the text passed in the function is not in whatever variable or string you are looking for - in this case document.location.search.
  • A WHOLE NUMBER EQUAL TO 0 OR HIGHER when the text passed in the function is in whatever variable or string you are looking for - in this case document.location.search.

I hope this was useful, @gumbo

How to load all modules in a folder?

This is the best way i've found so far:

from os.path import dirname, join, isdir, abspath, basename
from glob import glob
pwd = dirname(__file__)
for x in glob(join(pwd, '*.py')):
    if not x.startswith('__'):
        __import__(basename(x)[:-3], globals(), locals())

Call child method from parent

https://facebook.github.io/react/tips/expose-component-functions.html for more answers ref here Call methods on React children components

By looking into the refs of the "reason" component, you're breaking encapsulation and making it impossible to refactor that component without carefully examining all the places it's used. Because of this, we strongly recommend treating refs as private to a component, much like state.

In general, data should be passed down the tree via props. There are a few exceptions to this (such as calling .focus() or triggering a one-time animation that doesn't really "change" the state) but any time you're exposing a method called "set", props are usually a better choice. Try to make it so that the inner input component worries about its size and appearance so that none of its ancestors do.

Difference between PACKETS and FRAMES

A packet is a general term for a formatted unit of data carried by a network. It is not necessarily connected to a specific OSI model layer.

For example, in the Ethernet protocol on the physical layer (layer 1), the unit of data is called an "Ethernet packet", which has an Ethernet frame (layer 2) as its payload. But the unit of data of the Network layer (layer 3) is also called a "packet".

A frame is also a unit of data transmission. In computer networking the term is only used in the context of the Data link layer (layer 2).

Another semantical difference between packet and frame is that a frame envelops your payload with a header and a trailer, just like a painting in a frame, while a packet usually only has a header.

But in the end they mean roughly the same thing and the distinction is used to avoid confusion and repetition when talking about the different layers.

How do I replace text in a selection?

This frustrated the heck out of me, and none of the above answers really got me what I wanted. I finally found the answer I was looking for, on a mac if you do ? + option + F it will bring up a Find-Replace bar at the bottom of your editor which is local to the file you have open.

There is an icon option which when hovered over says "In Selection" that you can select to find and replace within a selection. I've pointed to the correct icon in the screenshot below.

enter image description here

Hit replace all, and voila, all instances of '0' will be replaced with '255'.

Note: this feature is ONLY available when you use ? + option + F.

It does NOT appear when you use ? + shift + F.

Note: this will replace all instances of '0' with '255'. If you wanted to replace 0 (without the quotes) with 255, then just put 0 (without quotes) and 255 in the Find What: and Replace With: fields respectively.

Note:

option key is also labeled as the alt key.

? key is also labeled as the command key.

How to change the style of a DatePicker in android?

Calendar calendar = Calendar.getInstance();

DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), R.style.DatePickerDialogTheme, new DatePickerDialog.OnDateSetListener() {
  public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
    Calendar newDate = Calendar.getInstance();
    newDate.set(year, monthOfYear, dayOfMonth);

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
    String date = simpleDateFormat.format(newDate.getTime());
  }
}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));

datePickerDialog.show();

And use this style:

<style name="DatePickerDialogTheme" parent="Theme.AppCompat.Light.Dialog">
  <item name="colorAccent">@color/colorPrimary</item>
</style>

Dynamically generating a QR code with PHP

I have been using google qrcode api for sometime, but I didn't quite like this because it requires me to be on the Internet to access the generated image.

I did a little comand-line research and found out that linux has a command line tool qrencode for generating qr-codes.

I wrote this little script. And the good part is that the generated image is less than 1KB in size. Well the supplied data is simply a url.

$url = ($_SERVER['HTTPS'] ? "https://" : "http://").$_SERVER['HTTP_HOST'].'/profile.php?id='.$_GET['pid'];
$img = shell_exec('qrencode --output=- -m=1 '.escapeshellarg($url));

$imgData = "data:image/png;base64,".base64_encode($img);

Then in the html I load the image:

<img class="emrQRCode" src="<?=$imgData ?>" />

You just need to have installed it. [most imaging apps on linux would have installed it under the hood without you realizing.

Java Class.cast() vs. cast operator

Class.cast() is rarely ever used in Java code. If it is used then usually with types that are only known at runtime (i.e. via their respective Class objects and by some type parameter). It is only really useful in code that uses generics (that's also the reason it wasn't introduced earlier).

It is not similar to reinterpret_cast, because it will not allow you to break the type system at runtime any more than a normal cast does (i.e. you can break generic type parameters, but can't break "real" types).

The evils of the C-style cast operator generally don't apply to Java. The Java code that looks like a C-style cast is most similar to a dynamic_cast<>() with a reference type in Java (remember: Java has runtime type information).

Generally comparing the C++ casting operators with Java casting is pretty hard since in Java you can only ever cast reference and no conversion ever happens to objects (only primitive values can be converted using this syntax).

How do I automatically scroll to the bottom of a multiline text box?

You can use the following code snippet:

myTextBox.SelectionStart = myTextBox.Text.Length;
myTextBox.ScrollToCaret();

which will automatically scroll to the end.

Can a JSON value contain a multiline string

Not pretty good solution, but you can try the hjson tool. It allows you to write text multi-lined in editor and then converts it to the proper valid JSON format.

Note: it adds '\n' characters for the new lines, but you can simply delete them in any text editor with the "Replace all.." function.

SSL certificate is not trusted - on mobile only

The most likely reason for the error is that the certificate authority that issued your SSL certificate is trusted on your desktop, but not on your mobile.

If you purchased the certificate from a common certification authority, it shouldn't be an issue - but if it is a less common one it is possible that your phone doesn't have it. You may need to accept it as a trusted publisher (although this is not ideal if you are pushing the site to the public as they won't be willing to do this.)

You might find looking at a list of Trusted CAs for Android helps to see if yours is there or not.

How to send a correct authorization header for basic authentication

Per https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding and http://en.wikipedia.org/wiki/Basic_access_authentication , here is how to do Basic auth with a header instead of putting the username and password in the URL. Note that this still doesn't hide the username or password from anyone with access to the network or this JS code (e.g. a user executing it in a browser):

$.ajax({
  type: 'POST',
  url: http://theappurl.com/api/v1/method/,
  data: {},
  crossDomain: true,
  beforeSend: function(xhr) {
    xhr.setRequestHeader('Authorization', 'Basic ' + btoa(unescape(encodeURIComponent(YOUR_USERNAME + ':' + YOUR_PASSWORD))))
  }
});

Is there a 'foreach' function in Python 3?

map can be used for the situation mentioned in the question.

E.g.

map(len, ['abcd','abc', 'a']) # 4 3 1

For functions that take multiple arguments, more arguments can be given to map:

map(pow, [2, 3], [4,2]) # 16 9

It returns a list in python 2.x and an iterator in python 3

In case your function takes multiple arguments and the arguments are already in the form of tuples (or any iterable since python 2.6) you can use itertools.starmap. (which has a very similar syntax to what you were looking for). It returns an iterator.

E.g.

for num in starmap(pow, [(2,3), (3,2)]):
    print(num)

gives us 8 and 9

exclude @Component from @ComponentScan

I had an issue when using @Configuration, @EnableAutoConfiguration and @ComponentScan while trying to exclude specific configuration classes, the thing is it didn't work!

Eventually I solved the problem by using @SpringBootApplication, which according to Spring documentation does the same functionality as the three above in one annotation.

Another Tip is to try first without refining your package scan (without the basePackages filter).

@SpringBootApplication(exclude= {Foo.class})
public class MySpringConfiguration {}

unable to set private key file: './cert.pem' type PEM

After reading cURL documentation on the options you used, it looks like the private key of certificate is not in the same file. If it is in different file, you need to mention it using --key file and supply passphrase.

So, please make sure that either cert.pem has private key (along with the certificate) or supply it using --key option.

Also, this documentation mentions that Note that this option assumes a "certificate" file that is the private key and the private certificate concatenated!

How they are concatenated? It is quite easy. Put them one after another in the same file.

You can get more help on this here.

I believe this might help you.

Examples of Algorithms which has O(1), O(n log n) and O(log n) complexities

You can add following algorithms to your list:

O(1) - Determining if a number is even or odd; Working with HashMap

O(logN) - computing x^N,

O(N Log N) - Longest increasing subsequence

How to make rectangular image appear circular with CSS

This one works well if you know height and width:

img {
  object-fit: cover;
  border-radius: '50%';
  width: 100px;
  height: 100px;
}

via https://medium.com/@chrisnager/center-and-crop-images-with-a-single-line-of-css-ad140d5b4a87

How do you add PostgreSQL Driver as a dependency in Maven?

Depending on your PostgreSQL version you would need to add the postgresql driver to your pom.xml file.

For PostgreSQL 9.1 this would be:

<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <name>Your project name.</name>
    <dependencies>
        <dependency>
            <groupId>postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.1-901-1.jdbc4</version>
        </dependency>
    </dependencies>
</project>

You can get the code for the dependency (as well as any other dependency) from maven's central repository

If you are using postgresql 9.2+:

<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <name>Your project name.</name>
    <dependencies>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.2.1</version>
        </dependency>
    </dependencies>
</project>

You can check the latest versions and dependency snippets from:

moment.js get current time in milliseconds?

var timeArr = moment().format('x');

returns the Unix Millisecond Timestamp as per the format() documentation.

how to set the background color of the whole page in css

The problem is that the body of the page isn't actually visible. The DIVs under have width of 100% and have background colors themselves that override the body CSS.

To Fix the no-man's land, this might work. It's not elegant, but works.

#doc3 {
    margin: auto 10px;
    width: auto;
    height: 2000px;
    background-color: yellow;
}

Convert Mongoose docs to json

You can use res.json() to jsonify any object. lean() will remove all the empty fields in the mongoose query.

UserModel.find().lean().exec(function (err, users) { return res.json(users); }

How can you use optional parameters in C#?

I agree with stephenbayer. But since it is a webservice, it is easier for end-user to use just one form of the webmethod, than using multiple versions of the same method. I think in this situation Nullable Types are perfect for optional parameters.

public void Foo(int a, int b, int? c)
{
  if(c.HasValue)
  {
    // do something with a,b and c
  }
  else
  {
    // do something with a and b only
  }  
}

When should we use mutex and when should we use semaphore

I think the question should be the difference between mutex and binary semaphore.

Mutex = It is a ownership lock mechanism, only the thread who acquire the lock can release the lock.

binary Semaphore = It is more of a signal mechanism, any other higher priority thread if want can signal and take the lock.

Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

The Valid Architectures build setting has been removed in Xcode 12. If you had values in this build setting, they're causing a problem and need to be removed.

I was able to "clear out" the VALID_ARCHS build setting by adding it back in as a User-Defined build setting (with no values), running the project (which failed), and then deleting the VALID_ARCHS build setting. After that, I was able to run on the simulator.

My Architectures build setting is Standard Architectures.

You can add a User-Defined Setting from the plus button in Build Settings:

User-Defined Setting

Basic Authentication Using JavaScript

After Spending quite a bit of time looking into this, i came up with the solution for this; In this solution i am not using the Basic authentication but instead went with the oAuth authentication protocol. But to use Basic authentication you should be able to specify this in the "setHeaderRequest" with minimal changes to the rest of the code example. I hope this will be able to help someone else in the future:

var token_ // variable will store the token
var userName = "clientID"; // app clientID
var passWord = "secretKey"; // app clientSecret
var caspioTokenUrl = "https://xxx123.caspio.com/oauth/token"; // Your application token endpoint  
var request = new XMLHttpRequest(); 

function getToken(url, clientID, clientSecret) {
    var key;           
    request.open("POST", url, true); 
    request.setRequestHeader("Content-type", "application/json");
    request.send("grant_type=client_credentials&client_id="+clientID+"&"+"client_secret="+clientSecret); // specify the credentials to receive the token on request
    request.onreadystatechange = function () {
        if (request.readyState == request.DONE) {
            var response = request.responseText;
            var obj = JSON.parse(response); 
            key = obj.access_token; //store the value of the accesstoken
            token_ = key; // store token in your global variable "token_" or you could simply return the value of the access token from the function
        }
    }
}
// Get the token
getToken(caspioTokenUrl, userName, passWord);

If you are using the Caspio REST API on some request it may be imperative that you to encode the paramaters for certain request to your endpoint; see the Caspio documentation on this issue;

NOTE: encodedParams is NOT used in this example but was used in my solution.

Now that you have the token stored from the token endpoint you should be able to successfully authenticate for subsequent request from the caspio resource endpoint for your application

function CallWebAPI() {
    var request_ = new XMLHttpRequest();        
    var encodedParams = encodeURIComponent(params);
    request_.open("GET", "https://xxx123.caspio.com/rest/v1/tables/", true);
    request_.setRequestHeader("Authorization", "Bearer "+ token_);
    request_.send();
    request_.onreadystatechange = function () {
        if (request_.readyState == 4 && request_.status == 200) {
            var response = request_.responseText;
            var obj = JSON.parse(response); 
            // handle data as needed... 

        }
    }
} 

This solution does only considers how to successfully make the authenticated request using the Caspio API in pure javascript. There are still many flaws i am sure...

SSL Error: CERT_UNTRUSTED while using npm command

If you're behind a corporate proxy, try this setting for npm with your company's proxy:

npm --https-proxy=http://proxy.company.com install express -g

Checking if a double (or float) is NaN in C++

There is also a header-only library present in Boost that have neat tools to deal with floating point datatypes

#include <boost/math/special_functions/fpclassify.hpp>

You get the following functions:

template <class T> bool isfinite(T z);
template <class T> bool isinf(T t);
template <class T> bool isnan(T t);
template <class T> bool isnormal(T t);

If you have time then have a look at whole Math toolkit from Boost, it has many useful tools and is growing quickly.

Also when dealing with floating and non-floating points it might be a good idea to look at the Numeric Conversions.

How to use a wildcard in the classpath to add multiple jars?

This works on Windows:

java -cp "lib/*" %MAINCLASS%

where %MAINCLASS% of course is the class containing your main method.

Alternatively:

java -cp "lib/*" -jar %MAINJAR%

where %MAINJAR% is the jar file to launch via its internal manifest.

How to sort a collection by date in MongoDB?

This worked for me:

collection.find({}, {"sort" : [['datefield', 'asc']]}, function (err, docs) { ... });

Using Node.js, Express.js, and Monk

How do I convert an integer to binary in JavaScript?

The binary in 'convert to binary' can refer to three main things. The positional number system, the binary representation in memory or 32bit bitstrings. (for 64bit bitstrings see Patrick Roberts' answer)

1. Number System

(123456).toString(2) will convert numbers to the base 2 positional numeral system. In this system negative numbers are written with minus signs just like in decimal.

2. Internal Representation

The internal representation of numbers is 64 bit floating point and some limitations are discussed in this answer. There is no easy way to create a bit-string representation of this in javascript nor access specific bits.

3. Masks & Bitwise Operators

MDN has a good overview of how bitwise operators work. Importantly:

Bitwise operators treat their operands as a sequence of 32 bits (zeros and ones)

Before operations are applied the 64 bit floating points numbers are cast to 32 bit signed integers. After they are converted back.

Here is the MDN example code for converting numbers into 32-bit strings.

function createBinaryString (nMask) {
  // nMask must be between -2147483648 and 2147483647
  for (var nFlag = 0, nShifted = nMask, sMask = ""; nFlag < 32;
       nFlag++, sMask += String(nShifted >>> 31), nShifted <<= 1);
  return sMask;
}

createBinaryString(0) //-> "00000000000000000000000000000000"
createBinaryString(123) //-> "00000000000000000000000001111011"
createBinaryString(-1) //-> "11111111111111111111111111111111"
createBinaryString(-1123456) //-> "11111111111011101101101110000000"
createBinaryString(0x7fffffff) //-> "01111111111111111111111111111111"

What does "wrong number of arguments (1 for 0)" mean in Ruby?

If you change from using a lambda with one argument to a function with one argument, you will get this error.

For example:

You had:

foobar = lambda do |baz|
  puts baz
end

and you changed the definition to

def foobar(baz)
  puts baz
end

And you left your invocation as:

foobar.call(baz)

And then you got the message

ArgumentError: wrong number of arguments (0 for 1)

when you really meant:

foobar(baz)

Draw radius around a point in Google map

For a API v3 solution, refer to:

http://blog.enbake.com/draw-circle-with-google-maps-api-v3

It creates circle around points and then show markers within and out of the range with different colors. They also calculate dynamic radius but in your case radius is fixed so may be less work.

Should have subtitle controller already set Mediaplayer error Android

Also you can only set mediaPlayer.reset() and in onDestroy set it to release.

Reading a string with scanf

An array "decays" into a pointer to its first element, so scanf("%s", string) is equivalent to scanf("%s", &string[0]). On the other hand, scanf("%s", &string) passes a pointer-to-char[256], but it points to the same place.

Then scanf, when processing the tail of its argument list, will try to pull out a char *. That's the Right Thing when you've passed in string or &string[0], but when you've passed in &string you're depending on something that the language standard doesn't guarantee, namely that the pointers &string and &string[0] -- pointers to objects of different types and sizes that start at the same place -- are represented the same way.

I don't believe I've ever encountered a system on which that doesn't work, and in practice you're probably safe. None the less, it's wrong, and it could fail on some platforms. (Hypothetical example: a "debugging" implementation that includes type information with every pointer. I think the C implementation on the Symbolics "Lisp Machines" did something like this.)

send mail to multiple receiver with HTML mailto

"There are no safe means of assigning multiple recipients to a single mailto: link via HTML. There are safe, non-HTML, ways of assigning multiple recipients from a mailto: link."

http://www.sightspecific.com/~mosh/www_faq/multrec.html

For a quick fix to your problem, change your ; to a comma , and eliminate the spaces between email addresses

<a href='mailto:[email protected],[email protected]'>Email Us</a>

batch script - read line by line

Try this:

@echo off
for /f "tokens=*" %%a in (input.txt) do (
  echo line=%%a
)
pause

because of the tokens=* everything is captured into %a

edit: to reply to your comment, you would have to do that this way:

@echo off
for /f "tokens=*" %%a in (input.txt) do call :processline %%a

pause
goto :eof

:processline
echo line=%*

goto :eof

:eof

Because of the spaces, you can't use %1, because that would only contain the part until the first space. And because the line contains quotes, you can also not use :processline "%%a" in combination with %~1. So you need to use %* which gets %1 %2 %3 ..., so the whole line.

How do I convert from BLOB to TEXT in MySQL?

Or you can use this function:

DELIMITER $$

CREATE FUNCTION BLOB2TXT (blobfield VARCHAR(255)) RETURNS longtext
DETERMINISTIC
NO SQL
BEGIN
       RETURN CAST(blobfield AS CHAR(10000) CHARACTER SET utf8);
END
$$


DELIMITER ;

How to stop default link click behavior with jQuery

You want e.preventDefault() to prevent the default functionality from occurring.

Or have return false from your method.

preventDefault prevents the default functionality and stopPropagation prevents the event from bubbling up to container elements.

Unable to start Service Intent

In my case the 1 MB maximum cap for data transport by Intent. I'll just use Cache or Storage.

How to debug when Kubernetes nodes are in 'Not Ready' state

I found applying the network and rebooting both the nodes did the trick for me.

kubectl apply -f [podnetwork].yaml

Managing jQuery plugin dependency in webpack

This works in webpack 3:

in the webpack.config.babel.js file:

resolve: {
    alias: {
         jquery: "jquery/src/jquery"
    },
 ....
}

And use ProvidePlugin

new webpack.ProvidePlugin({
        '$': 'jquery',
        'jQuery': 'jquery',
    })

Java Keytool error after importing certificate , "keytool error: java.io.FileNotFoundException & Access Denied"

This could happen if you are not running the command prompt in administrator mode. If you are using windows 7, you can go to run, type cmd and hit Ctrl+Shift+enter. This will open the command prompt in administrator mode. If not, you can also go to start -> all programs -> accessories -> right click command prompt and click 'run as administrator'.

Java 8 LocalDate Jackson format

The simplest solution (which supports deserialization and serialization as well) is

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy")
@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
private LocalDate dateOfBirth;

While using the following dependencies in your project.

Maven

<dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-databind</artifactId>
   <version>2.9.7</version>
</dependency>
<dependency>
   <groupId>com.fasterxml.jackson.datatype</groupId>
   <artifactId>jackson-datatype-jsr310</artifactId>
   <version>2.9.7</version>
</dependency>

Gradle

compile "com.fasterxml.jackson.core:jackson-databind:2.9.7"
compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.9.7"

No additional implementation of a ContextResolver, Serializer or Deserializer is required.

Returning unique_ptr from functions

This is in no way specific to std::unique_ptr, but applies to any class that is movable. It's guaranteed by the language rules since you are returning by value. The compiler tries to elide copies, invokes a move constructor if it can't remove copies, calls a copy constructor if it can't move, and fails to compile if it can't copy.

If you had a function that accepts std::unique_ptr as an argument you wouldn't be able to pass p to it. You would have to explicitly invoke move constructor, but in this case you shouldn't use variable p after the call to bar().

void bar(std::unique_ptr<int> p)
{
    // ...
}

int main()
{
    unique_ptr<int> p = foo();
    bar(p); // error, can't implicitly invoke move constructor on lvalue
    bar(std::move(p)); // OK but don't use p afterwards
    return 0;
}

Rebase array keys after unsetting elements

100% working for me ! After unset elements in array you can use this for re-indexing the array

$result=array_combine(range(1, count($your_array)), array_values($your_array));

All combinations of a list of lists

you need itertools.product:

>>> import itertools
>>> a = [[1,2,3],[4,5,6],[7,8,9,10]]
>>> list(itertools.product(*a))
[(1, 4, 7), (1, 4, 8), (1, 4, 9), (1, 4, 10), (1, 5, 7), (1, 5, 8), (1, 5, 9), (1, 5, 10), (1, 6, 7), (1, 6, 8), (1, 6, 9), (1, 6, 10), (2, 4, 7), (2, 4, 8), (2, 4, 9), (2, 4, 10), (2, 5, 7), (2, 5, 8), (2, 5, 9), (2, 5, 10), (2, 6, 7), (2, 6, 8), (2, 6, 9), (2, 6, 10), (3, 4, 7), (3, 4, 8), (3, 4, 9), (3, 4, 10), (3, 5, 7), (3, 5, 8), (3, 5, 9), (3, 5, 10), (3, 6, 7), (3, 6, 8), (3, 6, 9), (3, 6, 10)]

Proxy with urllib2

To use the default system proxies (e.g. from the http_support environment variable), the following works for the current request (without installing it into urllib2 globally):

url = 'http://www.example.com/'
proxy = urllib2.ProxyHandler()
opener = urllib2.build_opener(proxy)
in_ = opener.open(url)
in_.read()

MSBuild doesn't copy references (DLL files) if using project dependencies in solution

This requires adding a .targets file to your project and setting it to be included in the project's includes section.

See my answer here for the procedure.

SQL JOIN, GROUP BY on three tables to get totals

I have a tip for those, who want to get various aggregated values from the same table.

Lets say I have table with users and table with points the users acquire. So the connection between them is 1:N (one user, many points records).

Now in the table 'points' I also store the information about for what did the user get the points (login, clicking a banner etc.). And I want to list all users ordered by SUM(points) AND then by SUM(points WHERE type = x). That is to say ordered by all the points user has and then by points the user got for a specific action (eg. login).

The SQL would be:

SELECT SUM(points.points) AS points_all, SUM(points.points * (points.type = 7)) AS points_login
FROM user
LEFT JOIN points ON user.id = points.user_id
GROUP BY user.id

The beauty of this is in the SUM(points.points * (points.type = 7)) where the inner parenthesis evaluates to either 0 or 1 thus multiplying the given points value by 0 or 1, depending on wheteher it equals to the the type of points we want.

How to import NumPy in the Python shell

The message is fairly self-explanatory; your working directory should not be the NumPy source directory when you invoke Python; NumPy should be installed and your working directory should be anything but the directory where it lives.

jQuery UI autocomplete with item and id

Just want to share what worked on my end, in case it would be able to help someone else too. Alternatively based on Paty Lustosa's answer above, please allow me to add another approach derived from this site where he used an ajax approach for the source method

http://salman-w.blogspot.ca/2013/12/jquery-ui-autocomplete-examples.html#example-3

The kicker is the resulting "string" or json format from your php script (listing.php below) that derives the result set to be shown in the autocomplete field should follow something like this:

    {"list":[
     {"value": 1, "label": "abc"},
     {"value": 2, "label": "def"},
     {"value": 3, "label": "ghi"}
    ]}

Then on the source portion of the autocomplete method:

    source: function(request, response) {
        $.getJSON("listing.php", {
            term: request.term
        }, function(data) {                     
            var array = data.error ? [] : $.map(data.list, function(m) {
                return {
                    label: m.label,
                    value: m.value
                };
            });
            response(array);
        });
    },
    select: function (event, ui) {
        $("#autocomplete_field").val(ui.item.label); // display the selected text
        $("#field_id").val(ui.item.value); // save selected id to hidden input
        return false;
    }

Hope this helps... all the best!

create a trusted self-signed SSL cert for localhost (for use with Express/Node)

Some of the answers posted have pieces that were very useful to me to overcome this problem too. However, I was also interested in the minimum number of steps and, ideally, avoiding OpenSSL (on Windows 10).

So, one critical piece from the answers (credit: @TroyWorks) is that you need to edit your HOSTS file to create a fictitious server, and map that to 127.0.0.1. This assumes you are going to be doing local development.

In my case, I was using the SS certificate to secure a websocket in NodeJS, and that socket was being connected to programmatically (as opposed to via browser). So for me, it was critical that the certificate be accepted without warnings or errors, and the critical piece there was to get the cert created with a proper CN (and of course accept the cert into Trusted Authorities, as described elsewhere in the answers). Using IIS to create a self-signed cert won't create the proper CN, so I discovered the following simple command using Powershell:

New-SelfSignedCertificate -DnsName "gandalf.dummy.dev" -FriendlyName "gandalf" -CertStoreLocation "cert:\LocalMachine\My"

This has to be run in the PS Admin console, but it simply works, and puts the cert into the "Personal" section of the LocalMachine certificate store. You can verify it got created by executing:

ls cert:\LocalMachine\My 

To trust it, simply copy this and paste into "Trusted Root Certification Authorities" using Certificate Manager (making sure you are looking at the Local Machine certificates, not Current User!).

If you bind to this certificate in IIS, you should be able to hit https://gandalf.dummy.dev/ and get a secure connection without any warnings.

The final piece, using this in NodeJS, is described above and in other SO answers, so I'll only add that on Windows, it is easier to work with a pfx file that combines the cert and private key. You can export a pfx easily from the Certificate Manager, but it does affect how you use it in NodeJS. When instantiating a Server using the 'https' module, the options you would use (instead of 'key' and 'cert') would be 'pfx' and 'passphrase', as in:

var https = require('https');
var options = { 
    pfx: fs.readFileSync('mypfxfile'), 
    passphrase: 'foo' 
};
var server = https.createServer(options);

What should I do if the current ASP.NET session is null?

Yes, the Session object might be null, but only in certain circumstances, which you will only rarely run into:

If you only have code in pages, you won't run into this. Most of my ASP .NET code uses Session without checking for null repeatedly. It is, however, something to think about if you are developing an IHttpModule or otherwise is down in the grittier details of ASP .NET.

Edit

In answer to the comment: Whether or not session state is available depends on whether the AcquireRequestState event has run for the request. This is where the session state module does it's work by reading the session cookie and finding the appropiate set of session variables for you.

AcquireRequestState runs before control is handed to your Page. So if you are calling other functionality, including static classes, from your page, you should be fine.

If you have some classes doing initialization logic during startup, for example on the Application_Start event or by using a static constructor, Session state might not be available. It all boils down to whether there is a current request and AcquireRequestState has been run.

Also, should the client have disabled cookies, the Session object will still be available - but on the next request, the user will return with a new empty Session. This is because the client is given a Session statebag if he does not have one already. If the client does not transport the session cookie, we have no way of identifying the client as the same, so he will be handed a new session again and again.

How to compare two double values in Java?

        int mid = 10;
        for (double j = 2 * mid; j >= 0; j = j - 0.1) {
            if (j == mid) {
                System.out.println("Never happens"); // is NOT printed
            }

            if (Double.compare(j, mid) == 0) {
                System.out.println("No way!"); // is NOT printed
            }

            if (Math.abs(j - mid) < 1e-6) {
                System.out.println("Ha!"); // printed
            }
        }
        System.out.println("Gotcha!");

How to actually search all files in Visual Studio

So the answer seems to be to NOT use the Solution Explorer search box.

Rather, open any file in the solution, then use the control-f search pop-up to search all files by:

  1. selecting "Find All" from the "--> Find Next / <-- Find Previous" selector
  2. selecting "Current Project" or "Entire Solution" from the selector that normally says just "Current Document".

What are carriage return, linefeed, and form feed?

Those are non-printing characters, relating to the concept of "new line". \n is linefeed. \r is carriage return. On different platforms they have different meanings, relative to a valid new line. In windows, a new line is \r\n. In linux, \n. In mac, \r.

In practice, you put them in any string, and it will have effect on the print-out of the string.

Pass a PHP variable value through an HTML form

EDIT: After your comments, I understand that you want to pass variable through your form.

You can do this using hidden field:

<input type='hidden' name='var' value='<?php echo "$var";?>'/> 

In PHP action File:

<?php 
   if(isset($_POST['var'])) $var=$_POST['var'];
?>

Or using sessions: In your first page:

 $_SESSION['var']=$var;

start_session(); should be placed at the beginning of your php page.

In PHP action File:

if(isset($_SESSION['var'])) $var=$_SESSION['var'];

First Answer:

You can also use $GLOBALS :

if (isset($_POST['save_exit']))
{

   echo $GLOBALS['var']; 

}

Check this documentation for more informations.

What is two way binding?

Two-way binding just means that:

  1. When properties in the model get updated, so does the UI.
  2. When UI elements get updated, the changes get propagated back to the model.

Backbone doesn't have a "baked-in" implementation of #2 (although you can certainly do it using event listeners). Other frameworks like Knockout do wire up two-way binding automagically.


enter image description here


In Backbone, you can easily achieve #1 by binding a view's "render" method to its model's "change" event. To achieve #2, you need to also add a change listener to the input element, and call model.set in the handler.

Here's a Fiddle with two-way binding set up in Backbone.

Why do I get TypeError: can't multiply sequence by non-int of type 'float'?

raw_input returns a string (a sequence of characters). In Python, multiplying a string and a float makes no defined meaning (while multiplying a string and an integer has a meaning: "AB" * 3 is "ABABAB"; how much is "L" * 3.14 ? Please do not reply "LLL|"). You need to parse the string to a numerical value.

You might want to try:

salesAmount = float(raw_input("Insert sale amount here\n"))

Maven: repository element was not specified in the POM inside distributionManagement?

I got the same message ("repository element was not specified in the POM inside distributionManagement element"). I checked /target/checkout/pom.xml and as per another answer and it really lacked <distributionManagement>.

It turned out that the problem was that <distributionManagement> was missing in pom.xml in my master branch (using git).

After cleaning up (mvn release:rollback, mvn clean, mvn release:clean, git tag -d v1.0.0) I run mvn release again and it worked.

How to add minutes to current time in swift

Two approaches:

  1. Use Calendar and date(byAdding:to:wrappingComponents:). E.g., in Swift 3 and later:

    let calendar = Calendar.current
    let date = calendar.date(byAdding: .minute, value: 5, to: startDate)
    
  2. Just use + operator (see +(_:_:)) to add a TimeInterval (i.e. a certain number of seconds). E.g. to add five minutes, you can:

    let date = startDate + 5 * 60
    

    (Note, the order is specific here: The date on the left side of the + and the seconds on the right side.)

    You can also use addingTimeInterval, if you’d prefer:

    let date = startDate.addingTimeInterval(5 * 60)
    

Bottom line, +/addingTimeInterval is easiest for simple scenarios, but if you ever want to add larger units (e.g., days, months, etc.), you would likely want to use the calendrical calculations because those adjust for daylight savings, whereas addingTimeInterval doesn’t.


For Swift 2 renditions, see the previous revision of this answer.

A variable modified inside a while loop is not remembered

Hmmm... I would almost swear that this worked for the original Bourne shell, but don't have access to a running copy just now to check.

There is, however, a very trivial workaround to the problem.

Change the first line of the script from:

#!/bin/bash

to

#!/bin/ksh

Et voila! A read at the end of a pipeline works just fine, assuming you have the Korn shell installed.

How do I compare two strings in python?

>>> s1="abc def ghi"
>>> s2="def ghi abc"
>>> s1 == s2  # For string comparison 
False
>>> sorted(list(s1)) == sorted(list(s2)) # For comparing if they have same characters. 
True
>>> sorted(list(s1))
[' ', ' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
>>> sorted(list(s2))
[' ', ' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

Set Locale programmatically

As no answer is complete for the current way to solve this problem, I try to give instructions for a complete solution. Please comment if something is missing or could be done better.

General information

First, there exist some libraries that want to solve the problem but they all seem outdated or are missing some features:

Further I think writing a library might not be a good/easy way to solve this problem because there is not very much to do, and what has to be done is rather changing existing code than using something completely decoupled. Therefore I composed the following instructions that should be complete.

My solution is mainly based on https://github.com/gunhansancar/ChangeLanguageExample (as already linked to by localhost). It is the best code I found to orientate at. Some remarks:

  • As necessary, it provides different implementations to change locale for Android N (and above) and below
  • It uses a method updateViews() in each Activity to manually update all strings after changing locale (using the usual getString(id)) which is not necessary in the approach shown below
  • It only supports languages and not complete locales (which also include region (country) and variant codes)

I changed it a bit, decoupling the part which persists the chosen locale (as one might want to do that separately, as suggested below).

Solution

The solution consists of the following two steps:

  • Permanently change the locale to be used by the app
  • Make the app use the custom locale set, without restarting

Step 1: Change the locale

Use the class LocaleHelper, based on gunhansancar's LocaleHelper:

  • Add a ListPreference in a PreferenceFragment with the available languages (has to be maintained when languages should be added later)
import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.preference.PreferenceManager;

import java.util.Locale;

import mypackage.SettingsFragment;

/**
 * Manages setting of the app's locale.
 */
public class LocaleHelper {

    public static Context onAttach(Context context) {
        String locale = getPersistedLocale(context);
        return setLocale(context, locale);
    }

    public static String getPersistedLocale(Context context) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getString(SettingsFragment.KEY_PREF_LANGUAGE, "");
    }

    /**
     * Set the app's locale to the one specified by the given String.
     *
     * @param context
     * @param localeSpec a locale specification as used for Android resources (NOTE: does not
     *                   support country and variant codes so far); the special string "system" sets
     *                   the locale to the locale specified in system settings
     * @return
     */
    public static Context setLocale(Context context, String localeSpec) {
        Locale locale;
        if (localeSpec.equals("system")) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                locale = Resources.getSystem().getConfiguration().getLocales().get(0);
            } else {
                //noinspection deprecation
                locale = Resources.getSystem().getConfiguration().locale;
            }
        } else {
            locale = new Locale(localeSpec);
        }
        Locale.setDefault(locale);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return updateResources(context, locale);
        } else {
            return updateResourcesLegacy(context, locale);
        }
    }

    @TargetApi(Build.VERSION_CODES.N)
    private static Context updateResources(Context context, Locale locale) {
        Configuration configuration = context.getResources().getConfiguration();
        configuration.setLocale(locale);
        configuration.setLayoutDirection(locale);

        return context.createConfigurationContext(configuration);
    }

    @SuppressWarnings("deprecation")
    private static Context updateResourcesLegacy(Context context, Locale locale) {
        Resources resources = context.getResources();

        Configuration configuration = resources.getConfiguration();
        configuration.locale = locale;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            configuration.setLayoutDirection(locale);
        }

        resources.updateConfiguration(configuration, resources.getDisplayMetrics());

        return context;
    }
}

Create a SettingsFragment like the following:

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import mypackage.LocaleHelper;
import mypackage.R;

/**
 * Fragment containing the app's main settings.
 */
public class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
    public static final String KEY_PREF_LANGUAGE = "pref_key_language";

    public SettingsFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_settings, container, false);
        return view;
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        switch (key) {
            case KEY_PREF_LANGUAGE:
                LocaleHelper.setLocale(getContext(), PreferenceManager.getDefaultSharedPreferences(getContext()).getString(key, ""));
                getActivity().recreate(); // necessary here because this Activity is currently running and thus a recreate() in onResume() would be too late
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        // documentation requires that a reference to the listener is kept as long as it may be called, which is the case as it can only be called from this Fragment
        getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
    }
}

Create a resource locales.xml listing all locales with available translations in the following way (list of locale codes):

<!-- Lists available locales used for setting the locale manually.
     For now only language codes (locale codes without country and variant) are supported.
     Has to be in sync with "settings_language_values" in strings.xml (the entries must correspond).
  -->
<resources>
    <string name="system_locale" translatable="false">system</string>
    <string name="default_locale" translatable="false"></string>
    <string-array name="locales">
        <item>@string/system_locale</item> <!-- system setting -->
        <item>@string/default_locale</item> <!-- default locale -->
        <item>de</item>
    </string-array>
</resources>

In your PreferenceScreen you can use the following section to let the user select the available languages:

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <PreferenceCategory
        android:title="@string/preferences_category_general">
        <ListPreference
            android:key="pref_key_language"
            android:title="@string/preferences_language"
            android:dialogTitle="@string/preferences_language"
            android:entries="@array/settings_language_values"
            android:entryValues="@array/locales"
            android:defaultValue="@string/system_locale"
            android:summary="%s">
        </ListPreference>
    </PreferenceCategory>
</PreferenceScreen>

which uses the following strings from strings.xml:

<string name="preferences_category_general">General</string>
<string name="preferences_language">Language</string>
<!-- NOTE: Has to correspond to array "locales" in locales.xml (elements in same orderwith) -->
<string-array name="settings_language_values">
    <item>Default (System setting)</item>
    <item>English</item>
    <item>German</item>
</string-array>

Step 2: Make the app use the custom locale

Now setup each Activity to use the custom locale set. The easiest way to accomplish this is to have a common base class for all activities with the following code (where the important code is in attachBaseContext(Context base) and onResume()):

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

import mypackage.LocaleHelper;
import mypackage.R;

/**
 * {@link AppCompatActivity} with main menu in the action bar. Automatically recreates
 * the activity when the locale has changed.
 */
public class MenuAppCompatActivity extends AppCompatActivity {
    private String initialLocale;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initialLocale = LocaleHelper.getPersistedLocale(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_settings:
                Intent intent = new Intent(this, SettingsActivity.class);
                startActivity(intent);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(LocaleHelper.onAttach(base));
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (initialLocale != null && !initialLocale.equals(LocaleHelper.getPersistedLocale(this))) {
            recreate();
        }
    }
}

What it does is

  • Override attachBaseContext(Context base) to use the locale previously persisted with LocaleHelper
  • Detect a change of the locale and recreate the Activity to update its strings

Notes on this solution

  • Recreating an Activity does not update the title of the ActionBar (as already observed here: https://github.com/gunhansancar/ChangeLanguageExample/issues/1).

    • This can be achieved by simply having a setTitle(R.string.mytitle) in the onCreate() method of each activity.
  • It lets the user chose the system default locale, as well as the default locale of the app (which can be named, in this case "English").

  • Only language codes, no region (country) and variant codes (like fr-rCA) are supported so far. To support full locale specifications, a parser similar to that in the Android-Languages library can be used (which supports region but no variant codes).

    • If someone finds or has written a good parser, add a comment so I can include it in the solution.

How to specify an element after which to wrap in css flexbox?

You can accomplish this by setting this on the container:

ul {
    display: flex;
    flex-wrap: wrap;
}

And on the child you set this:

li:nth-child(2n) {
    flex-basis: 100%;
}

_x000D_
_x000D_
ul {
  display: flex;
  flex-wrap: wrap;
  list-style: none;
}

li:nth-child(4n) {
  flex-basis: 100%;
}
_x000D_
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
</ul>
_x000D_
_x000D_
_x000D_

This causes the child to make up 100% of the container width before any other calculation. Since the container is set to break in case there is not enough space it does so before and after this child. So you could use an empty div element to force the wrap between the element before and after it.

iPhone UILabel text soft shadow

I advise you to use the shadowColor and shadowOffset properties of UILabel:

UILabel* label = [[UILabel alloc] init];
label.shadowColor = [UIColor whiteColor];
label.shadowOffset = CGSizeMake(0,1);

How do I find what Java version Tomcat6 is using?

Once you have started tomcat simply run the following command at a terminal prompt:

ps -ef | grep tomcat

This will show the process details and indicate which JVM (by folder location) is running tomcat.