Programs & Examples On #Radio

Radio is the transmission of signals through free space by electromagnetic radiation of a frequency significantly below that of visible light, or a device for doing the same. Radios are typically used for communication including voice, video and data. This includes Wi-fi, Bluetooth, Mobile phones, GPS, Radar, some remote control devices and near field communication devices (NFC) such as contactless smartcards.

Vertically aligning text next to a radio button

I think this is what you might be asking for

http://jsbin.com/ixowuw/2/

CSS

label{
  font-size:18px;
  vertical-align: middle;
}

input[type="radio"]{
  vertical-align: middle;
}

HTML

<span>
  <input type="radio" id="oddsPref" name="oddsPref" value="decimal" />
  <label>Decimal</label>
</span>

show and hide divs based on radio button click

The hide selector was incorrect. I hid the blocks at page load and showed the selected value. I also changed the car div id's to make it easier to append the radio button value and create the proper id selector.

<div id="myRadioGroup">
  2 Cars<input type="radio" name="cars" checked="checked" value="2"  />
  3 Cars<input type="radio" name="cars" value="3" />
  <div id="car-2">
  2 Cars
  </div>
  <div id="car-3">
  3 Cars
  </div>
</div>

<script type="text/javascript">
$(document).ready(function(){ 
  $("div div").hide();
  $("#car-2").show();
  $("input[name$='cars']").click(function() {
      var test = $(this).val();
      $("div div").hide();
      $("#car-"+test).show();
  }); 
});
</script>

jQuery check/uncheck radio button onclick

I have expanded on the previous suggestions. This works for me, with multiple radios coupled by the same name.

$("input[type='radio']").click(function()
{
  var previousValue = $(this).attr('previousValue');
  var name = $(this).attr('name');

  if (previousValue == 'checked')
  {
    $(this).removeAttr('checked');
    $(this).attr('previousValue', false);
  }
  else
  {
    $("input[name="+name+"]:radio").attr('previousValue', false);
    $(this).attr('previousValue', 'checked');
  }
});

AngularJS - Binding radio buttons to models with boolean values

The way your radios are set up in the fiddle - sharing the same model - will cause only the last group to show a checked radio if you decide to quote all of the truthy values. A more solid approach will involve giving the individual groups their own model, and set the value as a unique attribute of the radios, such as the id:

$scope.radioMod = 1;
$scope.radioMod2 = 2;

Here is a representation of the new html:

<label data-ng-repeat="choice2 in question2.choices">
            <input type="radio" name="response2" data-ng-model="radioMod2" value="{{choice2.id}}"/>
                {{choice2.text}}
        </label>

And a fiddle.

SQLAlchemy IN clause

An alternative way is using raw SQL mode with SQLAlchemy, I use SQLAlchemy 0.9.8, python 2.7, MySQL 5.X, and MySQL-Python as connector, in this case, a tuple is needed. My code listed below:

id_list = [1, 2, 3, 4, 5] # in most case we have an integer list or set
s = text('SELECT id, content FROM myTable WHERE id IN :id_list')
conn = engine.connect() # get a mysql connection
rs = conn.execute(s, id_list=tuple(id_list)).fetchall()

Hope everything works for you.

Get full URL and query string in Servlet for both HTTP and HTTPS requests

Simply Use:

String Uri = request.getRequestURL()+"?"+request.getQueryString();

Accurate way to measure execution times of php scripts

Create file loadtime.php

<?php
class loadTime{
    private $time_start     =   0;
    private $time_end       =   0;
    private $time           =   0;
    public function __construct(){
        $this->time_start= microtime(true);
    }
    public function __destruct(){
        $this->time_end = microtime(true);
        $this->time = $this->time_end - $this->time_start;
        echo "Loaded in $this->time seconds\n";
    }
}

Than in the beggining of your script, after <?php write include 'loadtime.php'; $loadtime=new loadTime();

When page is loaded at the end there will be written "Loaded in x seconds"

Specify sudo password for Ansible

My hack to automate this was to use an environment variable and access it via --extra-vars="ansible_become_pass='{{ lookup('env', 'ANSIBLE_BECOME_PASS') }}'".

Export an env var, but avoid bash/shell history (prepend with a space, or other methods). E.g.:

     export ANSIBLE_BECOME_PASS='<your password>'

Lookup the env var while passing the extra ansible_become_pass variable into the ansible-playbook, E.g.:

ansible-playbook playbook.yml -i inventories/dev/hosts.yml -u user --extra-vars="ansible_become_pass='{{ lookup('env', 'ANSIBLE_BECOME_PASS') }}'"

Good alternate answers:

Creating custom function in React component

You can try this.

// Author: Hannad Rehman Sat Jun 03 2017 12:59:09 GMT+0530 (India Standard Time)

import React from 'react';
import RippleButton from '../../Components/RippleButton/rippleButton.jsx';

class HtmlComponents extends React.Component {

    constructor(props){
        super(props);
        this.rippleClickFunction=this.rippleClickFunction.bind(this);
    }

    rippleClickFunction(){
        //do stuff. 
        // foo==bar
    }

    render() {
      return (
         <article>
             <h1>React Components</h1>
             <RippleButton onClick={this.rippleClickFunction}/>
         </article>
      );
   }
}

export default HtmlComponents;

Yhe only concern is you have to bind the context to the function

Error C1083: Cannot open include file: 'stdafx.h'

You can fix this problem by adding "$(ProjectDir)" (or wherever the stdafx.h is) to list of directories under Project->Properties->Configuration Properties->C/C++->General->Additional Include Directories.

error opening trace file: No such file or directory (2)

You will not have access to your real sd card in emulator. You will have to follow the steps in this tutorial to direct your emulator to a directory on your development environment acting as your SD card.

Eclipse will not open due to environment variables

very easy, you just copy the folder 'jre' to the folder that you put eclipse. That'all. Jre is the environment, normally it's location in the C:/Programing Files/Java/jre :D

MySQL IF ELSEIF in select query

I found a bug in MySQL 5.1.72 when using the nested if() functions .... the value of column variables (e.g. qty_1) is blank inside the second if(), rendering it useless. Use the following construct instead:

case 
  when qty_1<='23' then price
  when '23'>qty_1 && qty_2<='23' then price_2
  when '23'>qty_2 && qty_3<='23' then price_3
  when '23'>qty_3 then price_4
  else 1
end

Python - How to concatenate to a string in a for loop?

That's not how you do it.

>>> ''.join(['first', 'second', 'other'])
'firstsecondother'

is what you want.

If you do it in a for loop, it's going to be inefficient as string "addition"/concatenation doesn't scale well (but of course it's possible):

>>> mylist = ['first', 'second', 'other']
>>> s = ""
>>> for item in mylist:
...    s += item
...
>>> s
'firstsecondother'

How to allow http content within an iframe on a https site

All you need to do is just use Google as a Proxy server.

https://www.google.ie/gwt/x?u=[YourHttpLink].

<iframe src="https://www.google.ie/gwt/x?u=[Your http link]"></frame>

It worked for me.

Credits:- https://www.wikihow.com/Use-Google-As-a-Proxy

Docker container not starting (docker start)

What I need is to use Docker with MariaDb on different port /3301/ on my Ubuntu machine because I already had MySql installed and running on 3306.

To do this after half day searching did it using:

docker run -it -d -p 3301:3306 -v ~/mdbdata/mariaDb:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=root --name mariaDb mariadb

This pulls the image with latest MariaDb, creates container called mariaDb, and run mysql on port 3301. All data of which is located in home directory in /mdbdata/mariaDb.

To login in mysql after that can use:

mysql -u root -proot -h 127.0.0.1 -P3301

Used sources are:

The answer of Iarks in this article /using -it -d was the key :) /

how-to-install-and-use-docker-on-ubuntu-16-04

installing-and-using-mariadb-via-docker

mariadb-and-docker-use-cases-part-1

Good luck all!

Remove all child nodes from a parent?

You can use .empty(), like this:

$("#foo").empty();

From the docs:

Remove all child nodes of the set of matched elements from the DOM.

How to redirect the output of an application in background to /dev/null

You use:

yourcommand  > /dev/null 2>&1

If it should run in the Background add an &

yourcommand > /dev/null 2>&1 &

>/dev/null 2>&1 means redirect stdout to /dev/null AND stderr to the place where stdout points at that time

If you want stderr to occur on console and only stdout going to /dev/null you can use:

yourcommand 2>&1 > /dev/null

In this case stderr is redirected to stdout (e.g. your console) and afterwards the original stdout is redirected to /dev/null

If the program should not terminate you can use:

nohup yourcommand &

Without any parameter all output lands in nohup.out

LINQ query to select top five

This can also be achieved using the Lambda based approach of Linq;

var list = ctn.Items
.Where(t=> t.DeliverySelection == true && t.Delivery.SentForDelivery == null)
.OrderBy(t => t.Delivery.SubmissionDate)
.Take(5);

How to get character array from a string?

It already is:

_x000D_
_x000D_
var mystring = 'foobar';_x000D_
console.log(mystring[0]); // Outputs 'f'_x000D_
console.log(mystring[3]); // Outputs 'b'
_x000D_
_x000D_
_x000D_

Or for a more older browser friendly version, use:

_x000D_
_x000D_
var mystring = 'foobar';_x000D_
console.log(mystring.charAt(3)); // Outputs 'b'
_x000D_
_x000D_
_x000D_

Hiding the address bar of a browser (popup)

This is how I do it for popups, though it is only working with IE11, not Chrome- haven't tested in Firefox.

window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no');

Removing first x characters from string?

Another way (depending on your actual needs): If you want to pop the first n characters and save both the popped characters and the modified string:

s = 'lipsum'
n = 3
a, s = s[:n], s[n:]
print(a)
# lip
print(s)
# sum

Set selected item of spinner programmatically

You can easily set like this: spinner.setSelection(1), instead of 1, you can set any position of list you would like to show.

Git refusing to merge unrelated histories on rebase

I ran this command and issue got resolved.

git pull origin branchName --allow-unrelated-histories

Check out this page for more info.

React: "this" is undefined inside a component function

You can rewrite how your onToggleLoop method is called from your render() method.

render() {
    var shuffleClassName = this.state.toggleActive ? "player-control-icon active" : "player-control-icon"

return (
  <div className="player-controls">
    <FontAwesome
      className="player-control-icon"
      name='refresh'
      onClick={(event) => this.onToggleLoop(event)}
      spin={this.state.loopActive}
    />       
  </div>
    );
  }

The React documentation shows this pattern in making calls to functions from expressions in attributes.

Get jQuery version from inspecting the jQuery object

You can use either $().jquery; or $.fn.jquery which will return a string containing the version number, e.g. 1.6.2.

How to access the correct `this` inside a callback?

this in JS:

The value of this in JS is 100% determined by how a function is called, and not how it is defined. We can relatively easily find the value of this by the 'left of the dot rule':

  1. When the function is created using the function keyword the value of this is the object left of the dot of the function which is called
  2. If there is no object left of the dot then the value of this inside a function is often the global object (global in node, window in browser). I wouldn't recommend using the this keyword here because it is less explicit than using something like window!
  3. There exist certain constructs like arrow functions and functions created using the Function.prototype.bind() a function that can fix the value of this. These are exceptions of the rule but are really helpful to fix the value of this.

Example in nodeJS

module.exports.data = 'module data';
// This outside a function in node refers to module.exports object
console.log(this);

const obj1 = {
    data: "obj1 data",
    met1: function () {
        console.log(this.data);
    },
    met2: () => {
        console.log(this.data);
    },
};

const obj2 = {
    data: "obj2 data",
    test1: function () {
        console.log(this.data);
    },
    test2: function () {
        console.log(this.data);
    }.bind(obj1),
    test3: obj1.met1,
    test4: obj1.met2,
};

obj2.test1();
obj2.test2();
obj2.test3();
obj2.test4();
obj1.met1.call(obj2);

Output:

enter image description here

Let me walk you through the outputs 1 by 1 (ignoring the first log starting from the second):

  1. this is obj2 because of the left of the dot rule, we can see how test1 is called obj2.test1();. obj2 is left of the dot and thus the this value.
  2. Even though obj2 is left of the dot, test2 is bound to obj1 via the bind() method. So the this value is obj1.
  3. obj2 is left of the dot from the function which is called: obj2.test3(). Therefore obj2 will be the value of this.
  4. In this case: obj2.test4() obj2 is left of the dot. However, arrow functions don't have their own this binding. Therefore it will bind to the this value of the outer scope which is the module.exports an object which was logged in the beginning.
  5. We can also specify the value of this by using the call function. Here we can pass in the desired this value as an argument, which is obj2 in this case.

How do I convert an integer to binary in JavaScript?

function dec2bin(dec){
    return (dec >>> 0).toString(2);
}

dec2bin(1);    // 1
dec2bin(-1);   // 11111111111111111111111111111111
dec2bin(256);  // 100000000
dec2bin(-256); // 11111111111111111111111100000000

You can use Number.toString(2) function, but it has some problems when representing negative numbers. For example, (-1).toString(2) output is "-1".

To fix this issue, you can use the unsigned right shift bitwise operator (>>>) to coerce your number to an unsigned integer.

If you run (-1 >>> 0).toString(2) you will shift your number 0 bits to the right, which doesn't change the number itself but it will be represented as an unsigned integer. The code above will output "11111111111111111111111111111111" correctly.

This question has further explanation.

-3 >>> 0 (right logical shift) coerces its arguments to unsigned integers, which is why you get the 32-bit two's complement representation of -3.

How to check if an option is selected?

You can use this way by jquery :

