Does java have a skip list implementation

Question: I find ConcurrentSkipListSet in Java Collection Framework, which is backed up with a skip list. But is there a skip list in Java? A set does not work in my use case. I need a indexable list that supports duplicates.
Comment: What is it about a skiplist that you need for your program?  If you want an indexable list supporting duplicates, why not just use an `ArrayList`?
Comment: indexable list that supports duplicates ... ArrayList ?
Answer: This answer is 3 years late but I hope it will be useful for those wanting a Java skip list from this moment on :)
This solution allows duplicates as you asked. I follow roughly the guide here http://igoro.com/archive/skip-lists-are-fascinating, so the complexities are similar to that, except delete costs O(nlogn) - as I didn't bother using doubly-linked nodes, I imagine doing so would bring delete down to O(logn).
Code comprises of: an interface, the skip list implementing the interface, and the node class.  It is also generic.
You can tune the parameter LEVELS for performance, but remember the space-time tradeoff.
import java.util.Random;

interface SkippableList<T extends Comparable<? super T>> {
    int LEVELS = 5;

    boolean delete(T target);
    void print();
    void insert(T data);
    SkipNode<T> search(T data);
}

public class SkipList<T extends Comparable<? super T>> implements SkippableList<T> {

    public static void main(String[] args) {
        SkipList<Integer> sl = new SkipList<>();
        int[] data = {4,2,7,0,9,1,3,7,3,4,5,6,0,2,8};
        for (int i : data) {
            sl.insert(i);
        }

        sl.print();
        sl.search(4);

        sl.delete(9);
        sl.print();

        sl.insert(69);
        sl.print();
        sl.search(69);
    }

    private final SkipNode<T> head = new SkipNode<>(null);
    private final Random rand = new Random();

    @Override
    public void insert(T data) {
        SkipNode<T> SkipNode = new SkipNode<>(data);
        for (int i = 0; i < LEVELS; i++) {
            if (rand.nextInt((int) Math.pow(2, i)) == 0) { //insert with prob = 1/(2^i)
                insert(SkipNode, i);
            }
        }
    }

    @Override
    public boolean delete(T target) {
        System.out.println("Deleting " + target.toString());
        SkipNode<T> victim = search(target, false);
        if (victim == null) return false;
        victim.data = null;

        for (int i = 0; i < LEVELS; i++) {
            head.refreshAfterDelete(i);
        }

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

    @Override
    public SkipNode<T> search(T data) {
        return search(data, true);
    }

    @Override
    public void print() {
        for (int i = 0; i < LEVELS; i++) {
            head.print(i);
        }

        System.out.println();
    }

    private void insert(SkipNode<T> SkipNode, int level) {
        head.insert(SkipNode, level);
    }

    private SkipNode<T> search(T data, boolean print) {
        SkipNode<T> result = null;
        for (int i = LEVELS-1; i >= 0; i--) {
            if ((result = head.search(data, i, print)) != null) {
                if (print) {
                    System.out.println("Found " + data.toString() + " at level " + i + ", so stoppped" );
                    System.out.println();
                }

                break;
            }
        }

        return result;
    }

}

class SkipNode<N extends Comparable<? super N>> {

    N data;
    @SuppressWarnings("unchecked")
    SkipNode<N>[] next = (SkipNode<N>[]) new SkipNode[SkippableList.LEVELS];

    SkipNode(N data) {
        this.data = data;
    }

    void refreshAfterDelete(int level) {
        SkipNode<N> current = this.getNext(level);
        while (current != null && current.getNext(level) != null) {
            if (current.getNext(level).data == null) {
                SkipNode<N> successor = current.getNext(level).getNext(level);
                current.setNext(successor, level);
                return;
            }

            current = current.getNext(level);
        }
    }

    void setNext(SkipNode<N> next, int level) {
        this.next[level] = next;
    }

    SkipNode<N> getNext(int level) {
        return this.next[level];
    }

    SkipNode<N> search(N data, int level, boolean print) {
        if (print) {
            System.out.print("Searching for: " + data + " at ");
            print(level);
        }

        SkipNode<N> result = null;
        SkipNode<N> current = this.getNext(level);
        while (current != null && current.data.compareTo(data) < 1) {
            if (current.data.equals(data)) {
                result = current;
                break;
            }

            current = current.getNext(level);
        }

        return result;
    }

    void insert(SkipNode<N> SkipNode, int level) {
        SkipNode<N> current = this.getNext(level);
        if (current == null) {
            this.setNext(SkipNode, level);
            return;
        }

        if (SkipNode.data.compareTo(current.data) < 1) {
            this.setNext(SkipNode, level);
            SkipNode.setNext(current, level);
            return;
        }

        while (current.getNext(level) != null && current.data.compareTo(SkipNode.data) < 1 &&
                current.getNext(level).data.compareTo(SkipNode.data) < 1) {

            current = current.getNext(level);
        }

        SkipNode<N> successor = current.getNext(level);
        current.setNext(SkipNode, level);
        SkipNode.setNext(successor, level);
    }

    void print(int level) {
        System.out.print("level " + level + ": [");
        int length = 0;
        SkipNode<N> current = this.getNext(level);
        while (current != null) {
            length++;
            System.out.print(current.data.toString() + " ");
            current = current.getNext(level);
        }

        System.out.println("], length: " + length);
    }

}

Comment: @Stephan, added an answer which fixes the bug
Comment: Nice one. You have a bug when removing the first item of the list. I have not fixed it yet but letting you know just in case you can fix it first..
Comment: Can you please fix the bug mentioned by @idipous?
Comment: ... or @idipous can you please fix the bug?
Comment: @Stephan I ended up using another implementation so never got around fixing this
Comment: @idipous Would you mind share this other implementation here in an answer?
Comment: @Neo Thank you ;)
Answer: Fixed the bug in the implementation provided by @PoweredByRice. It threw an NPE for cases when the node deleted was the first node. Other updates include renamed variable names and reverse printing the order of the skip list.
import java.util.Random;

interface SkippableList<T extends Comparable<? super T>> {

  int LEVELS = 5;

  boolean delete(T target);
  void print();
  void insert(T data);
  SkipNode<T> search(T data);
}

class SkipNode<N extends Comparable<? super N>> {

  N data;
  @SuppressWarnings("unchecked")
  SkipNode<N>[] next = (SkipNode<N>[]) new SkipNode[SkippableList.LEVELS];

  SkipNode(N data) {
    this.data = data;
  }

  void refreshAfterDelete(int level) {
    SkipNode<N> current = this;
    while (current != null && current.getNext(level) != null) {
      if (current.getNext(level).data == null) {
        SkipNode<N> successor = current.getNext(level).getNext(level);
        current.setNext(successor, level);
        return;
      }

      current = current.getNext(level);
    }
  }

  void setNext(SkipNode<N> next, int level) {
    this.next[level] = next;
  }

  SkipNode<N> getNext(int level) {
    return this.next[level];
  }

  SkipNode<N> search(N data, int level, boolean print) {
    if (print) {
      System.out.print("Searching for: " + data + " at ");
      print(level);
    }

    SkipNode<N> result = null;
    SkipNode<N> current = this.getNext(level);
    while (current != null && current.data.compareTo(data) < 1) {
      if (current.data.equals(data)) {
        result = current;
        break;
      }

      current = current.getNext(level);
    }

    return result;
  }

  void insert(SkipNode<N> skipNode, int level) {
    SkipNode<N> current = this.getNext(level);
    if (current == null) {
      this.setNext(skipNode, level);
      return;
    }

    if (skipNode.data.compareTo(current.data) < 1) {
      this.setNext(skipNode, level);
      skipNode.setNext(current, level);
      return;
    }

    while (current.getNext(level) != null && current.data.compareTo(skipNode.data) < 1 &&
      current.getNext(level).data.compareTo(skipNode.data) < 1) {

      current = current.getNext(level);
    }

    SkipNode<N> successor = current.getNext(level);
    current.setNext(skipNode, level);
    skipNode.setNext(successor, level);
  }

  void print(int level) {
    System.out.print("level " + level + ": [ ");
    int length = 0;
    SkipNode<N> current = this.getNext(level);
    while (current != null) {
      length++;
      System.out.print(current.data + " ");
      current = current.getNext(level);
    }

    System.out.println("], length: " + length);
  }

}

public class SkipList<T extends Comparable<? super T>> implements SkippableList<T> {

  private final SkipNode<T> head = new SkipNode<>(null);
  private final Random rand = new Random();

  @Override
  public void insert(T data) {
    SkipNode<T> skipNode = new SkipNode<>(data);
    for (int i = 0; i < LEVELS; i++) {
      if (rand.nextInt((int) Math.pow(2, i)) == 0) {
        //insert with prob = 1/(2^i)
        insert(skipNode, i);
      }
    }
  }

  @Override
  public boolean delete(T target) {
    System.out.println("Deleting " + target);
    SkipNode<T> victim = search(target, true);
    if (victim == null) return false;
    victim.data = null;

    for (int i = 0; i < LEVELS; i++) {
      head.refreshAfterDelete(i);
    }

    System.out.println("deleted...");
    return true;
  }

  @Override
  public SkipNode<T> search(T data) {
    return search(data, true);
  }

  @Override
  public void print() {
    for (int i = LEVELS-1; i >= 0 ; i--) {
      head.print(i);
    }
    System.out.println();
  }

  private void insert(SkipNode<T> SkipNode, int level) {
    head.insert(SkipNode, level);
  }

  private SkipNode<T> search(T data, boolean print) {
    SkipNode<T> result = null;
    for (int i = LEVELS-1; i >= 0; i--) {
      if ((result = head.search(data, i, print)) != null) {
        if (print) {
          System.out.println("Found " + data.toString() + " at level " + i + ", so stopped" );
          System.out.println();
        }
        break;
      }
    }

    return result;
  }

  public static void main(String[] args) {
    SkipList<Integer> sl = new SkipList<>();
    int[] data = {4,2,7,0,9,1,3,7,3,4,5,6,0,2,8};
    for (int i : data) {
      sl.insert(i);
    }

    sl.print();
    sl.search(4);

    sl.delete(4);

    System.out.println("Inserting 10");
    sl.insert(10);
    sl.print();
    sl.search(10);
  }

}

Answer: Since you've mentioned a List that is both Indexable (I assume you want speedy retrieval) and need to allow duplicates, I would advise you go for a custom Set with a LinkedList or ArrayList perhaps.
You need to have a base Set, an HashSet for example and keep adding values to it. If you face a duplicate, the value of that Set should point to a List. So, that you will have both Speedy retrieval and of course you will store your objects in a psuedo Collection manner.
This should give you good efficiency for retrieval. Ideally if your Keys are not duplicates, you will achieve an O(1) as the retrieval speed.
Answer: When you create a ConcurrentSkipListSet, you pass a comparator to the constructor.
new ConcurrentSkipListSet<>(new ExampleComparator());

public class ExampleComparator implements Comparator<Event> {//your impl }

You could create a comparator that will make your SkipListSet behave as a normal List.
Comment: This will change the ordering of the set, *not* make it behave as a `List`
Answer: You can make use the below to code make your own basic skiplist :
1)Make start and end to represent start and end of skip list.
2)Add the nodes and assign pointers to next based on
if(node is even)
    then ,assign a fast lane pointer with next pointer
  else
    assign only pointer to next node

Java code for basic skip list (you can add more features if you want):
public class MyClass {

    public static void main(String args[]) {
        Skiplist skiplist=new Skiplist();

        Node n1=new Node();
        Node n2=new Node();
        Node n3=new Node();
        Node n4=new Node();
        Node n5=new Node();
        Node n6=new Node();

        n1.setData(1);
        n2.setData(2);
        n3.setData(3);
        n4.setData(4);
        n5.setData(5);
        n6.setData(6);

        skiplist.insert(n1);
        skiplist.insert(n2);
        skiplist.insert(n3);
        skiplist.insert(n4);
        skiplist.insert(n5);
        skiplist.insert(n6);

        /*print all nodes*/
        skiplist.display();
        System.out.println();
        /* print only fast lane node*/
        skiplist.displayFast();
    }
}