_x000D_
_x000D_
$(document).ready(function(){_x000D_
 $('#panel_master_user_job').change(function () {_x000D_
 var job =  $('#panel_master_user_job').val();_x000D_
 alert(job);_x000D_
})_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select name="job" id="panel_master_user_job" class="form-control">_x000D_
                                    <option value="master">Master</option>_x000D_
                                    <option value="user">User</option>_x000D_
                                    <option value="admin">Admin</option>_x000D_
                                    <option value="custom">Custom</option>_x000D_
                                </select>
_x000D_
_x000D_
_x000D_

Link to "pin it" on pinterest without generating a button

For such cases, I found very useful the Share Link Generator, it helps creating Facebook, Google+, Twitter, Pinterest, LinkedIn share buttons.

How to convert Double to int directly?

If you really should use Double instead of double you even can get the int Value of Double by calling:

Double d = new Double(1.23);
int i = d.intValue();

Else its already described by Peter Lawreys answer.

Adding an onclick function to go to url in JavaScript?

Not completely sure I understand the question, but do you mean something like this?

$('#something').click(function() { 
    document.location = 'http://somewhere.com/';
} );

Open another application from your own (intent)

Use this :

    PackageManager pm = getPackageManager();
    Intent intent = pm.getLaunchIntentForPackage("com.package.name");
    startActivity(intent);

Flutter - The method was called on null

As stated in the above answers, it's always a good practice to initialize the variables, but if you have something which you don't know what value should it takes, and you want to leave it uninitialized so you have to make sure that you are updating it before using it.

For example: Assume we have double _bmi; and you don't know what value should it takes, so you can leave it as it is, but before using it, you have to update its value first like calling a function that calculating BMI like follows:

String calculateBMI (){
_bmi = weight / pow( height/100, 2);
return _bmi.toStringAsFixed(1);}

or whatever, what I mean is, you can leave the variable as it is, but before using it make sure you have initialized it using whatever the method you are using.

How to use npm with node.exe?

The current windows installer from nodejs.org as of v0.6.11 (2012-02-20) will install NPM along with NodeJS.

NOTES:

  • At this point, the 64-bit version is your best bet
  • The install path for 32-bit node is "Program Files (x86)" in 64-bit windows.
  • You may also need to add quotes to the path statement in environment variables, this only seems to be in some cases that I've seen.
  • In Windows, the global install path is actually in your user's profile directory
    • %USERPROFILE%\AppData\Roaming\npm
    • %USERPROFILE%\AppData\Roaming\npm-cache
    • WARNING: If you're doing timed events or other automation as a different user, make sure you run npm install as that user. Some modules/utilities should be installed globally.
    • INSTALLER BUGS: You may have to create these directories or add the ...\npm directory to your users path yourself.

To change the "global" location for all users to a more appropriate shared global location %ALLUSERSPROFILE%\(npm|npm-cache) (do this as an administrator):

  • create an [NODE_INSTALL_PATH]\etc\ directory
    • this is needed before you try npm config --global ... actions
  • create the global (admin) location(s) for npm modules
    • C:\ProgramData\npm-cache - npm modules will go here
    • C:\ProgramData\npm - binary scripts for globally installed modules will go here
    • C:\ProgramData\npm\node_modules - globally installed modules will go here
    • set the permissions appropriately
      • administrators: modify
      • authenticated users: read/execute
  • Set global configuration settings (Administrator Command Prompt)
    • npm config --global set prefix "C:\ProgramData\npm"
    • npm config --global set cache "C:\ProgramData\npm-cache"
  • Add C:\ProgramData\npm to your System's Path environment variable

If you want to change your user's "global" location to %LOCALAPPDATA%\(npm|npm-cache) path instead:

  • Create the necessary directories
    • C:\Users\YOURNAME\AppData\Local\npm-cache - npm modules will go here
    • C:\Users\YOURNAME\AppData\Local\npm - binary scripts for installed modules will go here
    • C:\Users\YOURNAME\AppData\Local\npm\node_modules - globally installed modules will go here
  • Configure npm
    • npm config set prefix "C:\Users\YOURNAME\AppData\Local\npm"
    • npm config set cache "C:\Users\YOURNAME\AppData\Local\npm-cache"
  • Add the new npm path to your environment's PATH.
    • setx PATH "%PATH%;C:\Users\YOURNAME\AppData\Local\npm"

For beginners, some of the npm modules I've made the most use of are as follows.

More advanced JS options...

For testing, I reach for the following tools...

  • mocha - testing framework
  • chai - assertion library, I like chai.expect
  • sinon - spies and stubs and shims
  • sinon-chai - extend chai with sinon's assertion tools
  • babel-istanbul - coverage reports
  • jest - parallel testing, assertions, mocking, coverage reports in one tool
  • babel-plugin-rewire - slightly easier for some mocking conditions vs. jest

Web tooling.

  • webpack - module bundler, package node-style modules for browser usage
  • babel - convert modern JS (ES2015+) syntax for your deployment environment.

If you build it...

  • shelljs - shell utilities for node scripts,. I used to use gulp/grunt, but these days will have a scripts directory that's referenced in package.json scripts via npm. You can use gulp tools inside plain scripts.

MS Excel showing the formula in a cell instead of the resulting value

Check for spaces in your formula before the "=". example' =A1' instean '=A1'

Replace special characters in a string with _ (underscore)

string = string.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g,'_');

Alternatively, to change all characters except numbers and letters, try:

string = string.replace(/[^a-zA-Z0-9]/g,'_');

How can I pretty-print JSON using Go?

Edit Looking back, this is non-idiomatic Go. Small helper functions like this add an extra step of complexity. In general, the Go philosophy prefers to include the 3 simple lines over 1 tricky line.


As @robyoder mentioned, json.Indent is the way to go. Thought I'd add this small prettyprint function:

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
)

//dont do this, see above edit
func prettyprint(b []byte) ([]byte, error) {
    var out bytes.Buffer
    err := json.Indent(&out, b, "", "  ")
    return out.Bytes(), err
}

func main() {
    b := []byte(`{"hello": "123"}`)
    b, _ = prettyprint(b)
    fmt.Printf("%s", b)
}

https://go-sandbox.com/#/R4LWpkkHIN or http://play.golang.org/p/R4LWpkkHIN

setTimeout in for-loop does not print consecutive values

The function argument to setTimeout is closing over the loop variable. The loop finishes before the first timeout and displays the current value of i, which is 3.

Because JavaScript variables only have function scope, the solution is to pass the loop variable to a function that sets the timeout. You can declare and call such a function like this:

for (var i = 1; i <= 2; i++) {
    (function (x) {
        setTimeout(function () { alert(x); }, 100);
    })(i);
}

What is the difference between ManualResetEvent and AutoResetEvent in .NET?

OK, normally it does not a good practice to add 2 answers in same thread, but I did not want to edit/delete my previous answer, since it can help on another manner.

Now, I created, much more comprehensive, and easy to understand, run-to-learn console app snippet below.

Just run the examples on two different consoles, and observe behaviour. You will get much more clear idea there what is happening behind the scenes.

Manual Reset Event

using System;
using System.Threading;

namespace ConsoleApplicationDotNetBasics.ThreadingExamples
{
    public class ManualResetEventSample
    {
        private readonly ManualResetEvent _manualReset = new ManualResetEvent(false);

        public void RunAll()
        {
            new Thread(Worker1).Start();
            new Thread(Worker2).Start();
            new Thread(Worker3).Start();
            Console.WriteLine("All Threads Scheduled to RUN!. ThreadId: {0}", Thread.CurrentThread.ManagedThreadId);
            Console.WriteLine("Main Thread is waiting for 15 seconds, observe 3 thread behaviour. All threads run once and stopped. Why? Because they call WaitOne() internally. They will wait until signals arrive, down below.");
            Thread.Sleep(15000);
            Console.WriteLine("1- Main will call ManualResetEvent.Set() in 5 seconds, watch out!");
            Thread.Sleep(5000);
            _manualReset.Set();
            Thread.Sleep(2000);
            Console.WriteLine("2- Main will call ManualResetEvent.Set() in 5 seconds, watch out!");
            Thread.Sleep(5000);
            _manualReset.Set();
            Thread.Sleep(2000);
            Console.WriteLine("3- Main will call ManualResetEvent.Set() in 5 seconds, watch out!");
            Thread.Sleep(5000);
            _manualReset.Set();
            Thread.Sleep(2000);
            Console.WriteLine("4- Main will call ManualResetEvent.Reset() in 5 seconds, watch out!");
            Thread.Sleep(5000);
            _manualReset.Reset();
            Thread.Sleep(2000);
            Console.WriteLine("It ran one more time. Why? Even Reset Sets the state of the event to nonsignaled (false), causing threads to block, this will initial the state, and threads will run again until they WaitOne().");
            Thread.Sleep(10000);
            Console.WriteLine();
            Console.WriteLine("This will go so on. Everytime you call Set(), ManualResetEvent will let ALL threads to run. So if you want synchronization between them, consider using AutoReset event, or simply user TPL (Task Parallel Library).");
            Thread.Sleep(5000);
            Console.WriteLine("Main thread reached to end! ThreadId: {0}", Thread.CurrentThread.ManagedThreadId);

        }

        public void Worker1()
        {
            for (int i = 1; i <= 10; i++)
            {
                Console.WriteLine("Worker1 is running {0}/10. ThreadId: {1}.", i, Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(5000);
                // this gets blocked until _autoReset gets signal
                _manualReset.WaitOne();
            }
            Console.WriteLine("Worker1 is DONE. ThreadId: {0}", Thread.CurrentThread.ManagedThreadId);
        }
        public void Worker2()
        {
            for (int i = 1; i <= 10; i++)
            {
                Console.WriteLine("Worker2 is running {0}/10. ThreadId: {1}.", i, Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(5000);
                // this gets blocked until _autoReset gets signal
                _manualReset.WaitOne();
            }
            Console.WriteLine("Worker2 is DONE. ThreadId: {0}", Thread.CurrentThread.ManagedThreadId);
        }
        public void Worker3()
        {
            for (int i = 1; i <= 10; i++)
            {
                Console.WriteLine("Worker3 is running {0}/10. ThreadId: {1}.", i, Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(5000);
                // this gets blocked until _autoReset gets signal
                _manualReset.WaitOne();
            }
            Console.WriteLine("Worker3 is DONE. ThreadId: {0}", Thread.CurrentThread.ManagedThreadId);
        }
    }

}

Manual Reset Event Output

Auto Reset Event

using System;
using System.Threading;

namespace ConsoleApplicationDotNetBasics.ThreadingExamples
{
    public class AutoResetEventSample
    {
        private readonly AutoResetEvent _autoReset = new AutoResetEvent(false);

        public void RunAll()
        {
            new Thread(Worker1).Start();
            new Thread(Worker2).Start();
            new Thread(Worker3).Start();
            Console.WriteLine("All Threads Scheduled to RUN!. ThreadId: {0}", Thread.CurrentThread.ManagedThreadId);
            Console.WriteLine("Main Thread is waiting for 15 seconds, observe 3 thread behaviour. All threads run once and stopped. Why? Because they call WaitOne() internally. They will wait until signals arrive, down below.");
            Thread.Sleep(15000);
            Console.WriteLine("1- Main will call AutoResetEvent.Set() in 5 seconds, watch out!");
            Thread.Sleep(5000);
            _autoReset.Set();
            Thread.Sleep(2000);
            Console.WriteLine("2- Main will call AutoResetEvent.Set() in 5 seconds, watch out!");
            Thread.Sleep(5000);
            _autoReset.Set();
            Thread.Sleep(2000);
            Console.WriteLine("3- Main will call AutoResetEvent.Set() in 5 seconds, watch out!");
            Thread.Sleep(5000);
            _autoReset.Set();
            Thread.Sleep(2000);
            Console.WriteLine("4- Main will call AutoResetEvent.Reset() in 5 seconds, watch out!");
            Thread.Sleep(5000);
            _autoReset.Reset();
            Thread.Sleep(2000);
            Console.WriteLine("Nothing happened. Why? Becasuse Reset Sets the state of the event to nonsignaled, causing threads to block. Since they are already blocked, it will not affect anything.");
            Thread.Sleep(10000);
            Console.WriteLine("This will go so on. Everytime you call Set(), AutoResetEvent will let another thread to run. It will make it automatically, so you do not need to worry about thread running order, unless you want it manually!");
            Thread.Sleep(5000);
            Console.WriteLine("Main thread reached to end! ThreadId: {0}", Thread.CurrentThread.ManagedThreadId);

        }

        public void Worker1()
        {
            for (int i = 1; i <= 5; i++)
            {
                Console.WriteLine("Worker1 is running {0}/5. ThreadId: {1}.", i, Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(500);
                // this gets blocked until _autoReset gets signal
                _autoReset.WaitOne();
            }
            Console.WriteLine("Worker1 is DONE. ThreadId: {0}", Thread.CurrentThread.ManagedThreadId);
        }
        public void Worker2()
        {
            for (int i = 1; i <= 5; i++)
            {
                Console.WriteLine("Worker2 is running {0}/5. ThreadId: {1}.", i, Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(500);
                // this gets blocked until _autoReset gets signal
                _autoReset.WaitOne();
            }
            Console.WriteLine("Worker2 is DONE. ThreadId: {0}", Thread.CurrentThread.ManagedThreadId);
        }
        public void Worker3()
        {
            for (int i = 1; i <= 5; i++)
            {
                Console.WriteLine("Worker3 is running {0}/5. ThreadId: {1}.", i, Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(500);
                // this gets blocked until _autoReset gets signal
                _autoReset.WaitOne();
            }
            Console.WriteLine("Worker3 is DONE. ThreadId: {0}", Thread.CurrentThread.ManagedThreadId);
        }
    }

}

Auto Reset Event Output

What event handler to use for ComboBox Item Selected (Selected Item not necessarily changed)

This is a DependencyObject for attaching to a ComboBox.

It records the currently selected item when the dropdown is opened, and then fires SelectionChanged event if the same index is still selected when the dropdown is closed. It may need to be modified for it to work with Keyboard selection.

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Web.UI.WebControls;

namespace MyNamespace 
{
    public class ComboAlwaysFireSelection : DependencyObject
    {
        public static readonly DependencyProperty ActiveProperty = DependencyProperty.RegisterAttached(
            "Active",
            typeof(bool),
            typeof(ComboAlwaysFireSelection),
            new PropertyMetadata(false, ActivePropertyChanged));

        private static void ActivePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var element = d as ComboBox;
            if (element == null) 
                return;

            if ((e.NewValue as bool?).GetValueOrDefault(false))
            {
                element.DropDownClosed += ElementOnDropDownClosed;
                element.DropDownOpened += ElementOnDropDownOpened;
            }
            else
            {
                element.DropDownClosed -= ElementOnDropDownClosed;
                element.DropDownOpened -= ElementOnDropDownOpened;
            }
        }

        private static void ElementOnDropDownOpened(object sender, EventArgs eventArgs)
        {
            _selectedIndex = ((ComboBox) sender).SelectedIndex;
        }

        private static int _selectedIndex;

        private static void ElementOnDropDownClosed(object sender, EventArgs eventArgs)
        {
            var comboBox = ((ComboBox) sender);
            if (comboBox.SelectedIndex == _selectedIndex)
            {
                comboBox.RaiseEvent(new SelectionChangedEventArgs(Selector.SelectionChangedEvent, new ListItemCollection(), new ListItemCollection()));
            }
        }

        [AttachedPropertyBrowsableForChildrenAttribute(IncludeDescendants = false)]
        [AttachedPropertyBrowsableForType(typeof(ComboBox))]
        public static bool GetActive(DependencyObject @object)
        {
            return (bool)@object.GetValue(ActiveProperty);
        }

        public static void SetActive(DependencyObject @object, bool value)
        {
            @object.SetValue(ActiveProperty, value);
        }
    }
}

and add your namespace prefix to make it accessible.

<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:ut="clr-namespace:MyNamespace" ></UserControl>

and then you need to attach it like so

<ComboBox ut:ComboAlwaysFireSelection.Active="True" />

How to use z-index in svg elements?

Using D3:

If you want to add the element in the reverse order to the data use:

.insert('g', ":first-child")

Instead of .append

Adding an element to top of a group element

Checking if an Android application is running in the background

You can use ComponentCallbacks2 to detect if the app is in background. BTW this callback is only available in API Level 14 (Ice Cream Sandwich) and above.

You will get a call to the method:

public abstract void onTrimMemory (int level)

if the level is ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN then the app is in background.

You can implement this interface to an activity, service, etc.

public class MainActivity extends AppCompatActivity implements ComponentCallbacks2 {
   @Override
   public void onConfigurationChanged(final Configuration newConfig) {

   }

   @Override
   public void onLowMemory() {

   }

   @Override
   public void onTrimMemory(final int level) {
     if (level == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) {
        // app is in background
     }
   }
}

How to prevent form from submitting multiple times from client side?

Use unobtrusive javascript to disable the submit event on the form after it has already been submitted. Here is an example using jQuery.

EDIT: Fixed issue with submitting a form without clicking the submit button. Thanks, ichiban.

$("body").on("submit", "form", function() {
    $(this).submit(function() {
        return false;
    });
    return true;
});

jQuery.ajax returns 400 Bad Request

Late answer, but I figured it's worth keeping this updated. Expanding on Andrea Turri answer to reflect updated jQuery API and .success/.error deprecated methods.

As of jQuery 1.8.* the preferred way of doing this is to use .done() and .fail(). Jquery Docs

e.g.

$('#my_get_related_keywords').click(function() {

    var ajaxRequest = $.ajax({
        type: "POST",
        url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE",
        data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}',
        contentType: "application/json; charset=utf-8",
        dataType: "json"});

    //When the request successfully finished, execute passed in function
    ajaxRequest.done(function(msg){
           //do something
    });

    //When the request failed, execute the passed in function
    ajaxRequest.fail(function(jqXHR, status){
        //do something else
    });
});

Django - after login, redirect user to his custom page --> mysite.com/username

Got into django recently and been looking into a solution to that and found a method that might be useful.

So for example, if using allouth the default redirect is accounts/profile. Make a view that solely redirects to a location of choice using the username field like so:

def profile(request):
    name=request.user.username
    return redirect('-----choose where-----' + name + '/')

Then create a view that captures it in one of your apps, for example:

def profile(request, name):
    user = get_object_or_404(User, username=name)
    return render(request, 'myproject/user.html', {'profile': user})

Where the urlpatterns capture would look like this:

url(r'^(?P<name>.+)/$', views.profile, name='user')

Works well for me.

Calculating sum of repeated elements in AngularJS ng-repeat

In html

<b class="text-primary">Total Amount: ${{ data.allTicketsTotalPrice() }}</b>

in javascript

  app.controller('myController', function ($http) {
            var vm = this;          
            vm.allTicketsTotalPrice = function () {
                var totalPrice = 0;
                angular.forEach(vm.ticketTotalPrice, function (value, key) {
                    totalPrice += parseFloat(value);
                });
                return totalPrice.toFixed(2);
            };
        });

How do I update the password for Git?

Following steps can resolve the issue .....

  1. Go to the folder ~/Library/Application Support/SourceTree
  2. Delete the file {Username}@STAuth-bitbucket.org
  3. Restart Sourcetree
  4. Try to fetch, password filed appear, give your new password
  5. Also can run "git fetch" command in terminal and need to type password
  6. Done

Replace new lines with a comma delimiter with Notepad++?

Open the find and replace dialog (press CTRL+H).

Then select Regular expression in the 'Search Mode' section at the bottom.

In the Find what field enter this: [\r\n]+

In the Replace with:

There is a space after the comma.

This will also replace lines like

Apples

Apricots
Pear

Avocados
Bananas

Where there are empty lines.

If your lines have trailing blank spaces you should remove those first. The simplest way to achieve this is

EDIT -> Blank Operations -> Trim Trailing Space

OR

TextFX -> TextFX Edit -> Trim trailing spaces

Be sure to set the Search Mode to "Regular expression".

What is the equivalent to getch() & getche() in Linux?

You can use the curses.h library in linux as mentioned in the other answer.

You can install it in Ubuntu by:

sudo apt-get update

sudo apt-get install ncurses-dev

I took the installation part from here.

What is the 'open' keyword in Swift?

Open is an access level, was introduced to impose limitations on class inheritance on Swift.

This means that the open access level can only be applied to classes and class members.

In Classes

An open class can be subclassed in the module it is defined in and in modules that import the module in which the class is defined.

In Class members

The same applies to class members. An open method can be overridden by subclasses in the module it is defined in and in modules that import the module in which the method is defined.

THE NEED FOR THIS UPDATE

Some classes of libraries and frameworks are not designed to be subclassed and doing so may result in unexpected behavior. Native Apple library also won't allow overriding the same methods and classes,

So after this addition they will apply public and private access levels accordingly.

For more details have look at Apple Documentation on Access Control

I get conflicting provisioning settings error when I try to archive to submit an iOS app

If you are from Ionic world. You might get a "conflict code signing" error when you in the "archive" stage, as below:

... is automatically signed for development, but a conflicting code signing identity iPhone Distribution has been manually specified. Set the code signing identity value to "iPhone Developer" in the build settings editor, or switch to manual signing in the project editor. Code signing is required for product type 'Application' in SDK 'iOS 10.x'

In this case, please go to Build Settings/under signing, code signing identity, and select both as iOS Developer, not Distribution.

Go to the menu: Product/Archive again, then the issue will be fixed.

Script for rebuilding and reindexing the fragmented index?

To rebuild use:

ALTER INDEX __NAME_OF_INDEX__ ON __NAME_OF_TABLE__ REBUILD

or to reorganize use:

ALTER INDEX __NAME_OF_INDEX__ ON __NAME_OF_TABLE__ REORGANIZE

Reorganizing should be used at lower (<30%) fragmentations but only rebuilding (which is heavier to the database) cuts the fragmentation down to 0%.
For further information see https://msdn.microsoft.com/en-us/library/ms189858.aspx

Can anyone explain python's relative imports?

Checking it out in python3:

python -V
Python 3.6.5

Example1:

.
+-- parent.py
+-- start.py
+-- sub
    +-- relative.py

- start.py
import sub.relative

- parent.py
print('Hello from parent.py')

- sub/relative.py
from .. import parent

If we run it like this(just to make sure PYTHONPATH is empty):

PYTHONPATH='' python3 start.py

Output:

Traceback (most recent call last):
  File "start.py", line 1, in <module>
    import sub.relative
  File "/python-import-examples/so-example-v1/sub/relative.py", line 1, in <module>
    from .. import parent
ValueError: attempted relative import beyond top-level package

If we change import in sub/relative.py

- sub/relative.py
import parent

If we run it like this:

PYTHONPATH='' python3 start.py

Output:

Hello from parent.py

Example2:

.
+-- parent.py
+-- sub
    +-- relative.py
    +-- start.py

- parent.py
print('Hello from parent.py')

- sub/relative.py
print('Hello from relative.py')

- sub/start.py
import relative
from .. import parent

Run it like:

PYTHONPATH='' python3 sub/start.py

Output:

Hello from relative.py
Traceback (most recent call last):
  File "sub/start.py", line 2, in <module>
    from .. import parent
ValueError: attempted relative import beyond top-level package

If we change import in sub/start.py:

- sub/start.py
import relative
import parent

Run it like:

PYTHONPATH='' python3 sub/start.py

Output:

Hello from relative.py
Traceback (most recent call last):
  File "sub/start.py", line 3, in <module>
    import parent
ModuleNotFoundError: No module named 'parent'

Run it like:

PYTHONPATH='.' python3 sub/start.py

Output:

Hello from relative.py
Hello from parent.py

Also it's better to use import from root folder, i.e.:

- sub/start.py
import sub.relative
import parent

Run it like:

PYTHONPATH='.' python3 sub/start.py

Output:

Hello from relative.py
Hello from parent.py

powershell - extract file name and extension

just do it:

$file=Get-Item "C:\temp\file.htm"
$file.Basename 
$file.Extension

How do I copy directories recursively with gulp?

Turns out that to copy a complete directory structure gulp needs to be provided with a base for your gulp.src() method.

So gulp.src( [ files ], { "base" : "." }) can be used in the structure above to copy all the directories recursively.

If, like me, you may forget this then try:

gulp.copy=function(src,dest){
    return gulp.src(src, {base:"."})
        .pipe(gulp.dest(dest));
};

Loop in react-native

renderItem(item)
  {
    const width = '80%';
    var items = [];

    for(let i = 0; i < item.count; i++){

        items.push( <View style={{ padding: 10, borderBottomColor: "#f2f2f2", borderBottomWidth: 10, flexDirection: 'row' }}>
    <View style={{ width }}>
      <Text style={styles.name}>{item.title}</Text>
      <Text style={{ color: '#818181', paddingVertical: 10 }}>{item.taskDataElements[0].description + " "}</Text>
      <Text style={styles.begin}>BEGIN</Text>
    </View>

    <Text style={{ backgroundColor: '#fcefec', padding: 10, color: 'red', height: 40 }}>{this.msToTime(item.minTatTimestamp) <= 0 ? "NOW" : this.msToTime(item.minTatTimestamp) + "hrs"}</Text>
  </View> )
  }

  return items;
}

render() {
return (this.renderItem(this.props.item)) 
}

Cannot start MongoDB as a service

For version 2.6 at least, you must create the /data/db/ and /log/ folders that the mongo.cfg points to. MongoDB won't do so itself, and will throw that error in response when ran as a service.

How to load html string in a webview?

read from assets html file

ViewGroup webGroup;
  String content = readContent("content/ganji.html");

        final WebView webView = new WebView(this);
        webView.loadDataWithBaseURL(null, content, "text/html", "UTF-8", null);

        webGroup.addView(webView);

How can I see CakePHP's SQL dump in the controller?

In CakePHP 1.2 ..

$db =& ConnectionManager::getDataSource('default');
$db->showLog();

concatenate variables

set ROOT=c:\programs 
set SRC_ROOT=%ROOT%\System\Source

TypeError: string indices must be integers, not str // working with dict

time1 is the key of the most outer dictionary, eg, feb2012. So then you're trying to index the string, but you can only do this with integers. I think what you wanted was:

for info in courses[time1][course]:

As you're going through each dictionary, you must add another nest.

How to correct TypeError: Unicode-objects must be encoded before hashing?

encoding this line fixed it for me.

m.update(line.encode('utf-8'))

PHP - iterate on string characters

// Unicode Codepoint Escape Syntax in PHP 7.0
$str = "cat!\u{1F431}";

// IIFE (Immediately Invoked Function Expression) in PHP 7.0
$gen = (function(string $str) {
    for ($i = 0, $len = mb_strlen($str); $i < $len; ++$i) {
        yield mb_substr($str, $i, 1);
    }
})($str);

var_dump(
    true === $gen instanceof Traversable,
    // PHP 7.1
    true === is_iterable($gen)
);

foreach ($gen as $char) {
    echo $char, PHP_EOL;
}

How to align checkboxes and their labels consistently cross-browsers

The only perfectly working solution for me is:

input[type=checkbox], input[type=radio] {
    vertical-align: -2px;
    margin: 0;
    padding: 0;
}

Tested today in Chrome, Firefox, Opera, IE 7 and 8. Example: Fiddle

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

Don't use with Router.

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

It works well.

python pandas: apply a function with arguments to a series

You can pass any number of arguments to the function that apply is calling through either unnamed arguments, passed as a tuple to the args parameter, or through other keyword arguments internally captured as a dictionary by the kwds parameter.

For instance, let's build a function that returns True for values between 3 and 6, and False otherwise.

s = pd.Series(np.random.randint(0,10, 10))
s

0    5
1    3
2    1
3    1
4    6
5    0
6    3
7    4
8    9
9    6
dtype: int64

s.apply(lambda x: x >= 3 and x <= 6)

0     True
1     True
2    False
3    False
4     True
5    False
6     True
7     True
8    False
9     True
dtype: bool

This anonymous function isn't very flexible. Let's create a normal function with two arguments to control the min and max values we want in our Series.

def between(x, low, high):
    return x >= low and x =< high

We can replicate the output of the first function by passing unnamed arguments to args:

s.apply(between, args=(3,6))

Or we can use the named arguments

s.apply(between, low=3, high=6)

Or even a combination of both

s.apply(between, args=(3,), high=6)

Variable is accessed within inner class. Needs to be declared final

Here's a funny answer.

You can declare a final one-element array and change the elements of the array all you want apparently. I'm sure it breaks the very reason why this compiler rule was implemented in the first place but it's handy when you're in a time-bind as I was today.

I actually can't claim credit for this one. It was IntelliJ's recommendation! Feels a bit hacky. But doesn't seem as bad as a global variable so I thought it worth mentioning here. It's just one solution to the problem. Not necessarily the best one.

final int[] tapCount = {0};

addSiteButton.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
       tapCount[0]++;
    }

});

Apache Tomcat Not Showing in Eclipse Server Runtime Environments

Scenario 1: You had Eclipse showing server and now after removing the particular version you want to configure at Eclipse a new local server instance. But you can not move further.

This happens due to reason Eclipse still looks for configured version of Tomcat directory, which directory is no longer there.

There is no need till LUNA to make fresh installation!

All we need is to REPLACE the new server run time environment into eclipse after removing old one, which is non-existent. Eclipse will

enter image description here

Simple way to copy or clone a DataRow?

But to make sure that your new row is accessible in the new table, you need to close the table:

DataTable destination = new DataTable(source.TableName);
destination = source.Clone();
DataRow sourceRow = source.Rows[0];
destination.ImportRow(sourceRow);

How can I generate UUID in C#

I have a GitHub Gist with a Java like UUID implementation in C#: https://gist.github.com/rickbeerendonk/13655dd24ec574954366

The UUID can be created from the least and most significant bits, just like in Java. It also exposes them. The implementation has an explicit conversion to a GUID and an implicit conversion from a GUID.

Code signing is required for product type Unit Test Bundle in SDK iOS 8.0

In my case the problem that I faced was:

CodeSign error: code signing is required for product type 'Unit Test Bundle' in SDK 'iOS 8.4'

Fortunatelly, the target did not implemented anything, so a quick solution is remove it.

enter image description here

how to stop a running script in Matlab

Matlab help says this- For M-files that run a long time, or that call built-ins or MEX-files that run a long time, Ctrl+C does not always effectively stop execution. Typically, this happens on Microsoft Windows platforms rather than UNIX[1] platforms. If you experience this problem, you can help MATLAB break execution by including a drawnow, pause, or getframe function in your M-file, for example, within a large loop. Note that Ctrl+C might be less responsive if you started MATLAB with the -nodesktop option.

So I don't think any option exist. This happens with many matlab functions that are complex. Either we have to wait or don't use them!.

Split string on whitespace in Python

Using split() will be the most Pythonic way of splitting on a string.

It's also useful to remember that if you use split() on a string that does not have a whitespace then that string will be returned to you in a list.

Example:

>>> "ark".split()
['ark']

Reload content in modal (twitter bootstrap)

step 1 : Create a wrapper for the modal called clone-modal-wrapper.

step 2 : Create a blank div called modal-wrapper.

Step 3 : Copy the modal element from clone-modal-wrapper to modal-wrapper.

step 4 : Toggle the modal of modal-wrapper.

<a data-toggle="modal" class='my-modal'>Open modal</a>

<div class="clone-modal-wrapper">
   <div class='my-modal' class="modal fade">
      <div class="modal-dialog">
         <div class="modal-content">
            <div class="modal-header">
               <a class="close" data-dismiss="modal">×</a>
               <h3>Header</h3>
            </div>
            <div class="modal-body"></div>
            <div class="modal-footer">
               <input type="submit" class="btn btn-success" value="Save"/>
            </div>
         </div>
      </div>
   </div>
</div>

<div class="modal-wrapper"></div>


$("a[data-target=#myModal]").click(function (e) {
    e.preventDefault();
    $(".modal-wrapper").html($(".clone-modal-wrapper").html());
    $('.modal-wrapper').find('.my-modal').modal('toggle');
});

What is stdClass in PHP?

Please bear in mind that 2 empty stdClasses are not strictly equal. This is very important when writing mockery expectations.

php > $a = new stdClass();
php > $b = new stdClass();
php > var_dump($a === $b);
bool(false)
php > var_dump($a == $b);
bool(true)
php > var_dump($a);
object(stdClass)#1 (0) {
}
php > var_dump($b);
object(stdClass)#2 (0) {
}
php >