class Node{
    private int data;
    private Node one_next;  //contain pointer to next node
    private Node two_next;  //pointer to node after the very next node
    public int getData() {
        return data;
    }
    public void setData(int data) {
        this.data = data;
    }
    public Node getOne_next() {
        return one_next;
    }
    public void setOne_next(Node one_next) {
        this.one_next = one_next;
    }
    public Node getTwo_next() {
        return two_next;
    }
    public void setTwo_next(Node two_next) {
        this.two_next = two_next;
    }

}

class Skiplist{
    Node start;      //start pointer to skip list
    Node head;
    Node temp_next;  //pointer to store last used fast lane node
    Node end;        //end of skip list
    int length;

    public Skiplist(){
        start=new Node();
        end=new Node();
        length=0;
        temp_next=start;
    }

    public void insert(Node node){
        /*if skip list is empty */
        if(length==0){
            start.setOne_next(node);
            node.setOne_next(end);
            temp_next.setTwo_next(end);
            head=start;
            length++;
        }
        else{
            length++;
            Node temp=start.getOne_next();
            Node prev=start;

            while(temp != end){
                prev=temp;
                temp=temp.getOne_next();
            }

            /*add a fast lane pointer for even no of nodes*/
            if(length%2==0){
                prev.setOne_next(node);
                node.setOne_next(end);
                temp_next.setTwo_next(node);
                temp_next=node;
                node.setTwo_next(end);
            }
            /*odd no of node will not contain fast lane pointer*/
            else{
                prev.setOne_next(node);
                node.setOne_next(end);
            }

        }
    }

    public void display(){
        System.out.println("--Simple Traversal--");
        Node temp=start.getOne_next();

        while(temp != end){
            System.out.print(temp.getData()+"=>");
            temp=temp.getOne_next();

        }
    }

    public void displayFast(){
        System.out.println("--Fast Lane Traversal--");
        Node temp=start.getTwo_next();
        while(temp !=end){
            System.out.print(temp.getData()+"==>");
            temp=temp.getTwo_next();
        }
    }
}

Output:
--Simple Traversal--
1=>2=>3=>4=>5=>6=>
--Fast Lane Traversal--
2==>4==>6==>
Answer: I approve to use TreeList from apache-collections and decorate it with SortedList from Happy Java Libraries
https://sourceforge.net/p/happy-guys/wiki/Sorted%20List/
Answer: I am not claiming that this is my own implementation. I just cannot remember where I found it. If you know let me know and I will update. This has been working quite well for me:
public class SkipList<T extends Comparable<? super T>> implements Iterable<T> {

Node<T> _head = new Node<>(null, 33);
private final Random rand = new Random();
private int _levels = 1;
private AtomicInteger size = new AtomicInteger(0);

///
/// Inserts a value into the skip list.
///
public void insert(T value) {
    // Determine the level of the new node. Generate a random number R. The
    // number of
    // 1-bits before we encounter the first 0-bit is the level of the node.
    // Since R is
    // 32-bit, the level can be at most 32.
    int level = 0;
    size.incrementAndGet();
    for (int R = rand.nextInt(); (R & 1) == 1; R >>= 1) {
        level++;
        if (level == _levels) {
            _levels++;
            break;
        }
    }

    // Insert this node into the skip list
    Node<T> newNode = new Node<>(value, level + 1);
    Node<T> cur = _head;
    for (int i = _levels - 1; i >= 0; i--) {
        for (; cur.next[i] != null; cur = cur.next[i]) {
            if (cur.next[i].getValue().compareTo(value) > 0)
                break;
        }

        if (i <= level) {
            newNode.next[i] = cur.next[i];
            cur.next[i] = newNode;
        }
    }
}

///
/// Returns whether a particular value already exists in the skip list
///
public boolean contains(T value) {
    Node<T> cur = _head;
    for (int i = _levels - 1; i >= 0; i--) {
        for (; cur.next[i] != null; cur = cur.next[i]) {
            if (cur.next[i].getValue().compareTo(value) > 0)
                break;
            if (cur.next[i].getValue().compareTo(value) == 0)
                return true;
        }
    }
    return false;
}

///
/// Attempts to remove one occurence of a particular value from the skip
/// list. Returns
/// whether the value was found in the skip list.
///
public boolean remove(T value) {

    Node<T> cur = _head;

    boolean found = false;
    for (int i = _levels - 1; i >= 0; i--) {
        for (; cur.next[i] != null; cur = cur.next[i]) {
            if (cur.next[i].getValue().compareTo(value) == 0) {
                found = true;
                cur.next[i] = cur.next[i].next[i];
                break;
            }

            if (cur.next[i].getValue().compareTo(value) > 0)
                break;
        }
    }
    if (found)
        size.decrementAndGet();
    return found;
}

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public Iterator<T> iterator() {
    return new SkipListIterator(this, 0);
}

public int size() {
    return size.get();
}

public Double[] toArray() {
    Double[] a = new Double[size.get()];
    int i = 0;
    for (T t : this) {
        a[i] = (Double) t;
        i++;
    }
    return a;
  }

 }

 class Node<N extends Comparable<? super N>> {
public Node<N>[] next;
public N value;

@SuppressWarnings("unchecked")
public Node(N value, int level) {
    this.value = value;
    next = new Node[level];
}

public N getValue() {
    return value;
}

public Node<N>[] getNext() {
    return next;
}

public Node<N> getNext(int level) {
    return next[level];
}

public void setNext(Node<N>[] next) {
    this.next = next;
}
}

class SkipListIterator<E extends Comparable<E>> implements Iterator<E> {
   SkipList<E> list;
   Node<E> current;
   int level;

public SkipListIterator(SkipList<E> list, int level) {
    this.list = list;
    this.current = list._head;
    this.level = level;
}

public boolean hasNext() {
    return current.getNext(level) != null;
}

public E next() {
    current = current.getNext(level);
    return current.getValue();
}

public void remove() throws UnsupportedOperationException {
    throw new UnsupportedOperationException();
}
}


How to see new entries without refreshing the page?

Question: In my page.html using ngIf, data is fetched from local storage using below code:

<ion-header>
  <ion-navbar>
    <button ion-button menuToggle>
        <ion-icon name="menu"></ion-icon>
      </button>
    <ion-title>Education</ion-title>
  </ion-navbar>
</ion-header>
<ion-content padding>
  <ion-item>
    <ion-input [(ngModel)]="newentry.title" type="text" placeholder="Title" [value]="title ? title: ''">
    </ion-input>
  </ion-item>
  <ion-item>
    <ion-input [(ngModel)]="newentry.description" type="text" placeholder="Description">
    </ion-input>
  </ion-item>
  <ion-item>
    <ion-input [(ngModel)]="newentry.tagline" type="text" placeholder="Tag line">
    </ion-input>
  </ion-item>
  <ion-item>
    <ion-input [(ngModel)]="newentry.date" type="text" placeholder="Date">
    </ion-input>
  </ion-item>
  <button ion-button item-right>
       <ion-icon name="md-add-circle" (click)="save(newentry);"></ion-icon>

      </button>

      {{elem.title}} {{elem.description}}
      <button ion-button item-right (click)="editedu(elem,index);">
                <ion-icon name="open"></ion-icon>
              </button>
      <button ion-button item-right (click)="deleteedu(elem,index)">
                  <ion-icon name="trash"></ion-icon>
      </button>

</ion-content>

On this same page I have a form to add new data, but when I add and save, I have to load the page from menu again to see the new data entered, how can this load instantly ?
This is how my page looks:

Update
Posting my page.ts code:
import { Component } from '@angular/core';
import {  NavController, NavParams } from 'ionic-angular';
import { Education } from "./education";

/**
 * Generated class for the EducationPage page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */
//@IonicPage()
@Component({
  selector: 'page-education',
  templateUrl: 'education.html',
})

export class EducationPage {

  list: Array<number> = [1, 2, 3];
  //myArray =  [{title:"saurabh" , description:"dd" , tagline:"tt", date:"dd"},{title:"gaurav" , description:"dd" , tagline:"tt", date:"dd"}];
  myArray = [];
  number1 = 5;
  newentry = { title: "", description: "", tagline: "", date: "", id: Math.random().toString(36).substr(2, 10) };
  data = '';
  fetchdata = [];
  dataObj: Education[] = [];
  elem = '';
  index;
  constructor(public navCtrl: NavController, public navParams: NavParams) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad EducationPage');
    //console.log(this.list);
    // console.log(this.myArray);
    //  localStorage.setItem("education-number",JSON.stringify(this.list));
    this.data = localStorage.getItem('education');
    if (!this.data) {
      localStorage.setItem("education", JSON.stringify(this.myArray));
    }
    this.fetchdata = JSON.parse(localStorage.getItem('education'));
    console.log(this.fetchdata);

  }

  // updateeditmode(){
  //   this.editmode=true;
  //   console.log(this.editmode);
  // }

  editedu(elem, index) {
    // console.log(elem);
    console.log("inside editedu::");
    this.newentry = elem;
    this.newentry.title = elem.title;
    // this.fetchdata.splice(index, 1);
    //elem.title = 'CLICKED';
    console.log(this.fetchdata);
    localStorage.setItem("education", JSON.stringify(this.fetchdata));
  }

  deleteedu(elem, index) {
    console.log(elem);
    console.log(index);
    this.fetchdata.splice(index, 1);
    //elem.title = 'CLICKED';
    console.log(this.fetchdata);
    localStorage.setItem("education", JSON.stringify(this.fetchdata));
  }

  save(entry: Education) {
    this.data = localStorage.getItem('education');
    console.log("save working");
    console.log(this.data);
    if (this.data) //check if it exists or not empty
    {
      console.log("inside save function");
      this.dataObj = JSON.parse(this.data); //parse string
      console.log(this.dataObj);
      let filtered = this.dataObj.filter(t => t.id === entry.id);
      if (filtered.length > 0) {
        this.dataObj[this.dataObj.findIndex(eel=>eel.id === entry.id)] = entry;
      } else {
        this.dataObj.push(this.newentry);
      }
      console.log(this.dataObj);
      localStorage.setItem("education", JSON.stringify(this.dataObj));
    }

    console.log("inside save edit area");
    //this.editedu(this.elem,this.index);
  }

}

Comment: "below code" doesn't show anything about localStorage.What is `fetchdata`?
Comment: call this function ionViewDidLoad() method once you save data
Comment: Post your code.
Comment: html or ts file ?
Comment: You have to add the data to your table, which is `fetchdata`. Since you get the data from the local storage, you should use `NgZone` to run your non-Angular code.
Comment: All the code that is needed so that we can understand how you're currently adding a new item.
Comment: updated my question, posted entire .ts code
Comment: Your HTML page displays the elements in fetchdata. Your save method doesn't add anything to fetchdata. So why would the displayed items change. Hint: TypeScript has local variables. Almost all the fields declared in your component should be local variables. The fields should contain the state of your component, that is used by the template. Not all the local variables needed by your various methods.
Comment: worked by calling this.ionViewDidLoad(); in the end of save function
Answer: Try one of these:

ApplicationRef.tick() - similar to Angular 1's $rootScope.$digest() --
  i.e., check the full component tree
ChangeDetectorRef.detectChanges() - similar to $scope.$digest() --
  i.e., check only this component and its children

After you get you update your data from subscribe method, use one of these to update the view with new changes.


Avoid change for users profile fields

Question: Now in my site every logged user are able to change his profile fields (standard fields and custom fields). I am searching a way to avoid this capability for every 'normal' users (in other word i want that only the administrator have this ability).
There is a method to do this via code or via frontend?
Answer: You can use the project Edit Own User Account Permission. It adds a new permission to People > Permissions called "Edit own user account". You can then allow specific roles the ability to edit their own account.
Comment: Provided that you are wanting to keep the user from editing any part of their user profile, this is definitely the better solution. However this will not work if you only want to keep them from editing a few fields.
Answer: I believe the Field Permissions module will do what you are wanting. It allows you to determine which roles can edit, view, and create values for any field.

Avoid change for users profile fields


How to use indentation in gson to generate a json file