How to concatenate strings in django templates?

Use with:

{% with "shop/"|add:shop_name|add:"/base.html" as template %}
{% include template %}
{% endwith %}

Hide strange unwanted Xcode logs

Building on the original tweet from @rustyshelf, and illustrated answer from iDevzilla, here's a solution that silences the noise from the simulator without disabling NSLog output from the device.

  1. Under Product > Scheme > Edit Scheme... > Run (Debug), set the OS_ACTIVITY_MODE environment variable to ${DEBUG_ACTIVITY_MODE} so it looks like this:

enter image description here

  1. Go to your project build settings, and click + to add a User-Defined Setting named DEBUG_ACTIVITY_MODE. Expand this setting and Click the + next to Debug to add a platform-specific value. Select the dropdown and change it to "Any iOS Simulator". Then set its value to "disable" so it looks like this:

enter image description here

How to add image to canvas

here is the sample code to draw image on canvas-

$("#selectedImage").change(function(e) {

var URL = window.URL;
var url = URL.createObjectURL(e.target.files[0]);
img.src = url;

img.onload = function() {
    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");        

    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(img, 0, 0, 500, 500);
}});

In the above code selectedImage is an input control which can be used to browse image on system. For more details of sample code to draw image on canvas while maintaining the aspect ratio:

http://newapputil.blogspot.in/2016/09/show-image-on-canvas-html5.html

Should you commit .gitignore into the Git repos?

You typically do commit .gitignore. In fact, I personally go as far as making sure my index is always clean when I'm not working on something. (git status should show nothing.)

There are cases where you want to ignore stuff that really isn't project specific. For example, your text editor may create automatic *~ backup files, or another example would be the .DS_Store files created by OS X.

I'd say, if others are complaining about those rules cluttering up your .gitignore, leave them out and instead put them in a global excludes file.

By default this file resides in $XDG_CONFIG_HOME/git/ignore (defaults to ~/.config/git/ignore), but this location can be changed by setting the core.excludesfile option. For example:

git config --global core.excludesfile ~/.gitignore

Simply create and edit the global excludesfile to your heart's content; it'll apply to every git repository you work on on that machine.

Reset input value in angular 2

Use @ViewChild to reset your control.

Template:

<input mdInput placeholder="Name" #filterName name="filterName" >

In Code:

@ViewChild('filterName') redel:ElementRef;

then you can access your control as

this.redel= "";

Difference between Key, Primary Key, Unique Key and Index in MySQL

Primary key does not allow NULL values, but unique key allows NULL values.

We can declare only one primary key in a table, but a table can have multiple unique keys (column assign).

Read file line by line in PowerShell

Not much documentation on PowerShell loops.

Documentation on loops in PowerShell is plentiful, and you might want to check out the following help topics: about_For, about_ForEach, about_Do, about_While.

foreach($line in Get-Content .\file.txt) {
    if($line -match $regex){
        # Work here
    }
}

Another idiomatic PowerShell solution to your problem is to pipe the lines of the text file to the ForEach-Object cmdlet:

Get-Content .\file.txt | ForEach-Object {
    if($_ -match $regex){
        # Work here
    }
}

Instead of regex matching inside the loop, you could pipe the lines through Where-Object to filter just those you're interested in:

Get-Content .\file.txt | Where-Object {$_ -match $regex} | ForEach-Object {
    # Work here
}

Differences in boolean operators: & vs && and | vs ||

The operators && and || are short-circuiting, meaning they will not evaluate their right-hand expression if the value of the left-hand expression is enough to determine the result.

transparent navigation bar ios

Swift 3 : extension for Transparent Navigation Bar

extension UINavigationBar {
    func transparentNavigationBar() {
    self.setBackgroundImage(UIImage(), for: .default)
    self.shadowImage = UIImage()
    self.isTranslucent = true
    }
}

Difference between jar and war in Java

A .war file has a specific structure in terms of where certain files will be. Other than that, yes, it's just a .jar.

How to reset db in Django? I get a command 'reset' not found error

reset has been replaced by flush with Django 1.5, see:

python manage.py help flush

How to replace all spaces in a string

Pure Javascript, without regular expression:

var result = replaceSpacesText.split(" ").join("");

Jenkins CI Pipeline Scripts not permitted to use method groovy.lang.GroovyObject

I ran into this when I reduced the number of user-input parameters in userInput from 3 to 1. This changed the variable output type of userInput from an array to a primitive.

Example:

myvar1 = userInput['param1']
myvar2 = userInput['param2']

to:

myvar = userInput

How to calculate the sum of all columns of a 2D numpy array (efficiently)

a.sum(0)

should solve the problem. It is a 2d np.array and you will get the sum of all column. axis=0 is the dimension that points downwards and axis=1 the one that points to the right.

How to compare two tables column by column in oracle

Used full outer join -- But it will not show - if its not matched -

SQL> desc aaa - its a table Name Null? Type


A1 NUMBER B1 VARCHAR2(10)

SQL> desc aaav -its a view Name Null? Type


A1 NUMBER B1 VARCHAR2(10)

SQL> select a.column_name,b.column_name from dba_tab_columns a full outer join dba_tab_columns b on a.column_name=b.column_name where a.TABLE_NAME='AAA' and B.table_name='AAAV';

COLUMN_NAME COLUMN_NAME


A1 A1 B1 B1

symfony2 : failed to write cache directory

You probably aborted a clearcache halfway and now you already have an app/cache/dev_old.

Try this (in the root of your project, assuming you're on a Unixy environment like OS X or Linux):

rm -rf app/cache/dev*

Check if a folder exist in a directory and create them using C#

    String path = Server.MapPath("~/MP_Upload/");
    if (!Directory.Exists(path))
    {
        Directory.CreateDirectory(path);
    }

What does git push -u mean?

When you push a new branch the first time use: >git push -u origin

After that, you can just type a shorter command: >git push

The first-time -u option created a persistent upstream tracking branch with your local branch.

Installing a dependency with Bower from URL and specify version

Just an update.

Now if it's a github repository then using just a github shorthand is enough if you do not mind the version of course.

GitHub shorthand

$ bower install desandro/masonry

How can I add (simple) tracing in C#?

DotNetCoders has a starter article on it: http://www.dotnetcoders.com/web/Articles/ShowArticle.aspx?article=50. They talk about how to set up the switches in the configuration file and how to write the code, but it is pretty old (2002).

There's another article on CodeProject: A Treatise on Using Debug and Trace classes, including Exception Handling, but it's the same age.

CodeGuru has another article on custom TraceListeners: Implementing a Custom TraceListener

How to initialize an array in one step using Ruby?

Along with the above answers , you can do this too

    =>  [*'1'.."5"]   #remember *
    => ["1", "2", "3", "4", "5"]

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

It can be very useful when flattening a hierarchy and/or mapping objects. Instead of:

if (Model.Model2 == null
  || Model.Model2.Model3 == null
  || Model.Model2.Model3.Model4 == null
  || Model.Model2.Model3.Model4.Name == null)
{
  mapped.Name = "N/A"
}
else
{
  mapped.Name = Model.Model2.Model3.Model4.Name;
}

It can be written like (same logic as above)

mapped.Name = Model.Model2?.Model3?.Model4?.Name ?? "N/A";

DotNetFiddle.Net Working Example.

(the ?? or null-coalescing operator is different than the ? or null conditional operator).

It can also be used out side of assignment operators with Action. Instead of

Action<TValue> myAction = null;

if (myAction != null)
{
  myAction(TValue);
}

It can be simplified to:

myAction?.Invoke(TValue);

DotNetFiddle Example:

using System;

public class Program
{
  public static void Main()
  {
    Action<string> consoleWrite = null;

    consoleWrite?.Invoke("Test 1");

    consoleWrite = (s) => Console.WriteLine(s);

    consoleWrite?.Invoke("Test 2");
  }
}

Result:

Test 2

Get key by value in dictionary

my_dict = {'A': 19, 'B': 28, 'carson': 28}
search_age = 28

take only one

name = next((name for name, age in my_dict.items() if age == search_age), None)
print(name)  # 'B'

get multiple data

name_list = [name for name, age in filter(lambda item: item[1] == search_age, my_dict.items())]
print(name_list)  # ['B', 'carson']

Set Encoding of File to UTF8 With BOM in Sublime Text 3

I can't set "UTF-8 with BOM" in the corner button either, but I can change it from the menu bar.

"File"->"Save with encoding"->"UTF-8 with BOM"

"Items collection must be empty before using ItemsSource."

Exception

Items collection must be empty before using ItemsSource.

This exception occurs when you add items to the ItemsSource through different sources. So Make sure you haven't accidentally missed a tag, misplaced a tag, added extra tags, or miswrote a tag.

<!--Right-->

<ItemsControl ItemsSource="{Binding MyItems}">
     <ItemsControl.ItemsPanel.../>
     <ItemsControl.MyAttachedProperty.../>
     <FrameworkElement.ActualWidth.../>
</ItemsControl>


<!--WRONG-->

<ItemsControl ItemsSource="{Binding MyItems}">
     <Grid.../>
     <Button.../>
     <DataTemplate.../>
     <Heigth.../>
</ItemsControl>

While ItemsControl.ItemsSource is already set through Binding, other items (Grid, Button, ...) can't be added to the source. However while ItemsSource is not in-use the following code is allowed:

<!--Right-->
<ItemsControl>
     <Button.../>
     <TextBlock.../>
     <sys:String.../>
</ItemsControl>

notice the missing ItemsSource="{Binding MyItems}" part.

Open source PDF library for C/C++ application?

jagpdf seems to be one of them. It is written in C++ but provides a C API.

How to create nonexistent subdirectories recursively using Bash?

You can use the -p parameter, which is documented as:

-p, --parents

no error if existing, make parent directories as needed

So:

mkdir -p "$BACKUP_DIR/$client/$year/$month/$day"

PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly?

I am not sure and not really trust $_SERVER['HTTP_HOST'] because it depend on header from client. In another way, if a domain requested by client is not mine one, they will not getting into my site because DNS and TCP/IP protocol point it to the correct destination. However I don't know if possible to hijack the DNS, network or even Apache server. To be safe, I define host name in environment and compare it with $_SERVER['HTTP_HOST'].

Add SetEnv MyHost domain.com in .htaccess file on root and add ths code in Common.php

if (getenv('MyHost')!=$_SERVER['HTTP_HOST']) {
  header($_SERVER['SERVER_PROTOCOL'].' 400 Bad Request');
  exit();
}

I include this Common.php file in every php page. This page doing anything required for each request like session_start(), modify session cookie and reject if post method come from different domain.

Relationship between hashCode and equals method in Java

A contract is: If two objects are equal then they should have the same hashcode and if two objects are not equal then they may or may not have same hash code.

Try using your object as key in HashMap (edited after comment from joachim-sauer), and you will start facing trouble. A contract is a guideline, not something forced upon you.

SQL time difference between two dates result in hh:mm:ss

The shortest code would be:

Select CAST((@EndDateTime-@StartDateTime) as time(0)) '[hh:mm:ss]'

How to handle static content in Spring MVC?

I used both ways that is urlrewrite and annotation based in spring mvc 3.0.x and found that annotation based approach is most suitable that is

<annotation-driven />

<resources mapping="/resources/**" location="/resources/" />

In case of urlrewrite,have to define lots of rule and some time also get class not found exception for UrlRewriteFilter as already provided the dependency for it. I found that it's happening due to the presence of transitive dependency, so again one step will increased and have to exclude that dependency from pom.xml using

<exclusion></exclusion> tags.

So annotation based approach will be the good deal.

Change span text?

Replace whatever is in the address bar with this:

javascript:document.getElementById('serverTime').innerHTML='[text here]';

Example.

Unix command to find lines common in two files

The command you are seeking is comm. eg:-

comm -12 1.sorted.txt 2.sorted.txt

Here:

-1 : suppress column 1 (lines unique to 1.sorted.txt)

-2 : suppress column 2 (lines unique to 2.sorted.txt)

Make <body> fill entire screen?

I think the largely correct way, is to set css to this:

html
{
    overflow: hidden;
}

body
{
    margin: 0;
    box-sizing: border-box;
}

html, body
{
    height: 100%;
}

How do you get assembler output from C/C++ source in gcc?

This will generate assembly code with the C code + line numbers interweaved, to more easily see which lines generate what code:

# create assembler code:
g++ -S -fverbose-asm -g -O2 test.cc -o test.s
# create asm interlaced with source lines:
as -alhnd test.s > test.lst

Found in Algorithms for programmers, page 3 (which is the overall 15th page of the PDF).

How do I center a window onscreen in C#?

In Windows Forms:

this.StartPosition = FormStartPosition.CenterScreen;

In WPF:

this.WindowStartupLocation = WindowStartupLocation.CenterScreen;

That's all you have to do...

get current date from [NSDate date] but set the time to 10:00 am

You can use this method for any minute / hour / period (aka am/pm) combination:

- (NSDate *)todayModifiedWithHours:(NSString *)hours
                           minutes:(NSString *)minutes
                         andPeriod:(NSString *)period
{
    NSDate *todayModified = NSDate.date;

    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

    NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSMinuteCalendarUnit fromDate:todayModified];

    [components setMinute:minutes.intValue];

    int hour = 0;

    if ([period.uppercaseString isEqualToString:@"AM"]) {

        if (hours.intValue == 12) {
            hour = 0;
        }
        else {
            hour = hours.intValue;
        }
    }
    else if ([period.uppercaseString isEqualToString:@"PM"]) {

        if (hours.intValue != 12) {
            hour = hours.intValue + 12;
        }
        else {
            hour = 12;
        }
    }
    [components setHour:hour];

    todayModified = [calendar dateFromComponents:components];

    return todayModified;
}

Requested Example:

NSDate *todayAt10AM = [self todayModifiedWithHours:@"10"
                                           minutes:@"00"
                                         andPeriod:@"am"];

What are the Ruby File.open modes and options?

In Ruby IO module documentation, I suppose.

Mode |  Meaning
-----+--------------------------------------------------------
"r"  |  Read-only, starts at beginning of file  (default mode).
-----+--------------------------------------------------------
"r+" |  Read-write, starts at beginning of file.
-----+--------------------------------------------------------
"w"  |  Write-only, truncates existing file
     |  to zero length or creates a new file for writing.
-----+--------------------------------------------------------
"w+" |  Read-write, truncates existing file to zero length
     |  or creates a new file for reading and writing.
-----+--------------------------------------------------------
"a"  |  Write-only, starts at end of file if file exists,
     |  otherwise creates a new file for writing.
-----+--------------------------------------------------------
"a+" |  Read-write, starts at end of file if file exists,
     |  otherwise creates a new file for reading and
     |  writing.
-----+--------------------------------------------------------
"b"  |  Binary file mode (may appear with
     |  any of the key letters listed above).
     |  Suppresses EOL <-> CRLF conversion on Windows. And
     |  sets external encoding to ASCII-8BIT unless explicitly
     |  specified.
-----+--------------------------------------------------------
"t"  |  Text file mode (may appear with
     |  any of the key letters listed above except "b").

Setting the Vim background colors

In a terminal emulator like konsole or gnome-terminal, you should to set a 256 color setting for vim.

:set  t_Co=256

After that you can to change your background.

What is the difference between Forking and Cloning on GitHub?

While @AniketThakur's answer is very good. No one has answered the following question yet.

Can I only send pull requests via GitHub if I've forked a project?

No. If you are a contributor to a repository, you can: Make a local clone. Make a local branch. Add commits to that branch. Push the local branch back to github (creating a remote branch in the process). Make a pull request requesting for that branch to be merged into the master branch (or whatever branch you like).

How to count the number of set bits in a 32-bit integer?

Here is the sample code, which might be useful.

private static final int[] bitCountArr = new int[]{0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8};
private static final int firstByteFF = 255;
public static final int getCountOfSetBits(int value){
    int count = 0;
    for(int i=0;i<4;i++){
        if(value == 0) break;
        count += bitCountArr[value & firstByteFF];
        value >>>= 8;
    }
    return count;
}

Connection refused on docker container

In Windows, you also normally need to run command line as administrator.

As standard-user:

docker build -t myimage -f Dockerfile .
Sending build context to Docker daemon  106.8MB
Step 1/1 : FROM mcr.microsoft.com/dotnet/core/runtime:3.0
Get https://mcr.microsoft.com/v2/: dial tcp: lookup mcr.microsoft.com on [::1]:53: read udp [::1]:45540->[::1]:53: read: 
>>>connection refused

But as an administrator.

docker build -t myimage -f Dockerfile .
Sending build context to Docker daemon  106.8MB
Step 1/1 : FROM mcr.microsoft.com/dotnet/core/runtime:3.0
3.0: Pulling from dotnet/core/runtime
68ced04f60ab: Pull complete                                                                                             e936bd534ffb: Pull complete                                                                                             caf64655bcbb: Pull complete                                                                                             d1927dbcbcab: Pull complete                                                                                             Digest: sha256:e0c67764f530a9cad29a09816614c0129af8fe3bd550eeb4e44cdaddf8f5aa40
Status: Downloaded newer image for mcr.microsoft.com/dotnet/core/runtime:3.0
 ---> f059cd71a22a
Successfully built f059cd71a22a
Successfully tagged myimage:latest

IF a cell contains a string

SEARCH does not return 0 if there is no match, it returns #VALUE!. So you have to wrap calls to SEARCH with IFERROR.

For example...

=IF(IFERROR(SEARCH("cat", A1), 0), "cat", "none")

or

=IF(IFERROR(SEARCH("cat",A1),0),"cat",IF(IFERROR(SEARCH("22",A1),0),"22","none"))

Here, IFERROR returns the value from SEARCH when it works; the given value of 0 otherwise.

Lost connection to MySQL server at 'reading initial communication packet', system error: 0

If bind-address is not present in your configuration file and mysql is hosted on AWS instance, please check your security group. In ideal conditions, the inbound rules should accept all connection from port 3306 and outbound rule should respond back to all valid IPs.

Place a button right aligned

To keep the button in the page flow:

<input type="button" value="Click Me" style="margin-left: auto; display: block;" />

(put that style in a .css file, do not use this html inline, for better maintenance)

Set focus on textbox in WPF

In Code behind you can achieve it only by doing this.

 private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            txtIndex.Focusable = true;
            txtIndex.Focus();
        }

Note: It wont work before window is loaded

How to exit an if clause

You can emulate goto's functionality with exceptions:

try:
    # blah, blah ...
    # raise MyFunkyException as soon as you want out
except MyFunkyException:
    pass

Disclaimer: I only mean to bring to your attention the possibility of doing things this way, while in no way do I endorse it as reasonable under normal circumstances. As I mentioned in a comment on the question, structuring code so as to avoid Byzantine conditionals in the first place is preferable by far. :-)

Regex - Does not contain certain Characters

^[^<>]+$

The caret in the character class ([^) means match anything but, so this means, beginning of string, then one or more of anything except < and >, then the end of the string.

Python read-only property

Here is a way to avoid the assumption that

all users are consenting adults, and thus are responsible for using things correctly themselves.

please see my update below

Using @property, is very verbose e.g.:

   class AClassWithManyAttributes:
        '''refactored to properties'''
        def __init__(a, b, c, d, e ...)
             self._a = a
             self._b = b
             self._c = c
             self.d = d
             self.e = e

        @property
        def a(self):
            return self._a
        @property
        def b(self):
            return self._b
        @property
        def c(self):
            return self._c
        # you get this ... it's long

Using

No underscore: it's a public variable.
One underscore: it's a protected variable.
Two underscores: it's a private variable.

Except the last one, it's a convention. You can still, if you really try hard, access variables with double underscore.

So what do we do? Do we give up on having read only properties in Python?

Behold! read_only_properties decorator to the rescue!

@read_only_properties('readonly', 'forbidden')
class MyClass(object):
    def __init__(self, a, b, c):
        self.readonly = a
        self.forbidden = b
        self.ok = c

m = MyClass(1, 2, 3)
m.ok = 4
# we can re-assign a value to m.ok
# read only access to m.readonly is OK 
print(m.ok, m.readonly) 
print("This worked...")
# this will explode, and raise AttributeError
m.forbidden = 4

You ask:

Where is read_only_properties coming from?

Glad you asked, here is the source for read_only_properties:

def read_only_properties(*attrs):

    def class_rebuilder(cls):
        "The class decorator"

        class NewClass(cls):
            "This is the overwritten class"
            def __setattr__(self, name, value):
                if name not in attrs:
                    pass
                elif name not in self.__dict__:
                    pass
                else:
                    raise AttributeError("Can't modify {}".format(name))

                super().__setattr__(name, value)
        return NewClass
    return class_rebuilder

update

I never expected this answer will get so much attention. Surprisingly it does. This encouraged me to create a package you can use.

$ pip install read-only-properties

in your python shell:

In [1]: from rop import read_only_properties

In [2]: @read_only_properties('a')
   ...: class Foo:
   ...:     def __init__(self, a, b):
   ...:         self.a = a
   ...:         self.b = b
   ...:         

In [3]: f=Foo('explodes', 'ok-to-overwrite')

In [4]: f.b = 5

In [5]: f.a = 'boom'
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-5-a5226072b3b4> in <module>()
----> 1 f.a = 'boom'

/home/oznt/.virtualenvs/tracker/lib/python3.5/site-packages/rop.py in __setattr__(self, name, value)
    116                     pass
    117                 else:
--> 118                     raise AttributeError("Can't touch {}".format(name))
    119 
    120                 super().__setattr__(name, value)

AttributeError: Can't touch a

How do I solve this error, "error while trying to deserialize parameter"

In my case; my WCF service function was using List<byte> Types parameter and i was getting this exception in the client side. Then i changed it to byte[] Types, updated service reference and problem is solved.

Permissions error when connecting to EC2 via SSH on Mac OSx

If you have a PPK file working on a PC, then export it as OpenSSH file using puttygen.exe for PC and use that on Mac (any Unix machine).

I was getting the same error --

debug1: Authentications that can continue: publickey,gssapi-with-mic
debug1: Next authentication method: publickey
debug1: Trying private key: ec2-keypair
debug1: read PEM private key done: type RSA
debug1: Authentications that can continue: publickey,gssapi-with-mic
debug1: No more authentication methods to try.
Permission denied (publickey,gssapi-with-mic)

As I was using a PPK file on Windows, I followed the steps as described above and Bingo!

$ ssh -i ec2-openssh-key root@ec2-instance-ip

How do I determine the current operating system with Node.js

var isWin64 = process.env.hasOwnProperty('ProgramFiles(x86)');

Python: How to create a unique file name?

You can use the datetime module

import datetime
uniq_filename = str(datetime.datetime.now().date()) + '_' + str(datetime.datetime.now().time()).replace(':', '.')

Note that: I am using replace since the colons are not allowed in filenames in many operating systems.

That's it, this will give you a unique filename every single time.

How do I copy an entire directory of files into an existing directory using Python?

A merge one inspired by atzz and Mital Vora:

#!/usr/bin/python
import os
import shutil
import stat
def copytree(src, dst, symlinks = False, ignore = None):
  if not os.path.exists(dst):
    os.makedirs(dst)
    shutil.copystat(src, dst)
  lst = os.listdir(src)
  if ignore:
    excl = ignore(src, lst)
    lst = [x for x in lst if x not in excl]
  for item in lst:
    s = os.path.join(src, item)
    d = os.path.join(dst, item)
    if symlinks and os.path.islink(s):
      if os.path.lexists(d):
        os.remove(d)
      os.symlink(os.readlink(s), d)
      try:
        st = os.lstat(s)
        mode = stat.S_IMODE(st.st_mode)
        os.lchmod(d, mode)
      except:
        pass # lchmod not available
    elif os.path.isdir(s):
      copytree(s, d, symlinks, ignore)
    else:
      shutil.copy2(s, d)
  • Same behavior as shutil.copytree, with symlinks and ignore parameters
  • Create directory destination structure if non existant
  • Will not fail if dst already exists

What is the curl error 52 "empty reply from server"?

In my case this was caused by a PHP APC problem. First place to look would be the Apache error logs (if you are using Apache).

Hope this helps somebody.

Android: How to Enable/Disable Wifi or Internet Connection Programmatically

To Enable WiFi:

WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);

To Disable WiFi:

WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(false);

Note: To access with WiFi state, we have to add following permissions inside the AndroidManifest.xml file:

android.permission.ACCESS_WIFI_STATE
android.permission.UPDATE_DEVICE_STATS 
android.permission.CHANGE_WIFI_STATE

Splitting a Java String by the pipe symbol using split("|")

Use proper escaping: string.split("\\|")

Or, in Java 5+, use the helper Pattern.quote() which has been created for exactly this purpose:

string.split(Pattern.quote("|"))

which works with arbitrary input strings. Very useful when you need to quote / escape user input.

"RuntimeError: Make sure the Graphviz executables are on your system's path" after installing Graphviz 2.38

On Ubuntu Linux this solved it for me:

pip install graphviz
sudo apt-get install graphviz

You could also try conda install -c conda-forge graphviz instead of pip if using Anaconda.

Type.GetType("namespace.a.b.ClassName") returns null

if your class is not in current assambly you must give qualifiedName and this code shows how to get qualifiedname of class

string qualifiedName = typeof(YourClass).AssemblyQualifiedName;

and then you can get type with qualifiedName

Type elementType = Type.GetType(qualifiedName);

asp.net mvc @Html.CheckBoxFor

If only one checkbox should be checked in the same time use RadioButtonFor instead:

      @Html.RadioButtonFor(model => model.Type,1, new { @checked = "checked" }) fultime
      @Html.RadioButtonFor(model => model.Type,2) party
      @Html.RadioButtonFor(model => model.Type,3) next option...