Question: I have to generate a json file containing indentation. I was using Jackson for this but it adds a space before the colon and I don't need it, so I decided to use Gson.
After changing the code, I figured out that by default Gson don't use indentation but Jackson does. Does anyone know if it is possible in Gson to get indentation and how to do it?
For generating the json file with Gson I made this:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder = gsonBuilder.setPrettyPrinting();
Gson gson = gsonBuilder.create();
Writer writer = new FileWriter(propsFile);
gson.toJson(properties, writer);

Comment: I believe he/she means "indent"
Comment: If there is any solution to change the default intent in Gson, I can use Jackson, but how  I eliminate the space before colon?
Comment: What do you mean by "use `Intent`"?
Comment: Edited question and retagged as appropriate.
Comment: I meant "indent" indeed. Do you have some suggestions about how I could solve it?
Comment: You should post a small example of what you want your JSON to look like, because setting pretty print on is supposed to make JSON readable already, but it seems you don't like that format.
Answer: You can only employ the default indentation provided by setPrettyPrinting() and you cannot change its size or indentation characters. Please refer to the official information about it: Compact Vs. Pretty Printing for JSON Output Format.
Answer: Possible duplicate of https://stackoverflow.com/a/41509714/4379906

Use Jackson and and configure it not to add spaces before colon:
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.11.2</version>
</dependency>

CustomPrettyPrinter.java:
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;

import java.io.IOException;

class CustomPrettyPrinter extends DefaultPrettyPrinter {
    public CustomPrettyPrinter() {
        super();
    }

    public CustomPrettyPrinter(DefaultPrettyPrinter base) {
        super(base);
    }

    @Override
    public void writeObjectFieldValueSeparator(JsonGenerator g) throws IOException {
        g.writeRaw(": ");
    }

    @Override
    public DefaultPrettyPrinter createInstance() {
        return new CustomPrettyPrinter(this);
    }
}

UseJackson.java:
import com.fasterxml.jackson.core.util.DefaultIndenter;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.IOException;
import java.util.Properties;

public class UseJackson {
    public static void main(String[] args) throws IOException {
        DefaultPrettyPrinter.Indenter indenter = new DefaultIndenter("    ", DefaultIndenter.SYS_LF);
        DefaultPrettyPrinter printer = new CustomPrettyPrinter();
        printer.indentArraysWith(indenter);
        printer.indentObjectsWith(indenter);

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setDefaultPrettyPrinter(printer);

        Properties properties = new Properties();
        properties.put("foo", "3");
        properties.put("bar", "4");
        objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File("a.json"), properties);
    }
}

Use Gson and configure indentation:
UseGson.java:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.stream.JsonWriter;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;

public class UseGson {
    public static void main(String[] args) throws IOException {
        Properties properties = new Properties();
        properties.put("foo", "3");
        properties.put("bar", "4");

        JsonWriter jsonWriter = new JsonWriter(new FileWriter("a.json"));
        jsonWriter.setIndent("    ");

        Gson gson = new GsonBuilder().serializeNulls().create();
        gson.toJson(properties, Properties.class, jsonWriter);

        jsonWriter.close();
    }
}


Definitions for complex numbers

Question: I could not find this question anywhere else. But why are addition, subtraction, division, and other operations defines they are in complex numbers? Could they defined as something else?
Comment: Someone down-voted the question.  (I up-voted it and the sum is now zero.)  Could the down-voter explain what the objections are? ${}\qquad{}$
Comment: It would make it much easier to write an explanation if you add a bit about what exactly is tripping you, and what you already understand about the subject (in particular about the real numbers, from which we usually define the complex numbers).
Comment: Related: http://math.stackexchange.com/questions/1364439/most-natural-intro-to-complex-numbers/1364664#1364664
Answer: To add $a$ and $b$, start at $0$ and draw an arrow to $a$ and another arrow to $b$.  Then move the arrow from $0$ to $b$ so that its starting point is at $a$.  Then its ending point is at $a+b$.
That works BOTH for real numbers and for complex numbers.  So you're doing the same thing as with real numbers, but in a plane rather than in a line.
To multiply $a$ and $b$, draw the line through $0$ and $a$, and leave $0$ where it is but write $1$ where $a$ is.  Having put $0$ and $1$ in their places locate $b$ in this stretched coordinate system.  Look at what number appears at that point in the original coordinate system before stretching.  That number is $a\times b$.
For example, say $a=3$ and $b=2$.  Put $1$ where $a=3$ is, then see where $b=2$ is in the stretched system.  It's at $6$.  Therefore $a\times b=3\times 2=6$:
$$
\begin{array}{ccccccccccccccccccccccc}
0 & & 1 & & 2 & & 3 & & 4 & & 5 & & 6 & & 7 & \cdots \\
| & \qquad & | & \qquad & | & \qquad & | & \qquad & | & \qquad & | & \qquad & | & \qquad & | & \cdots \\
0 & & & & & & 1 & & & & & & 2 & & & \cdots
\end{array}
$$
That way of multiplying works BOTH in the real numbers and in the complex numbers.  So you're doing the same thing as with real numbers, but in a plane rather than in a line.  Anyone who's ever wondered why the product of two negative numbers is positive can use this idea to see the answer.  This also explains why multiplication by $i$ amounts to a $90^\circ$ counterclockwise rotation.
Answer: Yes, they could, at least for multiplication.  You can define $(x,y)\cdot(z,w)$ to be $(xz-3yw,xw+yz)$ for every $x,y,z,w\in\mathbb{R}$.  How deep is your knowledge about fields and field extensions?

EDIT:
Basically, if you want a field extension of $\mathbb{R}$, then this field will be a vector space over $\mathbb{R}$, so you don't have liberty with defining addition on this field extension as it has to be carried over from the addition on $\mathbb{R}$.  If the extension is algebraic and proper, then you can construct it by consider the quotient $\mathbb{R}[t]/\big(f(t)\big)$ for some polynomial $f(t)\in\mathbb{R}[t]$ irreducible over $\mathbb{R}$.  Such polynomials are of the form $f(t)=at^2+bt+c$ with $a,b,c\in\mathbb{R}$ are such that $a\neq 0$ and $b^2-4ac<0$.  If you define $\bar{t}$ to be $t+\big(f(t)\big)$ in $\mathbb{R}[t]/\big(f(t)\big)$, then every element of $\mathbb{R}[t]/\big(f(t)\big)$ can be written as $u+v\bar{t}$ for some $u,v\in\mathbb{R}$.  Note that $(x+y\bar{t})(z+w\bar{t})=\left(xz-\frac{c}{a}yw\right)+\left(xw+yz-\frac{b}{a}yw\right)\bar{t}$ is the multiplication on $\mathbb{R}[t]/\big(f(t)\big)$ (this is due to the fact that $a\bar{t}^2+b\bar{t}+c=0$ in $\mathbb{R}[t]/\big(f(t)\big)$).
The usual choice of this polynomial is $f(t)=t^2+1$, then you have the usual operations of the complex numbers.  In my example, I chose $f(t)=t^2+3$, but you can choose many other different polynomials such as $f(t)=t^2+t+41$, where your multiplication would become $(x+y\bar{t})(z+w\bar{t})=(xz-41yw)+(xw+yz-yw)\bar{t}$.  However, no matter which polynomial $f(t)$ you take, you will end up with a field isomorphic to $\mathbb{C}$.  A field isomorphism $\varphi:\mathbb{R}[t]/\big(f(t)\big)\to\mathbb{C}$ is given by $u+v\bar{t}\mapsto\left(u-\frac{b}{2a}v\right)+\left(\frac{\sqrt{4ac-b^2}}{2a}v\right)\text{i}$.  It is just that $\mathbb{C}=\mathbb{R}[t]/\big(t^2+1\big)$ is the easiest algebraic extension of $\mathbb{R}$ to deal with.
Comment: My understanding is decent. I have taught myself it so I would most likely know what you are talking about if you were to explain.
Comment: I believe this example is just the isomorphism between $\mathbb{R}[\sqrt{-1}]$ and $\mathbb{R}[\sqrt{-3}]$, being the identity on $\mathbb{R}$ and sending $\sqrt{-1}$ to $\sqrt{-3}$.
Answer: One way to view complex numbers is that they are an attempt to make $\mathbb{R}^2$ into a field while still retaining some of the fundamental properties of $\mathbb{R}$. As such, we would want to keep vector addition the same when translating between $\mathbb{R}^2$ and $\mathbb{C}$. Hence $(w,x)+(y,z) = (w+y,x+z)$. From there you can get subtraction quite easily since subtraction is just adding the additive inverse.
The tricky part is the multiplication. You can always define a multiplication on vector spaces but it might not really be a "useful" construct. For instance one way we could multiply vector elements is by $(w,x)\cdot(y,z) = (wy,xz)$, i.e. componentwise multiplication. The problem with this is that this doesn't give $\mathbb{R}^2$ a field structure. Particularly, there are nonzero elements which multiply to $(0,0)$: $(1,0)$ and $(0,1)$.
So the simplest construction fails pretty spectacularly. The next simplest might be $(w,x)\cdot(y,z) = (wz,xy)$. However again there are nonzero elements which multiply to $(0,0)$: $(1,0)$ and $(1,0)$. So even this doesn't work.

This is the point where we turn to the properties of $\mathbb{R}$ and make one "modest" geometric assumption.

We can identify $\mathbb{R}$ with the $x$ axis in $\mathbb{R}^2$. If we were to respect the field properties of $\mathbb{R}$, then we would need that $(x,0)\cdot(y,0) = (xy,0)$ - meaning if we multiply two complex numbers with $0$ in the second component (i.e. two real numbers), we should get a complex number with $0$ in its second argument (i.e. a real number).
Another piece is noting that $\mathbb{R}^2$ is a vector space over $\mathbb{R}$. Meaning that if we have real $\alpha$, then $\alpha(x,y) = (\alpha x,\alpha y)$. In terms of complex numbers, $(\alpha, 0)\cdot(x,y) = (\alpha x,\alpha y)$.
Since it doesn't matter in which order we multiply real numbers (i.e. $xy = yx$), it seems reasonable to want this for complex numbers so we will impose this condition as well.
If $(w,x)$ is a unit vector, then $(w,x)\cdot(y,z)$ has the same length as $(y,z)$.

The first three points heavily constrain the sort of multiplication we can do between complex numbers. If we multiplied $(w,x)$ and $(y,z)$, what should emerge is something of the form$^{1}$
$$\left(\begin{array}{c}\alpha_1 wy + \alpha_2 wz + \alpha_3 xy + \alpha_4 xz \\ \beta_1 wy + \beta_2 wz + \beta_3 xy + \beta_4 xz\end{array}\right).$$
If $x = 0 = z$, then we fall into the case of condition $1$ above and our multiplication should result in $(wy, 0)$, meaning that $\alpha_1 = 1$ and $\beta_1 = 0$.
If $x = 0$, then we fall into the case of condition $2$ above. In which case the product should become $(wy, wz)$. This says that $\alpha_2 = 0 = \beta_1$ and $\beta_2 = 1$.
This simplifies our multiplication a bit:
$$\left(\begin{array}{c} w \\ x \end{array}\right)\cdot\left(\begin{array}{c} y \\ z\end{array}\right) = \left(\begin{array}{c} wy + \alpha_3 xy + \alpha_4 xz \\ wz + \beta_3 xy + \beta_4 xz\end{array}\right).$$
Making use of commutativity (condition $3$),
$$\left(\begin{array}{c} w \\ x\end{array}\right)\cdot\left(\begin{array}{c} y \\ z\end{array}\right) = \left(\begin{array}{c} y \\ z\end{array}\right)\cdot \left(\begin{array}{c} w \\ x\end{array}\right)$$
or equivalently (using our simplified multiplication)
$$\left(\begin{array}{c} wy + \alpha_3 xy + \alpha_4 xz \\ wz + \beta_3 xy + \beta_4 xz\end{array}\right) = \left(\begin{array}{c} wy + \alpha_3 wz + \alpha_4 xz \\ xy + \beta_3 wz + \beta_4 xz\end{array}\right)$$
On the left hand side, there is no appearance of $wz$ in the first component so $\alpha_3 = 0$. Moreover, $\beta_3 = 1$ to match the $\beta_3 wz$ in the second component on the right hand side and the $wz$ in the second component on the left hand side. This simplifies our multiplication to
$$\left(\begin{array}{c} w \\ x\end{array}\right)\cdot\left(\begin{array}{c} y \\ z\end{array}\right) = \left(\begin{array}{c} wy + \alpha_4 xz \\ xy + wz + \beta_4 xz\end{array}\right).$$

So now we have two parameters which we need to somehow do away with. The reason for these parameters existing in the first place is that we have really only used the real structure of complex numbers; we haven't given any meaning to the multiplication of two pure imaginary numbers (vectors of the form $(0,a)$), hence the appearance of $xz$ in both the numerator and denominator.
At this point, we have invoked most of the properties of a field but we are still missing one: no zero divisors, meaning no two nonzero elements multiply to zero.
Taking $(w,x)$ to be a fixed nonzero vector, we can view $(w,x)\cdot(y,z)$ as a matrix product:
$$\left(\begin{array}{cc} w & \alpha_4 x \\ x & w+\beta_4 x\end{array}\right)\left(\begin{array}{c} y \\ z\end{array}\right).$$
If we don't want $(w,x)\cdot(y,z)$ to be zero, then the nullspace of the above matrix must be trivial. That is to say that the determinant of the above matrix must be nonzero. Equivalently, if the determinant of the above matrix is zero, then both $w$ and $x$ are zero.
Taking the determinant and setting it to zero, we get $w^2 + \beta_4 wx - \alpha_4x^2 = 0$. Note that both $\alpha_4$ and $\beta_4$ cannot be zero since then $(0,x)\cdot(0,z) = (0,0)$ for arbitrary $x,z$. If $x=0$, then $w$ must be $0$. Consider then $x\neq 0$.
The only way for there to be no solution to the above equation (in real numbers which is what $w$ and $x$ are) is if the discriminant is less than zero, i.e. $\beta_4^2x^2 + 4\alpha_4x^2 < 0$. Since $x^2 > 0$, this simplifies to $\beta_4^2 + 4\alpha_4 < 0$. Thus any $\alpha_4$ satisfying $\alpha_4 < -\left(\frac{\beta_4}{2}\right)^2$ will give rise to a field with $\beta_4$ being a free parameter.

This is a little bit unsatisfactory since we can't "derive" the complex number structure just from our first three conditions above. These conditions do not fully encompass the spirit of complex numbers. Complex numbers are meant to be not only algebraic in their origin but also geometric. This is the reason for our fourth assumption - to capture the geometric flavor of complex numbers.
If we invoke our geometric condition (condition $4$), we can completely solve the problem. Taking $w= 0 = y$ and $x=1 = z$, then $(0,1)\cdot(0,1) = (\alpha_4 ,\beta_4 )$. Thus $\alpha_4^2 + \beta_4^2 = 1$.
If $(w,x)$ is a unit vector, then $w = \cos\theta$ and $y = \sin\theta$ for some angle $\theta$. If $(w,x)\cdot(y,z)$ is to have the same length as $(y,z)$, then the matrix $(w,x)$ must have determinant $1$, meaning that
$$w^2 + \beta_4wx -\alpha_4 x^2 = 1 \Longrightarrow \cos^2\theta + \beta_4 \sin\theta\cos\theta -\alpha_4\sin^2\theta = 1.$$
Substituting $\alpha_4 = \pm\sqrt{1-\beta_4^2}$, this becomes
$$\cos^2\theta + \beta_4\sin\theta\cos\theta \mp \sqrt{1-\beta_4^2} \sin^2\theta = 1$$
which further reduces to
$$\left(\sqrt{1-\beta_4^2}-1\right)\sin^2\theta + \beta_4\sin\theta\cos\theta = 0.$$
Picking $\theta = \frac{\pi}{4}$, we see that $\sin\theta\cos\theta > 0$ and so $\beta_4 = 0$.
Thus $\alpha_4 = \pm 1$ but the only way for $(w,x)\cdot(y,z)$ to have the same length as $(y,z)$ (when $(w,x)$ is a unit vector) is if $\alpha_4 = -1$. Hence the product of $(w,x)$ and $(y,z)$ is $(wy - xz, wz+xy)$ which is exactly the algebraic structure of the complex numbers.
From this, you of course get that $(0,1)\cdot(0,1) = (-1,0)$ for free, which is of course the identity $i^2 = -1$. You also get to see first hand how the matrix form of complex numbers works (since it's more or less built into my "derivation") and by proxy the polar form and what the othe field structures on $\mathbb{R}^2$ are.

$^{1}$ You could of course have higher powers but then you'd lose linearity of multiplication over addition.
Comment: This is the first really satisfying justification of complex multiplication I've seen. Very well written!
Comment: Thanks a bunch! It just came to me in a stream of conscience fashion. I found it to be pretty elegant.
Answer: We define in $\Bbb R^2$ the operations $+$ and $\cdot$ by: $$(a,b)+(c,d) = (a+c,b+d), \quad (a,b)\cdot(c,d) = (ac-bd, ad+bc)$$because these operations make $\Bbb C \stackrel{\rm def}{=} (\Bbb R^2, +, \cdot)$ a field. One can prove that: $$\Bbb R \ni x \hookrightarrow (x,0) \in \Bbb R^2$$is an isomorphism onto its image, so that $\Bbb C$ contains a "copy" of $\Bbb R$ inside it. Also, note that $(0,1)\cdot (0,1) = (-1,0)$. From this, we call $(0,1) \equiv i$. Then the notation: $$(x,y) = (x,0)+(0,y)= (x,0) + (y,0)(0,1) \equiv x+iy.$$You could define other operations on $\Bbb R^2$, but most likely they won't have nice properties as the ones above.
Comment: I see. So the operations could be defined as anything? But complex numbers are based on the operations in the coordinate plane.
Comment: Writing $z = x+iy$ is a notation. Complex numbers aren't "based" in the coordinate plane, they **are** the coordinate plane $\Bbb R^2$ with convenient operations.
Comment: Could it be defined as anything else though?
Comment: **Could** be, but what good is a mathematical structure such that you can't do any theory with it?
Comment: It could be applied to a few things and studied for its own sake I suppose. I was just curious.
Answer: The definition of arithmetic of complex numbers is forced on you if you want it to extend the ordinary arithmetic of real numbers and still satisfy the usual "laws of arithmetic" (things like $x+y=y+x$, $x(y+z)=xy+xz$, etc.).  For instance, suppose you have complex numbers $z=a+bi$ and $w=c+di$, where $a,b,c,d\in\mathbb{R}$.  Then if we assume addition and multiplication satisfies all the usual rules, we get
$$z+w=(a+bi)+(c+di)=(a+c)+(bi+di)=(a+c)+(b+d)i$$
and
$$zw=(a+bi)(c+di)=ac+adi+bci+bdi^2=(ac-bd)+(ad+bc)i.$$
By similar manipulations, you can obtain the formulas for subtraction and division of complex numbers (though the division one is trickier to derive).
More precisely, the "usual rules" here are that addition and multiplication satisfy the axioms of a commutative ring (and subtraction and division are defined using additive and multiplicative inverses).  The above derivations can be interpreted as a proof that in any commutative ring $C$ containing the real numbers as a subring and an element $i\in C$ such that $i^2=-1$, addition and multiplication of elements of the form $a+bi$ for $a,b\in\mathbb{R}$ must satisfy the formulas above.

Definitions for complex numbers


Como criar um modelo com apenas alguns campos da tabela?

Question: Tenho algumas tabelas com vários campos. Por exemplo, a tabela (X) tem uns 20 campos dos quais eu só utilizarei 2 ou 3.
Nessa situação eu tenho que criar os modelos com todos os campos e ignorar as propriedades no EntityTypeConfiguration ou existe alguma forma de eu mapear apenas os campos que minha aplicação necessita nos meus modelos?
Comment: Está usando CodeFirst ou DatabaseFirst?
Answer: Usando ORM, é sempre complicado definir mais de uma entidade para a mesma tabela.
Mas devido a esta limitação a gente acaba descobrindo que não precisa fazer isso; que fazer isso aumenta a complexidade do sistema desnecessariamente.
Você precisa de alguns campos apenas para leitura?
Faça um select (LINQ) para um novo tipo de objeto (eventualmente anônimo mesmo) retornando apenas estes campos.
Você precisa ler e também alterar estes poucos campos?
Talvez aí resida um erro conceitual.
Apenas a entidade conhece a complexidade das alterações do seu estado. Por exemplo: será que você pode mesmo alterar dois atributos de uma entidade sem que ela esteja de posse do valor de outros atributos para poder validar-se?
Por outro lado, você como programador é um grande conhecedor do domínio e de repente sabe que pode fazer esta alteração sem riscos, e considera importante o ganho de performance de não ter que resgatar a entidade inteira para fazer esta pequena alteração.
Neste caso, você pode fazer as alterações através de comandos UPDATE, abrindo mão de usar a definição da entidade. Isso garante a performance e deixa explícito que a alteração está sendo feita sem o conhecimento do estado completo da entidade, porque ela não foi resgatada do banco.
Usando esta opção, talvez você queira definir uma API de repositório para esta entidade em vez de manipulá-la sempre diretamente através do LINQ ou comandos diretos, de modo a centralizar em um objeto a persistência e recuperação deste tipo de entidade, o que pode melhorar a expressividade geral do código e a reutilização dos métodos customizados de persistência e recuperação.
Comment: A maneira mais fácil que encontrei de resolver esse problema foi criando uma view e configurando via Fluent Api que minha entidade se baseie nessa view e não na tabela propriamente dita.
Answer: A maneira mais fácil que encontrei de resolver esse problema foi criando uma view e configurando via  Fluent Api que minha entidade se baseie nessa view e não na tabela propriamente dita.
Na configuração na tabela onde ao invés de informar a tabela deve se informar a view:
<code>ToTable("VIEW_USUARIO", "Schema_Data_Base");
</code>
Comment: E o que mais? Como ficou essa configuração?
Comment: Na configuração ta tabela onde ao inves de infornar a tabela deve se informar a view:
`ToTable("VIEW_USUARIO", "Schema_Data_Base");`
Comment: Edite sua resposta com esta parte. Aqui nos comentários não tem formatação do código.


How to calculate modulus of the form (a*b)%c?

Question: How to calculate modulus of the form (a*b)%c?
i want to calculate modulus of multiplication of two int numbers where they are almost in the stage of overflow...
here c is also int
Answer: (a * b) % c == ((a % c) * (b % c)) % c

Comment: If a <= b < c, a % c and b % c will do nothing, so we could still get an overflow.
Comment: +1 Just commented this, but the lack of coffee meant I was not sure. ;)
Answer: What about ((a % c) * (b % c)) % c? Depending on your architecture this could be faster or slower than casting to a bigger type.
Comment: If a <= b < c, a % c and b % c will do nothing, so we could still get an overflow.
Answer: You may cast a and c to long long, so the multiplication won't overflow.
((long long)a * (long long)b) % c

Comment: I don't think you would find a faster solution. On x86 machines, the result of 32 bit multiplication is always 64-bit. This way you just notify the compiler to use 64-bit result.
Comment: long long is not always bigger than int (especially on modern machines)
Comment: i need something optimized method


Get store id for each CMS page in Magento

Question: We're extending a custom extension of ours and in a form in the admin page, we're using the store view selector. Once the store is selected, we need to construct a list of the CMS pages for that store.
In order to filter the list of CMS pages based on the selected store, we're trying to insert some javascript to change the pages dropdown as per the selected store and subsequently we need to know what store id, each page belongs to on a per page basis.
Is there an easy way of achieving this? Can't post anything we've tried already as we've literally not managed to come up with anything that doesn't already require the form to be saved so we can get the selection.
Thanks in advance for any assistance.
Answer: Not sure about the Javascript part since I am not sure what have written.
If you want to get the store id for a page - you can grab the page using its ID and check the array of store ids for a match.  In the case below, $page['store_id'] is an array and can contain multiple store ids.  Hope that helps.
<code>$pageId = 12;
$page = Mage::getModel('cms/page')->load($pageId);
$page_StoreIds = $page['store_id']
</code>


tudo que estou usando nesse site HTML + CSS + JS + PHP

Question: Estou tendo um problema com esse trabalho e gostaria de uma ajuda, gostaria de  salvar o que foi escrito sem recarregar a pagina após clicar no botão "salvar".
desculpa se isso ficou um pouco bagunçado, primeira vez usando isso.
conteudo_do_site.html(é só uma pagina vazia mas é importante ter ela!)

script.js

/********************************Mudança de pagina*****************************************/
function tableshowhide(a, b, c, d) { /**/
  len = menu.childElementCount; /**/
  closeall(); /**/
  for (i = 0; 1 < len; i++) { /**/
    menu.children[i].onclick = function() { /**/
      closeall(); /**/
      all.children[this.id].style.display = "block"; /**/
    } /**/
  } /**/
  function closeall() { /**/
    for (i = 0; i < all.childElementCount; i++) { /**/
      all.children[i].style.display = "none" /**/
    } /**/
  } /**/
  menu.children[c].click(); /**/
} /**/
tableshowhide("menu", "all", "pag1", "pag2") /**/
/***************************fim da Mudança de pagina***************************************/
style.css
* {
  top: 0px;
  padding: 0px;
}

body {
  margin-top: 0px;
  margin-left: 0px;
  float: left;
  background-color: #696969;
  animation: anim 6s infinite;
}

@keyframes anim {
  0% {
    background: #696969
  }
  30% {
    background: #808080
  }
  60% {
    background: #A9A9A9
  }
  80% {
    background: #808080
  }
  88% {
    background: #BDBDBD
  }
  100% {
    background: #696969
  }
}

.Pesquisa {
  position: absolute;
  margin-top: 160px;
  margin-left: 5px;
  width: 49px;
  height: 95px;
  background-color: #808080;
  border-radius: 7px;
  /*----inicio do movendo os botões de paginas----*/
  bottom: 0;
  transition: bottom 0.6s ease;
  /*----final do movendo os botões de paginas----*/
}

.mini-bloco {
  margin-top: 4px;
  margin-left: 2.5px;
  width: 43px;
  height: 42px;
  background-color: #BDBDBD;
  border-radius: 7px;
  border: none;
  color: white;
  font-size: 16px;
}

/*********************************conteudo1************************************/

.conteudo1 {
  /**/
  position: fixed;
  /**/
  margin-top: 5px;
  /**/
  margin-left: 100px;
  /**/
  background-color: #BDBDBD;
  /**/
  overflow: auto;
  /**/
  width: 1200px;
  /**/
  height: 618px;
  /**/
  border-radius: 7px;
  /**/
  border: 2px;
  /**/
}

/**/

/*********************************conteudo1************************************/

/*********************************conteudo2************************************/

.conteudo2 {
  /**/
  position: fixed;
  /**/
  margin-top: 5px;
  /**/
  margin-left: 100px;
  /**/
  background-color: #BDBDBD;
  /**/
  overflow: auto;
  /**/
  width: 1200px;
  /**/
  height: 618px;
  /**/
  border-radius: 7px;
  /**/
  border: 2px;
  /**/
}

/**/

/*********************************conteudo2************************************/

.oi {
  width: 100px;
  height: 20px;
  border-radius: 5px;
  border: 0px;
}
index.php

<?php
 ini_set('default_charset','UTF-8');
?>
  <?php
    if(!empty ( $_POST ['conteudo'])){
        file_put_contents("conteudo_do_site.html", $_POST ['conteudo']);
    }
    if (  !empty( $_FILES['arquivo']  )  ){

        move_uploaded_file( $_FILES["arquivo"]["tmp_name"], basename($_FILES["arquivo"]["name"])  );

    }
?>
    <!DOCTYPE html>

      <meta charset="utf-8" />
      <title>Olaaaaaaas</title>
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" type="text/css" media="screen" href="style.css" />

          <button id="pag1" class="mini-bloco">P1</button>
          <button id="pag2" class="mini-bloco">P2</button>

          <form action="" method="post" style="border-radius: 10px;">
            <textarea name="conteudo">
                 <?php  echo file_get_contents("conteudo_do_site.html"); ?>
             </textarea>

            <button class="oi" >Salvar</button>
          </form>

          <form action="" method="post" enctype="multipart/form-data">
            <input type="file" name="arquivo" id="arquivo">
            <input class="oi" value="Upload Image">
          </form>

            <?php   echo file_get_contents("conteudo_do_site.html"); ?>

Comment: Se o botão é do tipo `submit`, é esperado que ele submeta o formulário quando pressionado e isso faz com que a página seja "recarregada", visto que está submetendo o formulário para a própria página. O comportamento que descreveu condiz com o código que está utilizando, então sua pergunta não está suficientemente clara. Busque [edit] e esclarecer com mais detalhes o que está fazendo e elabore um [mcve] demonstrando o problema. Aproveite também para fazer o [tour], ler o guia de [ask] e acessar a [help].
Answer: Você precisará fazer um ajax request a um script que salve o content.
O seu php ficaria assim:
save.php:
<?php
   $data = $_POST['content'];
   file_put_content('conteudo_do_site', $data);
   echo 'salvo!';
?>

JS (Fiz com jQuery):
 $.ajax({
        type: "POST",
        url: "save.php",
        data: {'content': $("#content").val()},
        success: function (data) {
            alert(data);
        }
    });

HTML:
 <form action="javascript:sendForm();" method="post" style="border-radius: 10px;">
            <textarea id='content' name="conteudo">
                    <?php  echo file_get_contents("conteudo_do_site.html"); ?>
                </textarea>

           <button type='submit' class="oi" >Salvar</button>
          </form>


Predict number of Birthdays for 1000 person of same class in next 365 Days

Question: I want to know an approximate number of birthdays for a class where each month 1000 Persons are added up. Like 1st month its 1000, 2nd month its 2000, 3rd month it is 3000 And so on. Now lets say today is 1st Jan 2013, then upto  1st Jan 2014, How many birthdays we'll be having with our class in which every month 1000 persons are adding up so that upto 1st Jan 2014 We will be having 12000 Persons in our class. I want to calculate total number of birthdays from 1st jan 2013 to 1st Jan 2014.
Comment: Could you perhaps clarify what you are asking here? What is meant by "persons are added up"? Added to what and how? And do you want the number of *dates* that at least one person in the class has a birthday on or the number of *persons* having a birthday?
Answer: A person in the class in January has chance $1$ of having a birthday because he is in the class all year.  That gets you  $1000$ birthdays.  A person who arrives in February has $\frac{365-31}{365}$ chance of having his birthday in class, so that group will on average get you $915$ birthdays.  Keep going through the months and you will have your answer.
Slightly less accurately, because it ignores the differing numbers of days per month, you have on average $6500$ people in class, so you should have about $6500$ birthdays during the year.
I'm not sure this is at all what you are asking.  Is it?


Strange permission errors in new PostgreSQL installation

Question: A freshly installed PostgreSQL (with configuration overwritten) won't start:
$ sudo service postgresql start
 * Starting PostgreSQL 9.1 database server
 * Error: could not read /etc/postgresql/9.1/main/postgresql.conf: Permission denied

Looks like it should be able to read it though:
$ ls -l postgresql.conf
-rw------- 1 postgres postgres 19450 2012-06-14 10:07 postgresql.conf

But fine, I'll add chmod +r it to test if that works.
$ sudo chmod +r postgresql.conf
$ sudo service postgresql start
 * Starting PostgreSQL 9.1 database server
 * The PostgreSQL server failed to start. Please check the log output:
Error: Could not open log file /var/log/postgresql/postgresql-9.1-main.log

Huh?
$ ls -l /var/log/postgresql/
total 4
-rw-r----- 1 postgres adm 827 2012-06-14 10:07 postgresql-9.1-main.log

I don't get it. What can be wrong here? This used to work before.
Can I maybe monitor what process attempts to open the file?

It's Ubuntu 11.10 on EC2, using Chef. For completeness, here's the recipe:
# Install PostgreSQL
package "postgresql-9.1"

# Stop server
service "postgresql" do
    action :stop
end

# Overwrite configuration (setting data dir)
template "/etc/postgresql/9.1/main/postgresql.conf" do
    source "postgresql-conf.erb"
    owner "postgres"
    group "postgres"
end

# Start server
service "postgresql" do
    action :start
end

Comment: First, please do not go randomly shotgunning permissions - that's ***NOT*** how you fix something, it's how you create an even bigger mess.  Instead, proceed logically with troubleshooting: `Postgres can not read/write log files it used to (and should) have access to.`  Why?  Possible reasons: (1) Is the server tryng to start/run as the `postgres` user? (Check the startup scripts) ; Are there multiple users named `postgres` with different UIDs? (check `/etc/passwd`) ; etc…
Comment: @voretaq7 I know, that was just a quick fix to try to get it to work. Once it works, I have time to figure out why exactly it doesn't work.
Answer: The custom configuration file (postgresql.conf) pointed to a data directory that did not exist. Of course, that's a problem (which I solved by setting up the data directory), but it has nothing to do with the error printed. Once again, PostgreSQL errors not so helpful.
Update:
I got the same error when the data directory existed, but with incorrect ownership.


Don't understand why I'm getting a NameError for a variable

Question: I have a Tic Tac Toe game in Python, and right now its giving me a weird "Name Error". Here is the error:
NameError: name 'newspace' is not defined

Here is my code:
global newSpace
newSpace = " "

#Check for a win function:
def checkWin(player):
  if player == "X":
    newSpace = "" #
  else:
    newSpace = "" #
  if spaces[0] == player and spaces[1] == player and spaces[2] == player:
    spaces[0] = newspace
    spaces[1] = newspace
    spaces[2] = newspace
    return True
  if spaces[3] == player and spaces[4] == player and spaces[5] == player:
    spaces[3] = newspace
    spaces[4] = newspace
    spaces[5] = newspace
    return True
  if spaces[6] == player and spaces[7] == player and spaces[8] == player:
    spaces[6] = newspace
    spaces[7] = newspace
    spaces[8] = newspace
    return True
  if spaces[0] == player and spaces[3] == player and spaces[6] == player:
    spaces[0] = newspace
    spaces[3] = newspace
    spaces[6] = newspace
    return True
  if spaces[1] == player and spaces[4] == player and spaces[7] == player:
    spaces[1] = newspace
    spaces[4] = newspace
    spaces[7] = newspace
    return True
  if spaces[2] == player and spaces[5] == player and spaces[8] == player:
    spaces[2] = newspace
    spaces[5] = newspace
    spaces[8] = newspace
    return True
  if spaces[0] == player and spaces[4] == player and spaces[8] == player:
    spaces[0] = newspace
    spaces[4] = newspace
    spaces[8] = newspace
    return True
  if spaces[2] == player and spaces[4] == player and spaces[6] == player:
    spaces[2] = newspace
    spaces[4] = newspace
    spaces[6] = newspace
    return True
  return False

I know it's not the most efficient code, but i'm a beginner. In the top, I define newSpace and make it global, so I don't understand why it's giving me this error. Anyone know why? Thanks.
For reference, you can see my whole code here: https://repl.it/@LoveTheBears101/Tic-Tac-Toe. This is from line 1 - 67
Comment: Python is case-sensitive.
Comment: Do you even need a global variable for this? What is the purpose of the program, and this function?
Comment: What should I do to catch that error?
Comment: You need to put the `global newSpace` _inside_ the function. Where you have it does nothing. (This is in addition to spelling it properly).
Answer: Case-sensitivity: newspace != newSpace
Comment: Wow! Thanks for the quick response, I should probably be more careful. My finished project is here: https://tic-tac-toe.lovethebears101.repl.run/
Comment: @LoveTheBears101 - If you like this answer, press the Accept button!
Comment: This likely isn't the only problem.
Comment: I don't know if @martineau is referring to only the NameError, but I agree that the code seems to have many issues.
Answer: Just remove global newSpace, it is not required here, if the newSpace is not declared earlier.


Convert string lines to valid json format in Python

Question: Given a test.json file with content as follows:
{'review/appearance': 2.5, 'beer/style': 'Hefeweizen', 'review/palate': 1.5, 'review/taste': 1.5, 'beer/name': 'Sausa Weizen', 'review/timeUnix': 1234817823, 'beer/ABV': 5.0, 'beer/beerId': '47986', 'beer/brewerId': '10325', 'review/timeStruct': {'isdst': 0, 'mday': 16, 'hour': 20, 'min': 57, 'sec': 3, 'mon': 2, 'year': 2009, 'yday': 47, 'wday': 0}, 'review/overall': 1.5, 'review/text': 'A lot of foam. But a lot.\tIn the smell some banana, and then lactic and tart. Not a good start.\tQuite dark orange in color, with a lively carbonation (now visible, under the foam).\tAgain tending to lactic sourness.\tSame for the taste. With some yeast and banana.', 'user/profileName': 'stcules', 'review/aroma': 2.0}
{'review/appearance': 3.0, 'beer/style': 'English Strong Ale', 'review/palate': 3.0, 'review/taste': 3.0, 'beer/name': 'Red Moon', 'review/timeUnix': 1235915097, 'beer/ABV': 6.2, 'beer/beerId': '48213', 'beer/brewerId': '10325', 'review/timeStruct': {'isdst': 0, 'mday': 1, 'hour': 13, 'min': 44, 'sec': 57, 'mon': 3, 'year': 2009, 'yday': 60, 'wday': 6}, 'review/overall': 3.0, 'review/text': 'Dark red color, light beige foam, average.\tIn the smell malt and caramel, not really light.\tAgain malt and caramel in the taste, not bad in the end.\tMaybe a note of honey in teh back, and a light fruitiness.\tAverage body.\tIn the aftertaste a light bitterness, with the malt and red fruit.\tNothing exceptional, but not bad, drinkable beer.', 'user/profileName': 'stcules', 'review/aroma': 2.5}
{'review/appearance': 3.0, 'beer/style': 'Foreign / Export Stout', 'review/palate': 3.0, 'review/taste': 3.0, 'beer/name': 'Black Horse Black Beer', 'review/timeUnix': 1235916604, 'beer/ABV': 6.5, 'beer/beerId': '48215', 'beer/brewerId': '10325', 'review/timeStruct': {'isdst': 0, 'mday': 1, 'hour': 14, 'min': 10, 'sec': 4, 'mon': 3, 'year': 2009, 'yday': 60, 'wday': 6}, 'review/overall': 3.0, 'review/text': 'Almost totally black. Beige foam, quite compact, not bad.\tLight smell, just a bit of roast, and some hop. A bit too light.\tThe taste is light oo, and drinkable, with some malt, roast, hints of coffee.\tNothing exceptional, but after all drinkable and pleasant.\tLight to average body.\tIn the aftertaste some dust, somr roast, hint of caramel, and a bit of bitterness.\tNo defect, drinkable, not bad.', 'user/profileName': 'stcules', 'review/aroma': 2.5}
{'review/appearance': 3.5, 'beer/style': 'German Pilsener', 'review/palate': 2.5, 'review/taste': 3.0, 'beer/name': 'Sausa Pils', 'review/timeUnix': 1234725145, 'beer/ABV': 5.0, 'beer/beerId': '47969', 'beer/brewerId': '10325', 'review/timeStruct': {'isdst': 0, 'mday': 15, 'hour': 19, 'min': 12, 'sec': 25, 'mon': 2, 'year': 2009, 'yday': 46, 'wday': 6}, 'review/overall': 3.0, 'review/text': 'Golden yellow color. White, compact foam, quite creamy. Good appearance.\tFresh smell, with good hop. Quite dry, with a good grassy note. Hay. Fresh and pleasant.\tMore sweet in the mouth, with honey. The hop comes back in the end, and in the aftertaste.\tNot bad, but a bit too sweet for a pils.\tIn the end some vanilla and camomile note.\tIn the aftertaste, too. Though the hop, a bit too sweet.\tHonest.', 'user/profileName': 'stcules', 'review/aroma': 3.0}
{'review/appearance': 4.0, 'beer/style': 'American Double / Imperial IPA', 'review/palate': 4.0, 'review/taste': 4.5, 'beer/name': 'Cauldron DIPA', 'review/timeUnix': 1293735206, 'user/gender': 'Male', 'user/birthdayRaw': 'Jun 16, 1901', 'beer/ABV': 7.7, 'beer/beerId': '64883', 'user/birthdayUnix': -2163081600, 'beer/brewerId': '1075', 'review/timeStruct': {'isdst': 0, 'mday': 30, 'hour': 18, 'min': 53, 'sec': 26, 'mon': 12, 'year': 2010, 'yday': 364, 'wday': 3}, 'user/ageInSeconds': 3581417047, 'review/overall': 4.0, 'review/text': "According to the website, the style for the Caldera Cauldron changes every year. The current release is a DIPA, which frankly is the only cauldron I'm familiar with (it was an IPA/DIPA the last time I ordered a cauldron at the horsebrass several years back). In any event... at the Horse Brass yesterday.\t\tThe beer pours an orange copper color with good head retention and lacing. The nose is all hoppy IPA goodness, showcasing a huge aroma of dry citrus, pine and sandlewood. The flavor profile replicates the nose pretty closely in this West Coast all the way DIPA. This DIPA is not for the faint of heart and is a bit much even for a hophead like myslf. The finish is quite dry and hoppy, and there's barely enough sweet malt to balance and hold up the avalanche of hoppy bitterness in this beer. Mouthfeel is actually fairly light, with a long, persistentely bitter finish. Drinkability is good, with the alcohol barely noticeable in this well crafted beer. Still, this beer is so hugely hoppy/bitter, it's really hard for me to imagine ordering more than a single glass. Regardless, this is a very impressive beer from the folks at Caldera.", 'user/profileName': 'johnmichaelsen', 'review/aroma': 4.5}

How could I convert it to standard json format? Thanks.
My trial:
import json

with open('./test.json','r') as f:
    s = f.read()
    s = s.replace('\t','')
    s = s.replace('\n','')
    s = s.replace("\'", "\"")
    data = json.load(s)
    print(s)

Output:
AttributeError: 'str' object has no attribute 'read'

Expected result:
[{"review/appearance": 2.5, "beer/style": "Hefeweizen", "review/palate": 1.5, "review/taste": 1.5, "beer/name": "Sausa Weizen", "review/timeUnix": 1234817823, "beer/ABV": 5.0, "beer/beerId": "47986", "beer/brewerId": "10325", "review/timeStruct": {"isdst": 0, "mday": 16, "hour": 20, "min": 57, "sec": 3, "mon": 2, "year": 2009, "yday": 47, "wday": 0}, "review/overall": 1.5, "review/text": "A lot of foam. But a lot.\tIn the smell some banana, and then lactic and tart. Not a good start.\tQuite dark orange in color, with a lively carbonation (now visible, under the foam).\tAgain tending to lactic sourness.\tSame for the taste. With some yeast and banana.", "user/profileName": "stcules", "review/aroma": 2.0},
{"review/appearance": 3.0, "beer/style": "English Strong Ale", "review/palate": 3.0, "review/taste": 3.0, "beer/name": "Red Moon", "review/timeUnix": 1235915097, "beer/ABV": 6.2, "beer/beerId": "48213", "beer/brewerId": "10325", "review/timeStruct": {"isdst": 0, "mday": 1, "hour": 13, "min": 44, "sec": 57, "mon": 3, "year": 2009, "yday": 60, "wday": 6}, "review/overall": 3.0, "review/text": "Dark red color, light beige foam, average.\tIn the smell malt and caramel, not really light.\tAgain malt and caramel in the taste, not bad in the end.\tMaybe a note of honey in teh back, and a light fruitiness.\tAverage body.\tIn the aftertaste a light bitterness, with the malt and red fruit.\tNothing exceptional, but not bad, drinkable beer.", "user/profileName": "stcules", "review/aroma": 2.5},
{"review/appearance": 3.0, "beer/style": "Foreign / Export Stout", "review/palate": 3.0, "review/taste": 3.0, "beer/name": "Black Horse Black Beer", "review/timeUnix": 1235916604, "beer/ABV": 6.5, "beer/beerId": "48215", "beer/brewerId": "10325", "review/timeStruct": {"isdst": 0, "mday": 1, "hour": 14, "min": 10, "sec": 4, "mon": 3, "year": 2009, "yday": 60, "wday": 6}, "review/overall": 3.0, "review/text": "Almost totally black. Beige foam, quite compact, not bad.\tLight smell, just a bit of roast, and some hop. A bit too light.\tThe taste is light oo, and drinkable, with some malt, roast, hints of coffee.\tNothing exceptional, but after all drinkable and pleasant.\tLight to average body.\tIn the aftertaste some dust, somr roast, hint of caramel, and a bit of bitterness.\tNo defect, drinkable, not bad.", "user/profileName": "stcules", "review/aroma": 2.5},
{"review/appearance": 3.5, "beer/style": "German Pilsener", "review/palate": 2.5, "review/taste": 3.0, "beer/name": "Sausa Pils", "review/timeUnix": 1234725145, "beer/ABV": 5.0, "beer/beerId": "47969", "beer/brewerId": "10325", "review/timeStruct": {"isdst": 0, "mday": 15, "hour": 19, "min": 12, "sec": 25, "mon": 2, "year": 2009, "yday": 46, "wday": 6}, "review/overall": 3.0, "review/text": "Golden yellow color. White, compact foam, quite creamy. Good appearance.\tFresh smell, with good hop. Quite dry, with a good grassy note. Hay. Fresh and pleasant.\tMore sweet in the mouth, with honey. The hop comes back in the end, and in the aftertaste.\tNot bad, but a bit too sweet for a pils.\tIn the end some vanilla and camomile note.\tIn the aftertaste, too. Though the hop, a bit too sweet.\tHonest.", "user/profileName": "stcules", "review/aroma": 3.0},
{"review/appearance": 4.0, "beer/style": "American Double / Imperial IPA", "review/palate": 4.0, "review/taste": 4.5, "beer/name": "Cauldron DIPA", "review/timeUnix": 1293735206, "user/gender": "Male", "user/birthdayRaw": "Jun 16, 1901", "beer/ABV": 7.7, "beer/beerId": "64883", "user/birthdayUnix": -2163081600, "beer/brewerId": "1075", "review/timeStruct": {"isdst": 0, "mday": 30, "hour": 18, "min": 53, "sec": 26, "mon": 12, "year": 2010, "yday": 364, "wday": 3}, "user/ageInSeconds": 3581417047, "review/overall": 4.0, "review/text": "According to the website, the style for the Caldera Cauldron changes every year. The current release is a DIPA, which frankly is the only cauldron I'm familiar with (it was an IPA/DIPA the last time I ordered a cauldron at the horsebrass several years back). In any event... at the Horse Brass yesterday.\t\tThe beer pours an orange copper color with good head retention and lacing. The nose is all hoppy IPA goodness, showcasing a huge aroma of dry citrus, pine and sandlewood. The flavor profile replicates the nose pretty closely in this West Coast all the way DIPA. This DIPA is not for the faint of heart and is a bit much even for a hophead like myslf. The finish is quite dry and hoppy, and there's barely enough sweet malt to balance and hold up the avalanche of hoppy bitterness in this beer. Mouthfeel is actually fairly light, with a long, persistentely bitter finish. Drinkability is good, with the alcohol barely noticeable in this well crafted beer. Still, this beer is so hugely hoppy/bitter, it's really hard for me to imagine ordering more than a single glass. Regardless, this is a very impressive beer from the folks at Caldera.", "user/profileName": "johnmichaelsen", "review/aroma": 4.5}]

Comment: `ast.literal_eval` instead of `json.load`…?
Comment: are all those jsons in an array (`[]`)? Since otherwise, that file wouldn't be a valid `.json`. If they are in an array. Why not just use `json.load` directly?
Comment: I download the data from `https://cseweb.ucsd.edu/classes/fa20/cse258-a/data/beer_50000.json`, I don't know how to load it correctly after downloaded.
Comment: Please check the expected result I updated.
Answer: Use ast.literal_eval to read lines in to python dicts and convert to a valid json using json.dumps
import json
import ast

with open("./test.json", "r") as f:
    for line in f:
        print(json.dumps(ast.literal_eval(line)))

Output:
{"review/appearance": 2.5, "beer/style": "Hefeweizen", "review/palate": 1.5, "review/taste": 1.5, "beer/name": "Sausa Weizen", "review/timeUnix": 1234817823, "beer/ABV": 5.0, "beer/beerId": "47986", "beer/brewerId": "10325", "review/timeStruct": {"isdst": 0, "mday": 16, "hour": 20, "min": 57, "sec": 3, "mon": 2, "year": 2009, "yday": 47, "wday": 0}, "review/overall": 1.5, "review/text": "A lot of foam. But a lot.\tIn the smell some banana, and then lactic and tart. Not a good start.\tQuite dark orange in color, with a lively carbonation (now visible, under the foam).\tAgain tending to lactic sourness.\tSame for the taste. With some yeast and banana.", "user/profileName": "stcules", "review/aroma": 2.0}
{"review/appearance": 3.0, "beer/style": "English Strong Ale", "review/palate": 3.0, "review/taste": 3.0, "beer/name": "Red Moon", "review/timeUnix": 1235915097, "beer/ABV": 6.2, "beer/beerId": "48213", "beer/brewerId": "10325", "review/timeStruct": {"isdst": 0, "mday": 1, "hour": 13, "min": 44, "sec": 57, "mon": 3, "year": 2009, "yday": 60, "wday": 6}, "review/overall": 3.0, "review/text": "Dark red color, light beige foam, average.\tIn the smell malt and caramel, not really light.\tAgain malt and caramel in the taste, not bad in the end.\tMaybe a note of honey in teh back, and a light fruitiness.\tAverage body.\tIn the aftertaste a light bitterness, with the malt and red fruit.\tNothing exceptional, but not bad, drinkable beer.", "user/profileName": "stcules", "review/aroma": 2.5}
{"review/appearance": 3.0, "beer/style": "Foreign / Export Stout", "review/palate": 3.0, "review/taste": 3.0, "beer/name": "Black Horse Black Beer", "review/timeUnix": 1235916604, "beer/ABV": 6.5, "beer/beerId": "48215", "beer/brewerId": "10325", "review/timeStruct": {"isdst": 0, "mday": 1, "hour": 14, "min": 10, "sec": 4, "mon": 3, "year": 2009, "yday": 60, "wday": 6}, "review/overall": 3.0, "review/text": "Almost totally black. Beige foam, quite compact, not bad.\tLight smell, just a bit of roast, and some hop. A bit too light.\tThe taste is light oo, and drinkable, with some malt, roast, hints of coffee.\tNothing exceptional, but after all drinkable and pleasant.\tLight to average body.\tIn the aftertaste some dust, somr roast, hint of caramel, and a bit of bitterness.\tNo defect, drinkable, not bad.", "user/profileName": "stcules", "review/aroma": 2.5}
{"review/appearance": 3.5, "beer/style": "German Pilsener", "review/palate": 2.5, "review/taste": 3.0, "beer/name": "Sausa Pils", "review/timeUnix": 1234725145, "beer/ABV": 5.0, "beer/beerId": "47969", "beer/brewerId": "10325", "review/timeStruct": {"isdst": 0, "mday": 15, "hour": 19, "min": 12, "sec": 25, "mon": 2, "year": 2009, "yday": 46, "wday": 6}, "review/overall": 3.0, "review/text": "Golden yellow color. White, compact foam, quite creamy. Good appearance.\tFresh smell, with good hop. Quite dry, with a good grassy note. Hay. Fresh and pleasant.\tMore sweet in the mouth, with honey. The hop comes back in the end, and in the aftertaste.\tNot bad, but a bit too sweet for a pils.\tIn the end some vanilla and camomile note.\tIn the aftertaste, too. Though the hop, a bit too sweet.\tHonest.", "user/profileName": "stcules", "review/aroma": 3.0}
{"review/appearance": 4.0, "beer/style": "American Double / Imperial IPA", "review/palate": 4.0, "review/taste": 4.5, "beer/name": "Cauldron DIPA", "review/timeUnix": 1293735206, "user/gender": "Male", "user/birthdayRaw": "Jun 16, 1901", "beer/ABV": 7.7, "beer/beerId": "64883", "user/birthdayUnix": -2163081600, "beer/brewerId": "1075", "review/timeStruct": {"isdst": 0, "mday": 30, "hour": 18, "min": 53, "sec": 26, "mon": 12, "year": 2010, "yday": 364, "wday": 3}, "user/ageInSeconds": 3581417047, "review/overall": 4.0, "review/text": "According to the website, the style for the Caldera Cauldron changes every year. The current release is a DIPA, which frankly is the only cauldron I'm familiar with (it was an IPA/DIPA the last time I ordered a cauldron at the horsebrass several years back). In any event... at the Horse Brass yesterday.\t\tThe beer pours an orange copper color with good head retention and lacing. The nose is all hoppy IPA goodness, showcasing a huge aroma of dry citrus, pine and sandlewood. The flavor profile replicates the nose pretty closely in this West Coast all the way DIPA. This DIPA is not for the faint of heart and is a bit much even for a hophead like myslf. The finish is quite dry and hoppy, and there's barely enough sweet malt to balance and hold up the avalanche of hoppy bitterness in this beer. Mouthfeel is actually fairly light, with a long, persistentely bitter finish. Drinkability is good, with the alcohol barely noticeable in this well crafted beer. Still, this beer is so hugely hoppy/bitter, it's really hard for me to imagine ordering more than a single glass. Regardless, this is a very impressive beer from the folks at Caldera.", "user/profileName": "johnmichaelsen", "review/aroma": 4.5}

EDIT:
(Code for the updated question)
output = []
with open("./test.json", "r") as f:
    for line in f:
        output.append(ast.literal_eval(line))
print(json.dumps(output))

Output:
[{"review/appearance": 2.5, "beer/style": "Hefeweizen", "review/palate": 1.5, "review/taste": 1.5, "beer/name": "Sausa Weizen", "review/timeUnix": 1234817823, "beer/ABV": 5.0, "beer/beerId": "47986", "beer/brewerId": "10325", "review/timeStruct": {"isdst": 0, "mday": 16, "hour": 20, "min": 57, "sec": 3, "mon": 2, "year": 2009, "yday": 47, "wday": 0}, "review/overall": 1.5, "review/text": "A lot of foam. But a lot.\tIn the smell some banana, and then lactic and tart. Not a good start.\tQuite dark orange in color, with a lively carbonation (now visible, under the foam).\tAgain tending to lactic sourness.\tSame for the taste. With some yeast and banana.", "user/profileName": "stcules", "review/aroma": 2.0}, {"review/appearance": 3.0, "beer/style": "English Strong Ale", "review/palate": 3.0, "review/taste": 3.0, "beer/name": "Red Moon", "review/timeUnix": 1235915097, "beer/ABV": 6.2, "beer/beerId": "48213", "beer/brewerId": "10325", "review/timeStruct": {"isdst": 0, "mday": 1, "hour": 13, "min": 44, "sec": 57, "mon": 3, "year": 2009, "yday": 60, "wday": 6}, "review/overall": 3.0, "review/text": "Dark red color, light beige foam, average.\tIn the smell malt and caramel, not really light.\tAgain malt and caramel in the taste, not bad in the end.\tMaybe a note of honey in teh back, and a light fruitiness.\tAverage body.\tIn the aftertaste a light bitterness, with the malt and red fruit.\tNothing exceptional, but not bad, drinkable beer.", "user/profileName": "stcules", "review/aroma": 2.5}, {"review/appearance": 3.0, "beer/style": "Foreign / Export Stout", "review/palate": 3.0, "review/taste": 3.0, "beer/name": "Black Horse Black Beer", "review/timeUnix": 1235916604, "beer/ABV": 6.5, "beer/beerId": "48215", "beer/brewerId": "10325", "review/timeStruct": {"isdst": 0, "mday": 1, "hour": 14, "min": 10, "sec": 4, "mon": 3, "year": 2009, "yday": 60, "wday": 6}, "review/overall": 3.0, "review/text": "Almost totally black. Beige foam, quite compact, not bad.\tLight smell, just a bit of roast, and some hop. A bit too light.\tThe taste is light oo, and drinkable, with some malt, roast, hints of coffee.\tNothing exceptional, but after all drinkable and pleasant.\tLight to average body.\tIn the aftertaste some dust, somr roast, hint of caramel, and a bit of bitterness.\tNo defect, drinkable, not bad.", "user/profileName": "stcules", "review/aroma": 2.5}, {"review/appearance": 3.5, "beer/style": "German Pilsener", "review/palate": 2.5, "review/taste": 3.0, "beer/name": "Sausa Pils", "review/timeUnix": 1234725145, "beer/ABV": 5.0, "beer/beerId": "47969", "beer/brewerId": "10325", "review/timeStruct": {"isdst": 0, "mday": 15, "hour": 19, "min": 12, "sec": 25, "mon": 2, "year": 2009, "yday": 46, "wday": 6}, "review/overall": 3.0, "review/text": "Golden yellow color. White, compact foam, quite creamy. Good appearance.\tFresh smell, with good hop. Quite dry, with a good grassy note. Hay. Fresh and pleasant.\tMore sweet in the mouth, with honey. The hop comes back in the end, and in the aftertaste.\tNot bad, but a bit too sweet for a pils.\tIn the end some vanilla and camomile note.\tIn the aftertaste, too. Though the hop, a bit too sweet.\tHonest.", "user/profileName": "stcules", "review/aroma": 3.0}, {"review/appearance": 4.0, "beer/style": "American Double / Imperial IPA", "review/palate": 4.0, "review/taste": 4.5, "beer/name": "Cauldron DIPA", "review/timeUnix": 1293735206, "user/gender": "Male", "user/birthdayRaw": "Jun 16, 1901", "beer/ABV": 7.7, "beer/beerId": "64883", "user/birthdayUnix": -2163081600, "beer/brewerId": "1075", "review/timeStruct": {"isdst": 0, "mday": 30, "hour": 18, "min": 53, "sec": 26, "mon": 12, "year": 2010, "yday": 364, "wday": 3}, "user/ageInSeconds": 3581417047, "review/overall": 4.0, "review/text": "According to the website, the style for the Caldera Cauldron changes every year. The current release is a DIPA, which frankly is the only cauldron I'm familiar with (it was an IPA/DIPA the last time I ordered a cauldron at the horsebrass several years back). In any event... at the Horse Brass yesterday.\t\tThe beer pours an orange copper color with good head retention and lacing. The nose is all hoppy IPA goodness, showcasing a huge aroma of dry citrus, pine and sandlewood. The flavor profile replicates the nose pretty closely in this West Coast all the way DIPA. This DIPA is not for the faint of heart and is a bit much even for a hophead like myslf. The finish is quite dry and hoppy, and there's barely enough sweet malt to balance and hold up the avalanche of hoppy bitterness in this beer. Mouthfeel is actually fairly light, with a long, persistentely bitter finish. Drinkability is good, with the alcohol barely noticeable in this well crafted beer. Still, this beer is so hugely hoppy/bitter, it's really hard for me to imagine ordering more than a single glass. Regardless, this is a very impressive beer from the folks at Caldera.", "user/profileName": "johnmichaelsen", "review/aroma": 4.5}]

Output is a valid json, you can check here: https://jsonlint.com/.
Comment: @ahbon yes they are different. Data in your filie is not valid json, even if we consider individual lines, but there is scope to convert those individual lines back to valid json. My answer converts each line to a valid json format string as asked in the question. You can see difference of `"` and `\t` in data. Spec for json format: https://tools.ietf.org/html/rfc7159
Comment: @ahbon You seem to have edited question later. Cool, I will change my answer accordingly.
Comment: Thanks, does this is different from `with open('./test.json','r') as f: print(f.read())`?
Comment: Thanks but I think the output from your answer is still different from the expected result I posted in the question. Could you help to convert the orignal data to it? You may find the full data here: https://cseweb.ucsd.edu/classes/fa20/cse258-a/data/beer_50000.json
Answer: Why don't you just load it in the first place and then do whatever you want to it?
something like this
import json

with open('./test.json','r') as f:
    data = json.load(f)
    s = data.replace('\t','')
    s = s.replace('\n','')
    s = s.replace("\'", "\"")

    print(s)

Comment: I get `JSONDecodeError: Expecting property name enclosed in double quotes`.
Answer: The issue is that you're using json.load on an str object (s). load expects a file object that supports read. Notice that s is a string, the result of f.read.
If you want to use json.load, you need to feed f into it. If you want to load the json from a string, use json.loads
data = json.loads(s)
print(data)

You were also trying to print s for whatever reason. Even though the result json is in data.
Comment: Sorry, it raises an error: `JSONDecodeError: Extra data`


Why is the menubar method not working in following code?

Question: Here is my code which doesn't work
import tkinter as tk

class english_to_ubbidubbi:

    def __init__(self,master):
        self.master=master
        self.master.title("Ubbi Dubbi")

        menubar=tk.Menu(self.master)
        file = tk.Menu(menubar, tearoff = 0)
        menubar.add_cascade(label ='Exit', menu = file)
        file.add_separator()
        file.add_command(label ='Exit', command = self.master.destroy)

        self.frame1=tk.Frame(self.master)
        tk.Label(self.frame1,text='Hello There').grid(row=0,column=0)
        self.frame1.grid(row=1,column=0)

win=tk.Tk()
app=english_to_ubbidubbi(win)
win.mainloop()

Above produces a widget without menu bar, whereas the code below works fine

import tkinter  as tk

root = tk.Tk()
root.title('Ubbi Dubbi')

menubar = tk.Menu(root)

file = tk.Menu(menubar, tearoff = 0)
menubar.add_cascade(label ='File', menu = file)

file.add_separator()
file.add_command(label ='Exit', command = root.destroy)

root.config(menu = menubar)
root.mainloop()

What am I doing wrong here
....................................................................................................................................................................................................................................................................................................................................................................................................................................
Answer: You didn't use .config(menu=menubar) in the first example, use:
class english_to_ubbidubbi:

    def __init__(self, master):
        self.master = master
        self.master.title("Ubbi Dubbi")

        menubar = tk.Menu(self.master)
        file = tk.Menu(menubar, tearoff=0)
        menubar.add_cascade(label='Exit', menu=file)
        file.add_separator()
        file.add_command(label='Exit', command=self.master.destroy)

        self.master.config(menu=menubar)

        self.frame1 = tk.Frame(self.master)
        tk.Label(self.frame1, text='Hello There').grid(row=0, column=0)
        self.frame1.grid(row=1, column=0)

Or:
class english_to_ubbidubbi:

    def __init__(self, master):
        self.master = master
        self.master.title("Ubbi Dubbi")

        menubar = tk.Menu(self.master)
        file = tk.Menu(menubar, tearoff=0)
        menubar.add_cascade(label='Exit', menu=file)
        file.add_separator()
        file.add_command(label='Exit', command=self.master.destroy)

        win.config(menu=menubar)

        self.frame1 = tk.Frame(self.master)
        tk.Label(self.frame1, text='Hello There').grid(row=0, column=0)
        self.frame1.grid(row=1, column=0)


Connect to virtual Robot via QiMessaging JavaScript

Question: I would like to test my Javascript application locally.
Therefore i would like to establish a connection between my JavaScript Application with QiMessaging to a virtual robot.
Has anybody done this before?
Is this even possible?
As virtual robot I tried naoqi-bin.exe and opennao vm on my windows 10 system.
It works fine with a real Robot (Pepper) by connecting to a virtual robot didnt work.
Here are my attempts:

qimessaging 1.0:
code:
<!DOCTYPE html>

    <meta charset="utf-8"/>

result:
Broweser Console shows:

404 Not Found
  http://127.0.0.1/libs/qimessaging/1.0/socket.io/1/?t=1557305266224
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
  the remote resource at http://127.0.0.1/libs/qimessaging/1.0/socket.io/1/?t=1557305266224 Reson: Reason: CORS header 'Access-Control-Allow-Origin' missing

qimessaging 2.0:
code:
<!DOCTYPE html>

    <meta charset="utf-8"/>

result:
same as with qimessaging 1.0

robotutils:
code:
<!DOCTYPE html>

  <meta charset="utf-8"/>

result:

GET http://127.0.0.1/libs/qimessaging/2/qimessaging.js 404 Not Found
The script from "http://127.0.0.1/libs/qimessaging/2/qimessaging.js"
  was loaded even though its MIME type ("text/html") is not a valid
  JavaScript MIME type.
Loading failed for the  with source
  "http://127.0.0.1/libs/qimessaging/2/qimessaging.js".

So my interpretationis that the virtual robot does not serve the required files or am i missing something here?
Answer: Ok i found the answer in a the aldebaran forum

[...]
Sorry, but qimessaging javascript won't work with a virtual
robot, only with a real robot (on a real robot there's a server
listening to a certain port for qimessaging js communication, there's
no such server running for a virtual robot).
[...]


RMO inequality problem

Question: If $a,b,c,d,e>1$, then prove that:
$$\frac{a^2}{b-1} + \frac{b^2}{c-1} + \frac{d^2}{e-1} + \frac{c^2}{a-1} + \frac{e^2}{d-1} \ge 20. $$
I don't know how to begin. What should be the approach?
Comment: Hint: let $a=a'+1,b=b'+1,\ldots$.
Comment: Wouldn't that make it more complicated
Comment: No. It's a standard technique. Often we deal with inequalities whose variables are positive reals, but this problem is a little different. In order to apply the standard inequalities (like C-S, AM-GM), it's natural to substitute like that.
Answer: Note that $x^2-4(x-1) = (x-2)^2\ge 0$ for all $x\in\mathbb{R}$, and hence $x^2\ge 4(x-1)$ for all $x\in\mathbb{R}$. As such, we have
$$ \frac{a^2}{b-1} + \frac{b^2}{c-1} + \frac{d^2}{e-1} + \frac{c^2}{a-1} + \frac{e^2}{d-1} \ge 4\left(\frac{a-1}{b-1} + \frac{b-1}{c-1} + \frac{c-1}{a-1} + \frac{d-1}{e-1} + \frac{e-1}{d-1}\right). $$
So it suffices to show
$$\frac{a-1}{b-1} + \frac{b-1}{c-1} + \frac{c-1}{a-1} + \frac{d-1}{e-1} + \frac{e-1}{d-1}\ge 5.$$
Can you see how to finish?
Comment: This is better than the accept answer.
Comment: @TahaAkbari I would rather say that both the answers are looking at the same thing with a different perspective. While this answer makes it look short and quick, the accepted answer gives an insight on how one can not only solve this problem, but also get at other problems.
Answer: Note that we can rewrite your expression as
$$ \left( \frac{a^2}{b-1} + \frac{b^2}{c-1} + \frac{c^2}{a-1} \right) + \left( \frac{d^2}{e-1} + \frac{e^2}{d-1} \right) \geq 20. $$
Let us consider first the baby problem of finding the minimum value of $f(x) = \frac{x^2}{x-1}$ assuming $x > 1$. The minimum is readily seen to be attained at $x = 2$ with value $4$.
Next, consider the problem of finding the minimum value of
$$ \frac{d^2}{e-1} + \frac{e^2}{d-1} =  f(d) \frac{d-1}{e-1} + f(e) \frac{e-1}{d-1} $$
assuming $d,e > 1$. The arithmetic-geometric inequality shows that
$$ f(d) \frac{d-1}{e-1} + f(e) \frac{e-1}{d-1} \geq 2 \sqrt{f(d)f(e)} \geq 2f(2) = 8 $$
where the minimum value of $8$ is indeed attained when $d = e = 2$.
Finally, consider the problem of finding the minimum value of
$$ \frac{a^2}{b-1} + \frac{b^2}{c-1} + \frac{c^2}{a-1} = f(a)\frac{a-1}{b-1} + f(b)\frac{b-1}{c-1} + f(c)\frac{c-1}{a-1} $$
assuming $a,b,c > 1$. Again, the arithmetic-geometric inequality shows that
$$ f(a)\frac{a-1}{b-1} + f(b)\frac{b-1}{c-1} + f(c)\frac{c-1}{a-1} \geq 3 (f(a)f(b)f(c))^{\frac{1}{3}} \geq 3f(2) = 12 $$
where the minimum indeed attained at $a = b = c = 2$.
Combining everything above, we obtain the required result.
Comment: @user115962 You can never be sure, but the thing that jumped to my mind was the fact that your problem seems to split into two "smaller" independent problems which have less variables and so seem easier. I was taught to always try and solve the most trivial instance of a problem first and so I decided to check the one variable case and see if it can be used to solve the general case. I think the most important part in solving this problem is identifying the role of the expression $\frac{x^2}{x-1}$ and the inequality $\frac{x^2}{x-1} \geq 4$.
Comment: The splitting into independent problems is the decomposition of the permutation (used in the rearrangement inequality) into disjoint cycles.
Comment: Question: how did you figure out that this approach would lead to the result needed? Whenever I try, I'm clouded by various possibilities in which it could be started. And the thing   I feel is that my try would be one of many and so it might just lead to making it all more complicated. How do you get confident of your approach ?
Comment: I mean, you took a calculus approach. Somebody else took an algebraic approach. How am I to know which path to take? How am I to surmise which one goes the right way?
Comment: @user115962 On what level are you? A college student using inequalities to solve problems or a high school student trying to solve olympiad inequalities? If it's the latter, then I would say that algebraic approaches are definitely the path you should take.
Comment: BTW, there is no calculus involved in my solution. You can deduce the inequality $\frac{x^2}{x-1} \geq 4$ using calculus but also algebraically. No matter how you do it, the solution from that point on involves only the AG-inequality.
Comment: @levap  Nicely Done! The solution illustrates wonderfully how one can consider a simpler problem to solve a more "complicated" and "intimidating" problem. :)
Answer: Using Cauchy-Scwarz to
\begin{align*}
\frac{a_1}{\sqrt{x_1}}, \frac{a_2}{\sqrt{x_2}}, \ldots, \frac{a_n}{\sqrt{x_n}} \\
\sqrt{x_1}, \sqrt{x_2}, \ldots, \sqrt{x_n}
\end{align*}
we get
\begin{align*}
\frac{a_1^2}{x_1}+\frac{a_2^2}{x_2}+\cdots + \frac{a_n^2}{x_n} \geq \frac{(a_1+a_2+\cdots + a_n)^2}{x_1+x_2+\cdots+x_n}
\end{align*}
Hence we have
\begin{align*}
\frac{a^2}{b-1}+\frac{b^2}{c-1}+\frac{d^2}{e-1}+\frac{c^2}{a-1}+\frac{e^2}{d-1} \geq \frac{(a+b+c+d+e)^2}{a+b+c+d+e-5}
\end{align*}
Putting $x=a+b+c+d+e$, we need to prove
\begin{align*}
\frac{x^2}{x-5} \geq 20
\end{align*}Since $x > 5$, this can be written as  $x^2 -20x + 100 \geq 0$. This follows readily since
\begin{align*} x^2-20x+100 = (x-10)^2\end{align*}
The proof also shows that the numerators can be any permutation of $a^2,b^2,c^2,d^2,e^2$
Comment: This is also called Titu's lemma for the record :)
Answer: The functions $x^2$ and $(x-1)$ are both increasing in $x$.  Therefore, by the rearrangement inequality, the sum is $ \geq \sum \frac{a^2}{a-1}$ which is easier to control, in fact each term of this sum is $\geq 4$.
Answer: By Cauchy Schwarz, $($given expression$)(a+b+c+d+e-5)\geq(a+b+c+d+e)^2$
Now this shows $($given expression$)\geq \dfrac{(a+b+c+d+e)^2}{a+b+c+d+e-5}$
Now $(a+b+c+d+e)^2=(a+b+c+d+e-5)^2+2\times(a+b+c+d+e-5)\times 5+25$ hence on division by $a+b+c+d+e-5$ we get $a+b+c+d+e-5+10+\dfrac{25}{a+b+c+d+e-5}=(a+b+c+d+e-5)+\dfrac{25}{a+b+c+d+e-5}+10$
Letting $x=a+b+c+d+e-5$ we note $x\geq0$ and the above is $x+\dfrac{25}{x}+10\geq 10+10=20$ by AM-GM.

RMO inequality problem