If one more one could be checked in the same time use excellent extension: CheckBoxListFor:

Hope,it will help

Get a file name from a path

The simplest solution is to use something like boost::filesystem. If for some reason this isn't an option...

Doing this correctly will require some system dependent code: under Windows, either '\\' or '/' can be a path separator; under Unix, only '/' works, and under other systems, who knows. The obvious solution would be something like:

std::string
basename( std::string const& pathname )
{
    return std::string( 
        std::find_if( pathname.rbegin(), pathname.rend(),
                      MatchPathSeparator() ).base(),
        pathname.end() );
}

, with MatchPathSeparator being defined in a system dependent header as either:

struct MatchPathSeparator
{
    bool operator()( char ch ) const
    {
        return ch == '/';
    }
};

for Unix, or:

struct MatchPathSeparator
{
    bool operator()( char ch ) const
    {
        return ch == '\\' || ch == '/';
    }
};

for Windows (or something still different for some other unknown system).

EDIT: I missed the fact that he also wanted to suppress the extention. For that, more of the same:

std::string
removeExtension( std::string const& filename )
{
    std::string::const_reverse_iterator
                        pivot
            = std::find( filename.rbegin(), filename.rend(), '.' );
    return pivot == filename.rend()
        ? filename
        : std::string( filename.begin(), pivot.base() - 1 );
}

The code is a little bit more complex, because in this case, the base of the reverse iterator is on the wrong side of where we want to cut. (Remember that the base of a reverse iterator is one behind the character the iterator points to.) And even this is a little dubious: I don't like the fact that it can return an empty string, for example. (If the only '.' is the first character of the filename, I'd argue that you should return the full filename. This would require a little bit of extra code to catch the special case.) }

an attempt was made to access a socket in a way forbbiden by its access permissions. why?

Most likely the socket is held by some process. Use netstat -o to find which one.

Left align and right align within div in Bootstrap

2021 Update...

Bootstrap 5 (beta)

For aligning within a flexbox div or row...

  • ml-auto is now ms-auto
  • mr-auto is now me-auto

Bootstrap 4+

  • pull-right is now float-right
  • text-right is the same as 3.x, and works for inline elements
  • both float-* and text-* are responsive for different alignment at different widths (ie: float-sm-right)

The flexbox utils (eg:justify-content-between) can also be used for alignment:

<div class="d-flex justify-content-between">
      <div>
         left
      </div>
      <div>
         right
      </div>
 </div>

or, auto-margins (eg:ml-auto) in any flexbox container (row,navbar,card,d-flex,etc...)

<div class="d-flex">
      <div>
         left
      </div>
      <div class="ml-auto">
         right
      </div>
 </div>

Bootstrap 4 Align Demo
Bootstrap 4 Right Align Examples(float, flexbox, text-right, etc...)


Bootstrap 3

Use the pull-right class..

<div class="container">
  <div class="row">
    <div class="col-md-6">Total cost</div>
    <div class="col-md-6"><span class="pull-right">$42</span></div>
  </div>
</div>

Bootstrap 3 Demo

You can also use the text-right class like this:

  <div class="row">
    <div class="col-md-6">Total cost</div>
    <div class="col-md-6 text-right">$42</div>
  </div>

Bootstrap 3 Demo 2

Difference between modes a, a+, w, w+, and r+ in built-in open function?

The opening modes are exactly the same as those for the C standard library function fopen().

The BSD fopen manpage defines them as follows:

 The argument mode points to a string beginning with one of the following
 sequences (Additional characters may follow these sequences.):

 ``r''   Open text file for reading.  The stream is positioned at the
         beginning of the file.

 ``r+''  Open for reading and writing.  The stream is positioned at the
         beginning of the file.

 ``w''   Truncate file to zero length or create text file for writing.
         The stream is positioned at the beginning of the file.

 ``w+''  Open for reading and writing.  The file is created if it does not
         exist, otherwise it is truncated.  The stream is positioned at
         the beginning of the file.

 ``a''   Open for writing.  The file is created if it does not exist.  The
         stream is positioned at the end of the file.  Subsequent writes
         to the file will always end up at the then current end of file,
         irrespective of any intervening fseek(3) or similar.

 ``a+''  Open for reading and writing.  The file is created if it does not
         exist.  The stream is positioned at the end of the file.  Subse-
         quent writes to the file will always end up at the then current
         end of file, irrespective of any intervening fseek(3) or similar.

Error during SSL Handshake with remote server

Faced the same problem as OP:

  • Tomcat returned response when accessing directly via SOAP UI
  • Didn't load html files
  • When used Apache properties mentioned by the previous answer, web-page appeared but AngularJS couldn't get HTTP response

Tomcat SSL certificate was expired while a browser showed it as secure - Apache certificate was far from expiration. Updating Tomcat KeyStore file solved the problem.

Delete duplicate elements from an array

Try following from Removing duplicates from an Array(simple):

Array.prototype.removeDuplicates = function (){
  var temp=new Array();
  this.sort();
  for(i=0;i<this.length;i++){
    if(this[i]==this[i+1]) {continue}
    temp[temp.length]=this[i];
  }
  return temp;
} 

Edit:

This code doesn't need sort:

Array.prototype.removeDuplicates = function (){
  var temp=new Array();
  label:for(i=0;i<this.length;i++){
        for(var j=0; j<temp.length;j++ ){//check duplicates
            if(temp[j]==this[i])//skip if already present 
               continue label;      
        }
        temp[temp.length] = this[i];
  }
  return temp;
 } 

(But not a tested code!)

How to prompt for user input and read command-line arguments

If it's a 3.x version then just simply use:

variantname = input()

For example, you want to input 8:

x = input()
8

x will equal 8 but it's going to be a string except if you define it otherwise.

So you can use the convert command, like:

a = int(x) * 1.1343
print(round(a, 2)) # '9.07'
9.07

Calling startActivity() from outside of an Activity context

Use this code in your Adapter_Activity and use context.startActivity(intent_Object) and intent_Object.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

Like this:

Intent n_act = new Intent(context, N_Activity.class);
n_act.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(n_act);

It Works....

How to get a path to the desktop for current user in C#?

// Environment.GetFolderPath
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); // Current User's Application Data
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); // All User's Application Data
Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles); // Program Files
Environment.GetFolderPath(Environment.SpecialFolder.Cookies); // Internet Cookie
Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // Logical Desktop
Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); // Physical Desktop
Environment.GetFolderPath(Environment.SpecialFolder.Favorites); // Favorites
Environment.GetFolderPath(Environment.SpecialFolder.History); // Internet History
Environment.GetFolderPath(Environment.SpecialFolder.InternetCache); // Internet Cache
Environment.GetFolderPath(Environment.SpecialFolder.MyComputer); // "My Computer" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // "My Documents" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyMusic); // "My Music" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); // "My Pictures" Folder
Environment.GetFolderPath(Environment.SpecialFolder.Personal); // "My Document" Folder
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); // Program files Folder
Environment.GetFolderPath(Environment.SpecialFolder.Programs); // Programs Folder
Environment.GetFolderPath(Environment.SpecialFolder.Recent); // Recent Folder
Environment.GetFolderPath(Environment.SpecialFolder.SendTo); // "Sent to" Folder
Environment.GetFolderPath(Environment.SpecialFolder.StartMenu); // Start Menu
Environment.GetFolderPath(Environment.SpecialFolder.Startup); // Startup
Environment.GetFolderPath(Environment.SpecialFolder.System); // System Folder
Environment.GetFolderPath(Environment.SpecialFolder.Templates); // Document Templates

Function to get yesterday's date in Javascript in format DD/MM/YYYY

You override $today in the if statement.

if($dd<10){$dd='0'+dd} if($mm<10){$mm='0'+$mm} $today = $dd+'/'+$mm+'/'+$yyyy;

It is then not a Date() object anymore - hence the error.

How do I clone a Django model instance object and save it to the database?

Just change the primary key of your object and run save().

obj = Foo.objects.get(pk=<some_existing_pk>)
obj.pk = None
obj.save()

If you want auto-generated key, set the new key to None.

More on UPDATE/INSERT here.

Official docs on copying model instances: https://docs.djangoproject.com/en/2.2/topics/db/queries/#copying-model-instances

Always show vertical scrollbar in <select>

I guess you cant, this maybe a limitation or not included in the IE browser. I have tried your jsfiddle with IE6-8 and all of it doesn't show the scrollbar and not sure with IE9. While in FF and chrome the scrollbar is shown. I also want to see how to do it in IE if possible.

If you really want to show the scrollbar, you can add a fake scrollbar. If you are familiar with some of the js library which use in RIA. Like in jquery/dojo some of the select is editable, because it is a combination of textbox + select or it can also be a textbox + div.

As an example, see it here a JavaScript that make select like editable.

How do you add input from user into list in Python

code below allows user to input items until they press enter key to stop:

In [1]: items=[]
   ...: i=0
   ...: while 1:
   ...:     i+=1
   ...:     item=input('Enter item %d: '%i)
   ...:     if item=='':
   ...:         break
   ...:     items.append(item)
   ...: print(items)
   ...: 

Enter item 1: apple

Enter item 2: pear

Enter item 3: #press enter here
['apple', 'pear']

In [2]: 

How to change the default message of the required field in the popover of form-control in bootstrap?

And for all input and select:

$("input[required], select[required]").attr("oninvalid", "this.setCustomValidity('Required!')");
$("input[required], select[required]").attr("oninput", "setCustomValidity('')");

WiX tricks and tips

Peter Tate has already shown how you can define reusable ComponentGroup definitions in separate wix fragments. Some additional tricks related to this:

Directory Aliasing

The component group fragments don't need to know about directories defined by the main product wxs. In your component group fragment you can talk about a folder like this:

<DirectoryRef Id="component1InstallFolder">
...
</DirectoryRef>

Then the main product can alias one of its directories (e.g. "productInstallFolder") like this:

<Directory Id="productInstallFolder" Name="ProductName">
   <!-- not subfolders (because no Name attribute) but aliases for parent! -->
   <Directory Id="component1InstallFolder"/> 
   <Directory Id="component2InstallFolder"/> 
</Directory>

Dependency Graph

ComponentGroup elements can contain ComponentGroupRef child elements. This is great if you have a big pool of reusable components with a complex dependency graph between them. You just set up a ComponentGroup in its own fragment for each component and declare the dependencies like this:

<ComponentGroup Id="B">
   <ComponentRef Id="_B" />
   <ComponentGroupRef Id="A">
</ComponentGroup>

If you now reference component group "B" in your setup because it is a direct dependency of your application, it will automatically pull in component group "A" even if the application author never realized that it was a dependency of "B". It "just works" as long as you don't have any circular dependencies.

Reusable wixlib

The above dependency graph idea works best if you compile the big-pool-o-reusable-components into a reusable wixlib with lit.exe. When creating an application setup, you can reference this wixlib much like a wixobj file. The candle.exe linker will automatically eliminate any fragments that are not "pulled in" by the main product wxs file(s).

How to read and write excel file

If you need to do anything more with office documents in Java, go for POI as mentioned.

For simple reading/writing an excel document like you requested, you can use the CSV format (also as mentioned):

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class CsvWriter {
 public static void main(String args[]) throws IOException {

  String fileName = "test.xls";

  PrintWriter out = new PrintWriter(new FileWriter(fileName));
  out.println("a,b,c,d");
  out.println("e,f,g,h");
  out.println("i,j,k,l");
  out.close();

  BufferedReader in = new BufferedReader(new FileReader(fileName));
  String line = null;
  while ((line = in.readLine()) != null) {

   Scanner scanner = new Scanner(line);
   String sep = "";
   while (scanner.hasNext()) {
    System.out.println(sep + scanner.next());
    sep = ",";
   }
  }
  in.close();
 }
}

How to get streaming url from online streaming radio station

not that hard,

if you take a look at the page source, you'll see that it uses to stream the audio via shoutcast.

this is the stream url

"StreamUrl": "http://stream.radiotime.com/listen.stream?streamIds=3244651&rti=c051HQVbfRc4FEMbKg5RRVMzRU9KUBw%2fVBZHS0dPF1VIExNzJz0CGQtRcX8OS0o0CUkYRFJDDW8LEVRxGAEOEAcQXko%2bGgwSBBZrV1pQZgQZZxkWCA4L%7e%7e%7e",

which returns a JSON like that:

{
    "Streams": [
        {
            "StreamId": 3244651,
            "Reliability": 92,
            "Bandwidth": 64,
            "HasPlaylist": false,
            "MediaType": "MP3",
            "Url": "http://mp3hdfm32.hala.jo:8132",
            "Type": "Live"
        }
    ]
}

i believe that's the url you need: http://mp3hdfm32.hala.jo:8132

this is the station WebSite

How to read a file from jar in Java?

If you want to read that file from inside your application use:

InputStream input = getClass().getResourceAsStream("/classpath/to/my/file");

The path starts with "/", but that is not the path in your file-system, but in your classpath. So if your file is at the classpath "org.xml" and is called myxml.xml your path looks like "/org/xml/myxml.xml".

The InputStream reads the content of your file. You can wrap it into an Reader, if you want.

I hope that helps.

angularjs to output plain text instead of html

You can use ng-bind-html, don't forget to inject $sanitize service into your module Hope it helps

How can I add "href" attribute to a link dynamically using JavaScript?

document.getElementById('link-id').href = "new-href";

I know this is an old post, but here's a one-liner that might be more suitable for some folks.

Making heatmap from pandas DataFrame

For people looking at this today, I would recommend the Seaborn heatmap() as documented here.

The example above would be done as follows:

import numpy as np 
from pandas import DataFrame
import seaborn as sns
%matplotlib inline

Index= ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
Cols = ['A', 'B', 'C', 'D']
df = DataFrame(abs(np.random.randn(5, 4)), index=Index, columns=Cols)

sns.heatmap(df, annot=True)

Where %matplotlib is an IPython magic function for those unfamiliar.

ReactJS: Warning: setState(...): Cannot update during an existing state transition

The problem is certainly the this binding while rending the button with onClick handler. The solution is to use arrow function while calling action handler while rendering. Like this: onClick={ () => this.handleButtonChange(false) }

Node.js: Difference between req.query[] and req.params

You should be able to access the query using dot notation now.

If you want to access say you are receiving a GET request at /checkEmail?type=email&utm_source=xxxx&email=xxxxx&utm_campaign=XX and you want to fetch out the query used.

var type = req.query.type,
    email = req.query.email,
    utm = {
     source: req.query.utm_source,
     campaign: req.query.utm_campaign
    };

Params are used for the self defined parameter for receiving request, something like (example):

router.get('/:userID/food/edit/:foodID', function(req, res){
 //sample GET request at '/xavg234/food/edit/jb3552'

 var userToFind = req.params.userID;//gets xavg234
 var foodToSearch = req.params.foodID;//gets jb3552
 User.findOne({'userid':userToFind}) //dummy code
     .then(function(user){...})
     .catch(function(err){console.log(err)});
});

Spring Data JPA findOne() change to Optional how to use this?

I always write a default method "findByIdOrError" in widely used CrudRepository repos/interfaces.

@Repository 
public interface RequestRepository extends CrudRepository<Request, Integer> {

    default Request findByIdOrError(Integer id) {
        return findById(id).orElseThrow(EntityNotFoundException::new);
    } 
}

Has anyone ever got a remote JMX JConsole to work?

Tried with Java 8 and newer versions

This solution works well also with firewalls

1. Add this to your java startup script on remote-host:

-Dcom.sun.management.jmxremote.port=1616
-Dcom.sun.management.jmxremote.rmi.port=1616
-Dcom.sun.management.jmxremote.ssl=false
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.local.only=false
-Djava.rmi.server.hostname=localhost

2. Execute this on your computer.

  • Windows users:

    putty.exe -ssh user@remote-host -L 1616:remote-host:1616

  • Linux and Mac Users:

    ssh user@remote-host -L 1616:remote-host:1616

3. Start jconsole on your computer

jconsole localhost:1616

4. Have fun!

P.S.: during step 2, using ssh and -L you specify that the port 1616 on the local (client) host must be forwarded to the remote side. This is an ssh tunnel and helps to avoids firewalls or various networks problems.

Maven Java EE Configuration Marker with Java Server Faces 1.2

You should check your project facets in the project configuration. This is where you may uncheck the JSF dependency.

enter image description here

How do I compare two string variables in an 'if' statement in Bash?

This question has already great answers, but here it appears that there is a slight confusion between using single equal (=) and double equals (==) in

if [ "$s1" == "$s2" ]

The main difference lies in which scripting language you are using. If you are using Bash then include #!/bin/bash in the starting of the script and save your script as filename.bash. To execute, use bash filename.bash - then you have to use ==.

If you are using sh then use #!/bin/sh and save your script as filename.sh. To execute use sh filename.sh - then you have to use single =. Avoid intermixing them.

does linux shell support list data structure?

It supports lists, but not as a separate data structure (ignoring arrays for the moment).

The for loop iterates over a list (in the generic sense) of white-space separated values, regardless of how that list is created, whether literally:

for i in 1 2 3; do
    echo "$i"
done

or via parameter expansion:

listVar="1 2 3"
for i in $listVar; do
    echo "$i"
done

or command substitution:

for i in $(echo 1; echo 2; echo 3); do
    echo "$i"
done

An array is just a special parameter which can contain a more structured list of value, where each element can itself contain whitespace. Compare the difference:

array=("item 1" "item 2" "item 3")
for i in "${array[@]}"; do   # The quotes are necessary here
    echo "$i"
done

list='"item 1" "item 2" "item 3"'
for i in $list; do
    echo $i
done
for i in "$list"; do
    echo $i
done
for i in ${array[@]}; do
    echo $i
done

Rerender view on browser resize with React

A very simple solution:

resize = () => this.forceUpdate()

componentDidMount() {
  window.addEventListener('resize', this.resize)
}

componentWillUnmount() {
  window.removeEventListener('resize', this.resize)
}

jump to line X in nano editor

In the nano editor

Ctrl+_

On openning a file

nano +10 file.txt

Export/import jobs in Jenkins

For those of us in the Windows world who may or may not have Bash available, here's my PowerShell port of Katu and Larry Cai's approach. Hope it helps someone.

##### Config vars #####
$serverUri = 'http://localhost:8080/' # URI of your Jenkins server
$jenkinsCli = 'C:\Program Files (x86)\Jenkins\war\WEB-INF\jenkins-cli.jar' # Path to jenkins-cli.jar on your machine
$destFolder = 'C:\Jenkins Backup\' # Output folder (will be created if it doesn't exist)
$destFile = 'jenkins-jobs.zip' # Output filename (will be overwritten if it exists)
########################

$work = Join-Path ([System.IO.Path]::GetTempPath()) ([System.IO.Path]::GetRandomFileName())
New-Item -ItemType Directory -Force -Path $work | Out-Null # Suppress output noise
echo "Created a temp working folder: $work"

$jobs = (java -jar $jenkinsCli -s $serverUri list-jobs)
echo "Found $($jobs.Length) existing jobs: [$jobs]"

foreach ($j in $jobs)
{
    $outfile = Join-Path $work "$j.xml"
    java -jar $jenkinsCli -s $serverUri get-job $j | Out-File $outfile
}
echo "Saved $($jobs.Length) jobs to temp XML files"

New-Item -ItemType Directory -Force -Path $destFolder | Out-Null # Suppress output noise
echo "Found (or created) $destFolder folder"

$destPath = Join-Path $destFolder $destFile
Get-ChildItem $work -Filter *.xml | 
    Write-Zip -Level 9 -OutputPath $destPath -FlattenPaths |
    Out-Null # Suppress output noise
echo "Copied $($jobs.Length) jobs to $destPath"

Remove-Item $work -Recurse -Force
echo "Removed temp working folder"

How to match all occurrences of a regex

To find all the matching strings, use String's scan method.

str = "A 54mpl3 string w1th 7 numb3rs scatter36 ar0und"
str.scan(/\d+/)
#=> ["54", "3", "1", "7", "3", "36", "0"]

If you want, MatchData, which is the type of the object returned by the Regexp match method, use:

str.to_enum(:scan, /\d+/).map { Regexp.last_match }
#=> [#<MatchData "54">, #<MatchData "3">, #<MatchData "1">, #<MatchData "7">, #<MatchData "3">, #<MatchData "36">, #<MatchData "0">]

The benefit of using MatchData is that you can use methods like offset:

match_datas = str.to_enum(:scan, /\d+/).map { Regexp.last_match }
match_datas[0].offset(0)
#=> [2, 4]
match_datas[1].offset(0)
#=> [7, 8]

See these questions if you'd like to know more:

Reading about special variables $&, $', $1, $2 in Ruby will be helpful too.

Can I run CUDA on Intel's integrated graphics processor?

If you're interested in learning a language which supports massive parallelism better go for OpenCL since you don't have an NVIDIA GPU. You can run OpenCL on Intel CPUs, but at best you can learn to program SIMDs. Optimization on CPU and GPU are different. I really don't think you can use Intel card for GPGPU.

Get Value of a Edit Text field

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

  Button  rtn = (Button)findViewById(R.id.button);
  EditText edit_text   = (EditText)findViewById(R.id.edittext1);

    rtn .setOnClickListener(
        new View.OnClickListener()
        {
            public void onClick(View view)
            {
                Log.v("EditText value=", edit_text.getText().toString());
            }
        });
}

How to use Elasticsearch with MongoDB?

This answer should be enough to get you set up to follow this tutorial on Building a functional search component with MongoDB, Elasticsearch, and AngularJS.

If you're looking to use faceted search with data from an API then Matthiasn's BirdWatch Repo is something you might want to look at.

So here's how you can setup a single node Elasticsearch "cluster" to index MongoDB for use in a NodeJS, Express app on a fresh EC2 Ubuntu 14.04 instance.

Make sure everything is up to date.

sudo apt-get update

Install NodeJS.

sudo apt-get install nodejs
sudo apt-get install npm

Install MongoDB - These steps are straight from MongoDB docs. Choose whatever version you're comfortable with. I'm sticking with v2.4.9 because it seems to be the most recent version MongoDB-River supports without issues.

Import the MongoDB public GPG Key.

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10

Update your sources list.

echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list

Get the 10gen package.

sudo apt-get install mongodb-10gen

Then pick your version if you don't want the most recent. If you are setting your environment up on a windows 7 or 8 machine stay away from v2.6 until they work some bugs out with running it as a service.

apt-get install mongodb-10gen=2.4.9

Prevent the version of your MongoDB installation being bumped up when you update.

echo "mongodb-10gen hold" | sudo dpkg --set-selections

Start the MongoDB service.

sudo service mongodb start

Your database files default to /var/lib/mongo and your log files to /var/log/mongo.

Create a database through the mongo shell and push some dummy data into it.

mongo YOUR_DATABASE_NAME
db.createCollection(YOUR_COLLECTION_NAME)
for (var i = 1; i <= 25; i++) db.YOUR_COLLECTION_NAME.insert( { x : i } )

Now to Convert the standalone MongoDB into a Replica Set.

First Shutdown the process.

mongo YOUR_DATABASE_NAME
use admin
db.shutdownServer()

Now we're running MongoDB as a service, so we don't pass in the "--replSet rs0" option in the command line argument when we restart the mongod process. Instead, we put it in the mongod.conf file.

vi /etc/mongod.conf

Add these lines, subbing for your db and log paths.

replSet=rs0
dbpath=YOUR_PATH_TO_DATA/DB
logpath=YOUR_PATH_TO_LOG/MONGO.LOG

Now open up the mongo shell again to initialize the replica set.

mongo DATABASE_NAME
config = { "_id" : "rs0", "members" : [ { "_id" : 0, "host" : "127.0.0.1:27017" } ] }
rs.initiate(config)
rs.slaveOk() // allows read operations to run on secondary members.

Now install Elasticsearch. I'm just following this helpful Gist.

Make sure Java is installed.

sudo apt-get install openjdk-7-jre-headless -y

Stick with v1.1.x for now until the Mongo-River plugin bug gets fixed in v1.2.1.

wget https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-1.1.1.deb
sudo dpkg -i elasticsearch-1.1.1.deb

curl -L http://github.com/elasticsearch/elasticsearch-servicewrapper/tarball/master | tar -xz
sudo mv *servicewrapper*/service /usr/local/share/elasticsearch/bin/
sudo rm -Rf *servicewrapper*
sudo /usr/local/share/elasticsearch/bin/service/elasticsearch install
sudo ln -s `readlink -f /usr/local/share/elasticsearch/bin/service/elasticsearch` /usr/local/bin/rcelasticsearch

Make sure /etc/elasticsearch/elasticsearch.yml has the following config options enabled if you're only developing on a single node for now:

cluster.name: "MY_CLUSTER_NAME"
node.local: true

Start the Elasticsearch service.

sudo service elasticsearch start

Verify it's working.

curl http://localhost:9200

If you see something like this then you're good.

{
  "status" : 200,
  "name" : "Chi Demon",
  "version" : {
    "number" : "1.1.2",
    "build_hash" : "e511f7b28b77c4d99175905fac65bffbf4c80cf7",
    "build_timestamp" : "2014-05-22T12:27:39Z",
    "build_snapshot" : false,
    "lucene_version" : "4.7"
  },
  "tagline" : "You Know, for Search"
}

Now install the Elasticsearch plugins so it can play with MongoDB.

bin/plugin --install com.github.richardwilly98.elasticsearch/elasticsearch-river-mongodb/1.6.0
bin/plugin --install elasticsearch/elasticsearch-mapper-attachments/1.6.0

These two plugins aren't necessary but they're good for testing queries and visualizing changes to your indexes.

bin/plugin --install mobz/elasticsearch-head
bin/plugin --install lukas-vlcek/bigdesk

Restart Elasticsearch.

sudo service elasticsearch restart

Finally index a collection from MongoDB.

curl -XPUT localhost:9200/_river/DATABASE_NAME/_meta -d '{
  "type": "mongodb",
  "mongodb": {
    "servers": [
      { "host": "127.0.0.1", "port": 27017 }
    ],
    "db": "DATABASE_NAME",
    "collection": "ACTUAL_COLLECTION_NAME",
    "options": { "secondary_read_preference": true },
    "gridfs": false
  },
  "index": {
    "name": "ARBITRARY INDEX NAME",
    "type": "ARBITRARY TYPE NAME"
  }
}'

Check that your index is in Elasticsearch

curl -XGET http://localhost:9200/_aliases

Check your cluster health.

curl -XGET 'http://localhost:9200/_cluster/health?pretty=true'

It's probably yellow with some unassigned shards. We have to tell Elasticsearch what we want to work with.

curl -XPUT 'localhost:9200/_settings' -d '{ "index" : { "number_of_replicas" : 0 } }'

Check cluster health again. It should be green now.

curl -XGET 'http://localhost:9200/_cluster/health?pretty=true'

Go play.

How to create friendly URL in php?

It's actually not PHP, it's apache using mod_rewrite. What happens is the person requests the link, www.example.com/profile/12345 and then apache chops it up using a rewrite rule making it look like this, www.example.com/profile.php?u=12345, to the server. You can find more here: Rewrite Guide

Bootstrap - floating navbar button right

In bootstrap 4 use:

<ul class="nav navbar-nav ml-auto">

This will push the navbar to the right. Use mr-auto to push it to the left, this is the default behaviour.

Is it a good practice to place C++ definitions in header files?

Often I'll put trivial member functions into the header file, to allow them to be inlined. But to put the entire body of code there, just to be consistent with templates? That's plain nuts.

Remember: A foolish consistency is the hobgoblin of little minds.

Can't create handler inside thread that has not called Looper.prepare()

You need to call Toast.makeText(...) from the UI thread:

activity.runOnUiThread(new Runnable() {
  public void run() {
    Toast.makeText(activity, "Hello", Toast.LENGTH_SHORT).show();
  }
});

This is copy-pasted from another (duplicate) SO answer.

What is the way of declaring an array in JavaScript?

The preferred way is to always use the literal syntax with square brackets; its behaviour is predictable for any number of items, unlike Array's. What's more, Array is not a keyword, and although it is not a realistic situation, someone could easily overwrite it:

function Array() { return []; }

alert(Array(1, 2, 3)); // An empty alert box

However, the larger issue is that of consistency. Someone refactoring code could come across this function:

function fetchValue(n) {
    var arr = new Array(1, 2, 3);

    return arr[n];
}

As it turns out, only fetchValue(0) is ever needed, so the programmer drops the other elements and breaks the code, because it now returns undefined:

var arr = new Array(1);

Android: Storing username and password?

With the new (Android 6.0) fingerprint hardware and API you can do it as in this github sample application.

How do you change library location in R?

I'm late to the party but I encountered the same thing when I tried to get fancy and move my library and then had files being saved to a folder that was outdated:

.libloc <<- "C:/Program Files/rest_of_your_Library_FileName"

One other point to mention is that for Windows Computers, if you copy the address from Windows Explorer, you have to manually change the '\' to a '/' for the directory to be recognized.

Preferred Java way to ping an HTTP URL for availability

here the writer suggests this:

public boolean isOnline() {
    Runtime runtime = Runtime.getRuntime();
    try {
        Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
        int     exitValue = ipProcess.waitFor();
        return (exitValue == 0);
    } catch (IOException | InterruptedException e) { e.printStackTrace(); }
    return false;
}

Possible Questions

  • Is this really fast enough?Yes, very fast!
  • Couldn’t I just ping my own page, which I want to request anyways? Sure! You could even check both, if you want to differentiate between “internet connection available” and your own servers beeing reachable What if the DNS is down? Google DNS (e.g. 8.8.8.8) is the largest public DNS service in the world. As of 2013 it serves 130 billion requests a day. Let ‘s just say, your app not responding would probably not be the talk of the day.

read the link. its seems very good

EDIT: in my exp of using it, it's not as fast as this method:

public boolean isOnline() {
    NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
    return netInfo != null && netInfo.isConnectedOrConnecting();
}

they are a bit different but in the functionality for just checking the connection to internet the first method may become slow due to the connection variables.

How can I make IntelliJ IDEA update my dependencies from Maven?

Uncheck

"Work Offline"

in Settings -> Maven ! It worked for me ! :D

nodejs npm global config missing on windows

Have you tried running npm config list? And, if you want to see the defaults, run npm config ls -l.

How to know which version of Symfony I have?

Use the following command in your Terminal/Command Prompt:

php bin/console --version

This will give you your Symfony Version.

Git reset --hard and push to remote repository

If forcing a push doesn't help ("git push --force origin" or "git push --force origin master" should be enough), it might mean that the remote server is refusing non fast-forward pushes either via receive.denyNonFastForwards config variable (see git config manpage for description), or via update / pre-receive hook.

With older Git you can work around that restriction by deleting "git push origin :master" (see the ':' before branch name) and then re-creating "git push origin master" given branch.

If you can't change this, then the only solution would be instead of rewriting history to create a commit reverting changes in D-E-F:

A-B-C-D-E-F-[(D-E-F)^-1]   master

A-B-C-D-E-F                             origin/master

difference between @size(max = value ) and @min(value) @max(value)

@Min and @Max are used for validating numeric fields which could be String(representing number), int, short, byte etc and their respective primitive wrappers.

@Size is used to check the length constraints on the fields.

As per documentation @Size supports String, Collection, Map and arrays while @Min and @Max supports primitives and their wrappers. See the documentation.

How do I get the YouTube video ID from a URL?

Here's a radically different solution.

You could request the JSON oEmbed document from 'https://www.youtube.com/oembed?format=json&url=' . rawurlencode($url) and then thumbnail_url has a fixed format, match it with a PCRE pattern like https://i.ytimg.com/vi/([^/]+), the first group is the YouTube ID.

How to apply border radius in IE8 and below IE8 browsers?

The border-radius property is supported in IE9+, Firefox 4+, Chrome, Safari 5+, and Opera, because it is CSS3 property. so, you could use css3pie

first check this demo in IE 8 and download it from here write your css rule like this

 #myAwesomeElement {
    border: 1px solid #999;
    -webkit-border-radius: 10px;
    -moz-border-radius: 10px;
    border-radius: 10px;
    behavior: url(path/to/pie_files/PIE.htc);
}   

note: added behavior: url(path/to/pie_files/PIE.htc); in the above rule. within url() you need to specify your PIE.htc file location

Spring JPA selecting specific columns

It is possible to specify null as field value in native sql.

@Query(value = "select p.id, p.uid, p.title, null as documentation, p.ptype " +
            " from projects p " +
            "where p.uid = (:uid)" +
            "  and p.ptype = 'P'", nativeQuery = true)
Project findInfoByUid(@Param("uid") String uid);

Rails server says port already used, how to kill that process?

Using this command you can kill the server:

ps aux|grep rails 

iOS download and save image inside app

As other people said, there are many cases in which you should download a picture in the background thread without blocking the user interface

In this cases my favorite solution is to use a convenient method with blocks, like this one: (credit -> iOS: How To Download Images Asynchronously (And Make Your UITableView Scroll Fast))

- (void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, UIImage *image))completionBlock
{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                               if ( !error )
                               {
                                   UIImage *image = [[UIImage alloc] initWithData:data];
                                   completionBlock(YES,image);
                               } else{
                                   completionBlock(NO,nil);
                               }
                           }];
}

And call it like

NSURL *imageUrl = //...

[[MyUtilManager sharedInstance] downloadImageWithURL:[NSURL URLWithString:imageURL] completionBlock:^(BOOL succeeded, UIImage *image) {
    //Here you can save the image permanently, update UI and do what you want...
}];

What's the simplest way to print a Java array?

Always check the standard libraries first.

import java.util.Arrays;

Then try:

System.out.println(Arrays.toString(array));

or if your array contains other arrays as elements:

System.out.println(Arrays.deepToString(array));

How can I update the current line in a C# Windows Console App?

Here is my take on s soosh's and 0xA3's answers. It can update the console with user messages while updating the spinner and has an elapsed time indicator aswell.

public class ConsoleSpiner : IDisposable
{
    private static readonly string INDICATOR = "/-\\|";
    private static readonly string MASK = "\r{0} {1:c} {2}";
    int counter;
    Timer timer;
    string message;

    public ConsoleSpiner() {
        counter = 0;
        timer = new Timer(200);
        timer.Elapsed += TimerTick;
    }

    public void Start() {
        timer.Start();
    }

    public void Stop() {
        timer.Stop();
        counter = 0;
    }

    public string Message {
        get { return message; }
        set { message = value; }
    }

    private void TimerTick(object sender, ElapsedEventArgs e) {
        Turn();
    }

    private void Turn() {
        counter++;
        var elapsed = TimeSpan.FromMilliseconds(counter * 200);
        Console.Write(MASK, INDICATOR[counter % 4], elapsed, this.Message);
    }

    public void Dispose() {
        Stop();
        timer.Elapsed -= TimerTick;
        this.timer.Dispose();
    }
}

usage is something like this:

class Program
{
    static void Main(string[] args)
    {
        using (var spinner = new ConsoleSpiner())
        {
            spinner.Start();
            spinner.Message = "About to do some heavy staff :-)"
            DoWork();
            spinner.Message = "Now processing other staff".
            OtherWork();
            spinner.Stop();
        }
        Console.WriteLine("COMPLETED!!!!!\nPress any key to exit.");

    }
}

How can I know if Object is String type object?

javamonkey79 is right. But don't forget what you might want to do (e.g. try something else or notify someone) if object is not an instance of String.

String myString;
if (object instanceof String) {
  myString = (String) object;
} else {
  // do something else     
}

BTW: If you use ClassCastException instead of Exception in your code above, you can be sure that you will catch the exception caused by casting object to String. And not any other exceptions caused by other code (e.g. NullPointerExceptions).

How to disable the resize grabber of <textarea>?

Just use resize: none

textarea {
   resize: none;
}

You can also decide to resize your textareas only horizontal or vertical, this way:

textarea { resize: vertical; }

textarea { resize: horizontal; }

Finally, resize: both enables the resize grabber.

What are the rules about using an underscore in a C++ identifier?

The rules (which did not change in C++11):

  • Reserved in any scope, including for use as implementation macros:
    • identifiers beginning with an underscore followed immediately by an uppercase letter
    • identifiers containing adjacent underscores (or "double underscore")
  • Reserved in the global namespace:
    • identifiers beginning with an underscore
  • Also, everything in the std namespace is reserved. (You are allowed to add template specializations, though.)

From the 2003 C++ Standard:

17.4.3.1.2 Global names [lib.global.names]

Certain sets of names and function signatures are always reserved to the implementation:

  • Each name that contains a double underscore (__) or begins with an underscore followed by an uppercase letter (2.11) is reserved to the implementation for any use.
  • Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.165

165) Such names are also reserved in namespace ::std (17.4.3.1).

Because C++ is based on the C standard (1.1/2, C++03) and C99 is a normative reference (1.2/1, C++03) these also apply, from the 1999 C Standard:

7.1.3 Reserved identifiers

Each header declares or defines all identifiers listed in its associated subclause, and optionally declares or defines identifiers listed in its associated future library directions subclause and identifiers which are always reserved either for any use or for use as file scope identifiers.

  • All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use.
  • All identifiers that begin with an underscore are always reserved for use as identifiers with file scope in both the ordinary and tag name spaces.
  • Each macro name in any of the following subclauses (including the future library directions) is reserved for use as specified if any of its associated headers is included; unless explicitly stated otherwise (see 7.1.4).
  • All identifiers with external linkage in any of the following subclauses (including the future library directions) are always reserved for use as identifiers with external linkage.154
  • Each identifier with file scope listed in any of the following subclauses (including the future library directions) is reserved for use as a macro name and as an identifier with file scope in the same name space if any of its associated headers is included.

No other identifiers are reserved. If the program declares or defines an identifier in a context in which it is reserved (other than as allowed by 7.1.4), or defines a reserved identifier as a macro name, the behavior is undefined.

If the program removes (with #undef) any macro definition of an identifier in the first group listed above, the behavior is undefined.

154) The list of reserved identifiers with external linkage includes errno, math_errhandling, setjmp, and va_end.

Other restrictions might apply. For example, the POSIX standard reserves a lot of identifiers that are likely to show up in normal code:

  • Names beginning with a capital E followed a digit or uppercase letter:
    • may be used for additional error code names.
  • Names that begin with either is or to followed by a lowercase letter
    • may be used for additional character testing and conversion functions.
  • Names that begin with LC_ followed by an uppercase letter
    • may be used for additional macros specifying locale attributes.
  • Names of all existing mathematics functions suffixed with f or l are reserved
    • for corresponding functions that operate on float and long double arguments, respectively.
  • Names that begin with SIG followed by an uppercase letter are reserved
    • for additional signal names.
  • Names that begin with SIG_ followed by an uppercase letter are reserved
    • for additional signal actions.
  • Names beginning with str, mem, or wcs followed by a lowercase letter are reserved
    • for additional string and array functions.
  • Names beginning with PRI or SCN followed by any lowercase letter or X are reserved
    • for additional format specifier macros
  • Names that end with _t are reserved
    • for additional type names.

While using these names for your own purposes right now might not cause a problem, they do raise the possibility of conflict with future versions of that standard.


Personally I just don't start identifiers with underscores. New addition to my rule: Don't use double underscores anywhere, which is easy as I rarely use underscore.

After doing research on this article I no longer end my identifiers with _t as this is reserved by the POSIX standard.

The rule about any identifier ending with _t surprised me a lot. I think that is a POSIX standard (not sure yet) looking for clarification and official chapter and verse. This is from the GNU libtool manual, listing reserved names.

CesarB provided the following link to the POSIX 2004 reserved symbols and notes 'that many other reserved prefixes and suffixes ... can be found there'. The POSIX 2008 reserved symbols are defined here. The restrictions are somewhat more nuanced than those above.

Error loading the SDK when Eclipse starts

There are lots of answer already given for this problem. Though this issue can happens for any API version, so just see the error line and find out android api version from path and platform name and go to the android sdk manager and delete related system image from sdk manager.

Hibernate - Batch update returned unexpected row count from update: 0 actual row count: 0 expected: 1

I was facing this exception, and hibernate was working well. I tried to insert manually one record using pgAdmin, here the issue became clear. SQL insert query returns 0 insert. and there is a trigger function that cause this issue because it returns null. so I have only to set it to return new. and finally I solved the problem.

hope that helps any body.

Does the join order matter in SQL?

for regular Joins, it doesn't. TableA join TableB will produce the same execution plan as TableB join TableA (so your C and D examples would be the same)

for left and right joins it does. TableA left Join TableB is different than TableB left Join TableA, BUT its the same than TableB right Join TableA

Android Studio error: "Environment variable does not point to a valid JVM installation"

You have a problem with your Java JDK installation. So, try reinstalling it. You can download it from: http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

It looks that you have a 64-bit system, so download the "Windows x64" version.

How do I set the default page of my application in IIS7?

Karan has posted the answer but that didn't work for me. So, I am posting what worked for me. If that didn't work then user can try this

<configuration> 
    <system.webServer> 
        <defaultDocument enabled="true"> 
            <files> 
                <add value="myFile.aspx" /> 
            </files> 
        </defaultDocument> 
    </system.webServer>
</configuration> 

Java: Static Class?

Sounds like you have a utility class similar to java.lang.Math.
The approach there is final class with private constructor and static methods.

But beware of what this does for testability, I recommend reading this article
Static Methods are Death to Testability

Check if cookie exists else set cookie to Expire in 10 days

You need to read and write document.cookie

if (document.cookie.indexOf("visited=") >= 0) {
  // They've been here before.
  alert("hello again");
}
else {
  // set a new cookie
  expiry = new Date();
  expiry.setTime(expiry.getTime()+(10*60*1000)); // Ten minutes

  // Date()'s toGMTSting() method will format the date correctly for a cookie
  document.cookie = "visited=yes; expires=" + expiry.toGMTString();
  alert("this is your first time");
}

Java Singleton and Synchronization

What is the best way to implement Singleton in Java, in a multithreaded environment?

Refer to this post for best way to implement Singleton.

What is an efficient way to implement a singleton pattern in Java?

What happens when multiple threads try to access getInstance() method at the same time?

It depends on the way you have implemented the method.If you use double locking without volatile variable, you may get partially constructed Singleton object.

Refer to this question for more details:

Why is volatile used in this example of double checked locking

Can we make singleton's getInstance() synchronized?

Is synchronization really needed, when using Singleton classes?

Not required if you implement the Singleton in below ways

  1. static intitalization
  2. enum
  3. LazyInitalaization with Initialization-on-demand_holder_idiom

Refer to this question fore more details

Java Singleton Design Pattern : Questions

How to sort a Pandas DataFrame by index?

Slightly more compact:

df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df = df.sort_index()
print(df)

Note: