text:
Q: Prestashop 1.7 Customer Password Encryption? I made some third party system based with php for Prestashop 1.6. It works with connecting directly the Prestashop Database. And know Im upgraded my Presta to 1.7.5.1 and IT WORKS. Only It dont log in customers anymore because as I can see Password encryption is changed. I was using md5(COOKIE_KEY.'password') for 1.6, but I see the passwords on 1.7 nothing like md5. Could you tell me how encryption is. (it become much better if you tell me with php code)
Prestashop 1.7.5.1
$2y$10$6b460aRLklgWblz75NAMteYXLJwjfV6a/uN8GJKgJgPDBuNhHs.ym
for 123456

A: PrestaShop 1.7.x now uses bcrypt as the preferred hash method (md5 is still supported though).
To better understand the behavior between PrestaShop v1.6.x vs 1.7.x for checking passwords, let's have a look at the getByEmail() method in the Customer class:
/**
  * Return customer instance from its e-mail (optionally check password).
  *
  * @param string $email e-mail
  * @param string $plaintextPassword Password is also checked if specified
  * @param bool $ignoreGuest
  *
  * @return bool|Customer|CustomerCore Customer instance
 */
 public function getByEmail($email, $plaintextPassword = null, $ignoreGuest = true)

If $plaintextPassword is provided the encrypted version of the password is retrieved with:
$this->passwd = $crypto->hash($plaintextPassword);

The Hashing class can be instancied by doing:
$crypto = ServiceLocator::get('\\PrestaShop\\PrestaShop\\Core\\Crypto\\Hashing');

Solution for your example using PrestaShop 1.7 classes/methods:
<?php

namespace PrestaShop\PrestaShop\Core\Crypto;
include('config/config.inc.php');

$plaintextPassword = '123456';
$crypto = new Hashing;
$encryptedPassword = $crypto->hash($plaintextPassword, _COOKIE_KEY_);

echo 'Clear: '.$plaintextPassword.'<br />Encrypted: '.$encryptedPassword;

/* Result (example)
Clear: 123456
Encrypted: $2y$10$6b460aRLklgWblz75NAMteYXLJwjfV6a/uN8GJKgJgPDBuNhHs.ym */

Alternate solution, without the need to include any PrestaShop files/methods:
<?php

$plaintextPassword = '123456';
$encryptedPassword = password_hash($plaintextPassword, PASSWORD_BCRYPT);
echo var_dump(password_verify($plaintextPassword, $encryptedPassword)); // True if encryption is matching

I hope this helps.


text:
Q: Mesos DCOS doesn't install Kafka I'm trying to install Kafka on Mesos. Installation seems to have succeeded.
vagrant@DevNode:/dcos$ dcos package install kafka
This will install Apache Kafka DCOS Service.
Continue installing? [yes/no] yes
Installing Marathon app for package [kafka] version [0.9.4.0]
Installing CLI subcommand for package [kafka] version [0.9.4.0]
New command available: dcos kafka
The Apache Kafka DCOS Service is installed:
  docs   - https://github.com/mesos/kafka
  issues - https://github.com/mesos/kafka/issues

vagrant@DevNode:/dcos$ dcos package list
NAME   VERSION  APP     COMMAND  DESCRIPTION
kafka  0.9.4.0  /kafka  kafka    Apache Kafka running on top of Apache Mesos

But kafka task is not started.
vagrant@DevNode:/dcos$ dcos kafka
Error: Kafka is not running
vagrant@DevNode:/dcos$

Marathon UI says service is waiting. Looks like it is not accepting resource that was allocated to it. More logs here.
Mar 23 03:52:59 ip-10-0-4-194.ec2.internal java[1425]: [2016-03-23 03:52:59,335] INFO Offer ID: [54f71504-b37a-4954-b082-e1f2a04b7fa4-O77]. Considered resources with roles: [*]. Not all basic resources satisfied: cpu not in offer, disk SATISFIED (0.0 <= 0.0), mem not in offer (mesosphere.mesos.ResourceMatcher$:marathon-akka.actor.default-dispatcher-11)
Mar 23 03:52:59 ip-10-0-4-194.ec2.internal java[1425]: [2016-03-23 03:52:59,370] INFO Offer [54f71504-b37a-4954-b082-e1f2a04b7fa4-O77]. Insufficient resources for [/kafka] (need cpus=0.5, mem=307.0, disk=0.0, ports=(1 dynamic), available in offer: [id { value: "54f71504-b37a-4954-b082-e1f2a04b7fa4-O77" } framework_id { value: "54f71504-b37a-4954-b082-e1f2a04b7fa4-0000" } slave_id { value: "54f71504-b37a-4954-b082-e1f2a04b7fa4-S1" } hostname: "10.0.4.190" resources { name: "ports" type: RANGES ranges { range { begin: 1 end: 21 } range { begin: 23 end: 5050 } range { begin: 5052 end: 32000 } } role: "slave_public" } resources { name: "cpus" type: SCALAR scalar { value: 4.0 } role: "slave_public" } resources { name: "mem" type: SCALAR scalar { value: 14019.0 } role: "slave_public" } resources { name: "disk" type: SCALAR scalar { value: 32541.0 } role: "slave_public" } attributes { name: "public_ip" type: TEXT text { value: "true" } } url { scheme: "http" address { hostname: "10.0.4.190" ip: "10.0.4.190" port: 5051 } path: "/slave(1)" }] (mesosphere.mesos.TaskBuilder:marathon-akka.actor.default-dispatcher-11)

Mesos master logs..
Mar 23 15:38:22 ip-10-0-4-194.ec2.internal mesos-master[1371]: I0323 15:38:22.339759  1376 master.cpp:5350] Sending 2 offers to framework 54f71504-b37a-4954-b082-e1f2a04b7fa4-0000 (marathon) at scheduler-f86b567c-de59-4891-916b-fb00c7959a09@10.0.4.194:60450
Mar 23 15:38:22 ip-10-0-4-194.ec2.internal mesos-master[1371]: I0323 15:38:22.341790  1381 master.cpp:3673] Processing DECLINE call for offers: [ 54f71504-b37a-4954-b082-e1f2a04b7fa4-O373 ] for framework 54f71504-b37a-4954-b082-e1f2a04b7fa4-0000 (marathon) at scheduler-f86b567c-de59-4891-916b-fb00c7959a09@10.0.4.194:60450
Mar 23 15:38:22 ip-10-0-4-194.ec2.internal mesos-master[1371]: I0323 15:38:22.342041  1381 master.cpp:3673] Processing DECLINE call for offers: [ 54f71504-b37a-4954-b082-e1f2a04b7fa4-O374 ] for framework 54f71504-b37a-4954-b082-e1f2a04b7fa4-0000 (marathon) at scheduler-f86b567c-de59-4891-916b-fb00c7959a09@10.0.4.194:60450

No sure why marathon didn't like that offer. I'm fairly sure there is enough resource.

A: Marathon is waiting for an Offer with enough resources for the Kafka scheduler. The offers it is rejecting appear not to have any cpu or memory. The Offer you see which does have sufficient resources is already statically reserved for the Role "slave_public".
The Kafka scheduler will be running with the Role *. Your cluster lacks sufficient resources in the default Role *. This is the role associated with private agents
You should go look at mesos/state and look at the available Resources on agents with the "*" role.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Material-UI Switch status is not being updated from DB value The Material-ui Switch is not updating when the firebase value is updated.
I posted just a part of the code here, the full Demo is available on CodeSandbox.
The project is connected to firebase and using depenedncies as: react-redux-firebase, redux-firestore, etc, you can find all details in the Demo.
CodeSandobox Demo
import React, { Component } from "react";
import styled from "styled-components";
import { connect } from "react-redux";
import { firestoreConnect } from "react-redux-firebase";
import { compose } from "redux";
import Switch from "@material-ui/core/Switch";

import { toggleStatus } from "../actions/statusActions";

const Wrapper = styled.div`
  padding-top: 50px;
`;

const OnOff = styled.span`
  ${props => `color: ${props.color}`};
`;

class Header extends Component {
  hanldeToggleStats = () => {
    const { status } = this.props;
    const dbStatus = status && status[0].status;
    this.props.toggleStatus(dbStatus);
  };

  render() {
    const { status } = this.props;
    const dbStatus = status && status[0].status;
    console.log("dbStatus:", dbStatus);

    return (
      <Wrapper>
        <div>
          Change status, refresh the page, observe difference between labels and
          Switch
        </div>
        <OnOff color={dbStatus ? "#BDBDBD" : "#7AC943"}>Off</OnOff>
        <Switch
          checked={dbStatus}
          onChange={this.hanldeToggleStats}
          color="primary"
        />
        <OnOff color={dbStatus ? "#7AC943" : "#BDBDBD"}>On</OnOff>
      </Wrapper>
    );
  }
}

const mapStateToProps = state => {
  return {
    status: state.firestore.ordered.status //this returns true
  };
};

const mapDispatchToProps = dispatch => {
  return {
    toggleStatus: status => dispatch(toggleStatus(status))
  };
};

export default compose(
  connect(
    mapStateToProps,
    mapDispatchToProps
  ),
  firestoreConnect([
    { collection: "status", limit: 1, orderBy: ["createdAt", "desc"] }
  ])
)(Header);

A: const dbStatus = Boolean(status && status[0].status);
const dbStatus = status && status[0].status; can result in dbStatus being undefined upon which the component is considered uncontrolled. Once it gets defined you should get a warning.


text:
Q: Avoid including bootstrap min.css & .css with wiredep I'm writing a script with wiredep & gulp but I have a an unexpected result at the the end when I include Bootstrap:
<link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap-theme.css" />
<link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap-theme.min.css" />
<link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap.css" />
<link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap.min.css" />

Why wiredep is including both .css & min.css files? And why bootstrap-theme is also included?
Thanks

A: The problem came from a bad override in my bower.json:
Before it was:
"overrides": {
    "bootstrap": {
        "main": [
            "dist/js/*.*",
            "dist/css/*.*",
            "dist/fonts/*.*"
        ]
    }

Fixed one is:
"overrides": {
    "bootstrap": {
        "main": [
            "dist/js/bootstrap.js",
            "dist/css/bootstrap.css",
            "dist/fonts/*.*"
        ]
    }

This overrides is needed for 3.3.5 and should not be needed anymore with 3.3.6.

A: I use bindep instead wiredep. It is more professional , with many features but above all it permits to overcome the bower limits using bower.
npm install bindep


text:
Q: comparing columns of two dataframes and get the deviation point in R I have 2 dataframes:
> dput(DF1)
    structure(c("a", "b", "c", "d", "e", "f", "g"), .Dim = c(1L,
    7L), .Dimnames = list("1", c("seq1", "seq2", "seq3", "seq4",
    "seq5", "seq6", "seq7")))

> dput(DF2)
    structure(list(seq1 = c("a", "a", "a", "a", "a"), seq2 = c("b",
    "d", "d", "d", "b"), seq3 = c("c", "c", "c", "c", "c"), seq4 = c("e",
    "e", "d", "d", "d"), seq5 = c("f", "f", "f", "g", "e"), seq6 = c("g",
    "g", "g", "g", "g"), seq7 = c("g", "g", "g", "g", "g"), UserId = c("1",
    "2", "3", "4", "5")), .Names = c("seq1", "seq2", "seq3", "seq4",
    "seq5", "seq6", "seq7", "UserId"), row.names = c(NA, -5L), class = "data.frame")

These are the above two datasets which I want to compare for e.g User1 in DF2 has deviated to e ( instead of goind to d, he went to e). DF1 is my correct defined sequence.
    So in the end i need to make a dataframe the below requirements:
> dput(required_dataframe)
structure(list(UserID = c("1", "2", "3", "4", "5"), Deviation = c("e",
"d", "d", "d", "g"), Actual_sequence = c("d", "b", "b", "b",
"f")), .Names = c("UserID", "Deviation", "Actual_sequence"), row.names = c(NA,
-5L), class = "data.frame")

For an instance that user1 deviated to point e (it should have gone to d). So for all users I need to calculate the deviation point along with the actual seq.
 Please find the attached images of DF1 ,DF2 and the required dataframe as well.
DF1
DF2
Required_dataframe

A: Once you get the two matrices to line up perfectly, you can compare them row-by-row and find out where they don't match. You can then find the first value in each row and use that as a selection:
sel <- cbind(
  seq_len(nrow(DF2)),
  max.col(t(t(DF2[seq_along(DF1)]) != c(DF1)), "first")
)
cbind(DF2["UserId"], Deviation=DF2[sel], Actual=DF1[sel[,2]])

#  UserId Deviation Actual
#1      1         e      d
#2      2         d      b
#3      3         d      b
#4      4         d      b
#5      5         g      f

The core of the comparison is this part, where you can see each cell being lined up:
t(DF2[seq_along(DF1)]) != c(DF1)

#      [,1]  [,2]  [,3]  [,4]  [,5]
#seq1 FALSE FALSE FALSE FALSE FALSE
#seq2 FALSE  TRUE  TRUE  TRUE FALSE
#seq3 FALSE FALSE FALSE FALSE FALSE
#seq4  TRUE  TRUE FALSE FALSE FALSE
#seq5  TRUE  TRUE  TRUE  TRUE FALSE
#seq6  TRUE  TRUE  TRUE  TRUE  TRUE
#seq7 FALSE FALSE FALSE FALSE FALSE


text:
Q: Numerically solving a 3-dimensional partial differential equation with third order spatial derivatives I am trying to numerically solve (and eventually plot evolving through time) the following differential equation
$\frac{\partial  f(x,y,t)}{\partial t} = i C_{0}\left(\frac{\partial^{2}f(x,y,t)}{\partial x^{2}} - \frac{\partial^{2}f(x,y,t)}{\partial y^{2}} \right) \\
- C_{1}\left( x - y\right) \left(\frac{\partial f(x,y,t)}{\partial x}  -  \frac{\partial f(x,y,t)}{\partial y} \right) \\
- C_{2}\left( x - y \right)^{2}f(x,y,t) \\
 + iC_{3}(x-y)\left(\frac{\partial^{3}f(x,y,t)}{\partial x^{3}} - \frac{\partial^{3}f(x,y,t)}{\partial y \partial x^{2}} - \frac{\partial^{3}f(x,y,t)}{\partial x \partial y^{2}} + \frac{\partial^{3}f(x,y,t)}{\partial y^{3}} \right) \\
 - C_{4} \left( x - y\right)^{2} \left(\frac{\partial^{2} f(x,y,t)}{\partial x^{2}} - 2\frac{\partial^{2} f(x,y,t)}{\partial x \partial y}  +  \frac{\partial^{2} f(x,y,t)}{\partial y^{2}} \right)$
for simplicity I'm taking the case where
$C_{0}=C_{1}=C_{2}=C_{3}=1$
I want the function and all its spatial derivatives to be zero at the edges of a rectangle of an arbitrary length L (T is also arbitrary). My attempt at doing this is
DiffEq[C0_, C1_, C2_, C3_] := (x - y)*(C0*(f[x, y, t]) + C1*(D[f[x, y, t] , x] - D[f[x, y, t] , y]) +  C2*(D[ f[x, y, t] , {x, 2}] - D[ f[x, y, t] , {y, 2}]) +  C3*(D[ f[x, y, t] , {x, 3}] - D[ f[x, y, t] , {y, 3}]))

L = 3;
T = 10;
NDSolve[{D[f[x, y, t], t] == Evaluate[DiffEq[-1, -1, -1, -1]], f[x, y, 0] == Exp[-(x^2 + y^2)], (D[f[x, y, t], x] /. x -> L) == 0, (D[f[x, y, t], y] /. y -> L) == 0, (D[f[x, y, t], x] /. x -> -L) == 0, (D[f[x, y, t], y] /. y -> -L) == 0, (D[f[x, y, t], x, x] /. x -> L) == 0, (D[f[x, y, t], y, y] /. y -> L) == 0, (D[f[x, y, t], x, x] /. x -> -L) == 0, (D[f[x, y, t], y, y] /. y -> -L) == 0}, f, {x, -L, L}, {y, -L, L}, {t, 0, T}, Method -> {"PDEDiscretization" -> {"MethodOfLines", "SpatialDiscretization" -> "TensorProductGrid"}}]

I get the following error
NDSolve::ibcinc: Warning: boundary and initial conditions are inconsistent.
NDSolve::mxst: Maximum number of 10000 steps reached at the point t == 0.03311714832347852`.
NDSolve::eerr: Warning: scaled local spatial error estimate of 5317.243100921993` at t = 0.03311714832347852` in the direction of independent variable x is much greater than the prescribed error tolerance. Grid spacing with 69 points may be too large to achieve the desired accuracy or precision. A singularity may have formed or a smaller grid spacing can be specified using the MaxStepSize or MinPoints method options.

I'm finding it difficult to insert any initial conditions at t=0 that will get rid of this error. I've tried switching up the method of inserting initial conditions too.
f[x, y, 0] == If[-L < x < L && -L < y < L, Exp[-(x^2 + y^2)], 0]


text:
Q: Save a form in jsp with dropdown listfrom from database in Spring MVC I'm trying to save Account object in the hibernate .please find the following code.
@RequestMapping(value = "/saveAccount", method = RequestMethod.POST)
    public ModelAndView saveAccount(@ModelAttribute("account") Account account,
            BindingResult result) {
        Session session = sessionFactory.openSession();
        System.out.println(account.getFirstName());
        System.out.println(account.getLastName());
        System.out.println(account.getSubject());
        System.out.println(account.getCity().getCityName());
        session.save(account);
        return new ModelAndView("redirect:/form.html");
    }

My jsp page have a form with First Name,Last Name ,city and subject fields.
I'm getting city dropdown fromatabase.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ taglib
    prefix="c"
    uri="http://java.sun.com/jsp/jstl/core"
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

Contact Form

  <form  method="post" action="/sdnext/saveAccount.html">
    First Name
    <input type="text" id="fname" name="firstName"   placeholder="Your name..">
    Last Name
    <input type="text" id="lname" name="lastName"  placeholder="Your last name..">
    City

<select name="city" id="cityName" >
    <c:forEach var="cityname" items="${lists}">
        <option value="${cityname.cityName}">${cityname.cityName}</option>
    </c:forEach>
</select>

        Subject
    <textarea id="subject" name="subject"  placeholder="Write something.."  style="height:200px"></textarea>
    <input type="submit" value="Submit">
  </form>

DataBase bean classes are here
package test.*;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name= "Account")
public class Account implements Serializable {

    /**
         *
         */
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return LastName;
    }

    public void setLastName(String lastName) {
        LastName = lastName;
    }

    public City getCity() {
        return city;
    }

    public void setCity(City city) {
        this.city = city;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    private String firstName;

    private String LastName;

    @OneToOne
    private City city;

    private String subject;
}

package test.*;

@Entity
@Table(name= "City")
public class City implements Serializable {

  /**
         *
         */
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    private String cityName;

    public String getCityName() {
        return cityName;
    }

    public void setCityName(String cityName) {
        this.cityName = cityName;
    }
}

I have used one to one mapping to city object.But i'm not able to save city object in database,rest all firstNme,LastName and subjects are getting saved.its showing in network console,but data is not getting saved in database.Please help me fix this.Thanking you..

A: By creating the dto we can persists the values selected from the dropdown.and its working for me .

A: <option value="${cityname}">${cityname.cityName}</option>
The problem is you are sending cityname.cityName (String) which cannot be mapped to City object so,
send the complete city object as the value. Hibernate will take care of mapping.


text:
Q: Как подгружать информацию на свой сайт с сайта IKEA по артикулу товара? Это нужно для сайта по доставке товара из этого магазина.
Например, как тут — dostavkin.su или тут — tomsk-ikea.ru
сам сайт IKEA
Т.е. человек на сайте ikea копирует артикул понравившегося товара и вставляет его на сайте по доставке и после нажатия кнопочки подгружается вся необходимая информация о товаре.

A: Сайт IKEA имеет API, закрытое, необходимое для виджетов и мобильного приложения, но подходящее под вашу задачу:
Запрос на получение товара:
http://www.ikea.com/ru/ru/catalog/products/%productId%/?type=xml&dataset=normal,allImages,prices,attributes

Запрос на проверку наличия:
http://www.ikea.com/ru/ru/iows/catalog/availability/%productId%

Пример:
http://www.ikea.com/ru/ru/catalog/products/00285183/?type=xml&dataset=normal,allImages,prices,attributes


text:
Q: How to use BITS data type in Snmp set method in WebNMS? Is it same as Octet String? Reference : https://www.webnms.com/snmp/help/snmpapi/snmpv3/using_mibs_in_applns/bits_datatype.html
I have read this on WebNMS site, but i need more details to use Snmp Set method for BITS datatype.

A: BITS is a textual convention defined , and its underlying type is OCTET STRING. So when you try to use SET operation you should send the raw bytes as OCTET STRING. But of course you need to carefully encode the bytes if the library/tool you use does not provide you wrappers to manipulate BITS types.


text:
Q: WPF Binding IEnumerable to ListBox with a DataTemplate I am trying to bind an IEnumerable class UserList to a ListBox in XAML, but I'm not able to resolve the name of the object. My xaml code is as follows:
            <ListBox DockPanel.Dock="Left" x:Name="UserListBox" Width="400"
                     ItemsSource="{Binding Source={StaticResource userList}}"
                     ItemTemplate="{StaticResource UserListTemplate}">

            </ListBox>

I have userList instantiated in MainWindow.xaml.cs as well, but I guess I'm not doing something right. Intention is to have ListBox read from UserList and create a list of Users from that IEnumerable. How do I fix this?
public MainWindow()
    {
        InitializeComponent();
        DataConnection.CreateAndOpenDB();
        src.UserList userList = new src.UserList();

    }

A: A local variable can not be resolved by the StaticResource extension.
Create a UserList property like shown below, and set the Window's DataContext to this. If you want to be able to add or remove elements after setting the DataContext, the class UserList should implement the INotifyCollectionChanged interface. It may do so by deriving from ObservableCollection.
public src.UserList UserList { get; } = new src.UserList();

public MainWindow()
{
    InitializeComponent();
    DataConnection.CreateAndOpenDB();
    // add elements to UserList here

    DataContext = this;
}

Then write the Binding in XAML like this:
ItemsSource="{Binding UserList}"

See Data Binding Overview for an introduction.


text:
Q: Fetching Alexa data How is it possible to get traffic data, sub domains data, country rank in percentage like in http://www.websiteoutlook.com/www.google.com?

A: NB: This approach doesn't work anymore. The endpoint simply returns "Ok", even for URLs which aren't assigned.
There is a free API (though I haven't been able to find any documentation for it anywhere).
http://data.alexa.com/data?cli=10&url=%YOUR_URL%

You can also query for more data the following way:
http://data.alexa.com/data?cli=10&dat=snbamz&url=%YOUR_URL%

All the letters in dat are the ones that determine which info you get. This dat string is the one I've been able to find which seems to have more options. Also, cli changes the output completely, this option makes it return an XML with quite a lot of information.
EDIT: This API is the one used by the Alexa toolbar.

A: Alexa have an API here. It's not free, though.

A: SimilarWeb has an API that exposes its traffic and ranking data. They also provide engagement metrics, referrals and domain categorization APIs, among others, so maybe it'll be good for you.
API -  developer.similarweb.com

A: A simple function to get the alexa rank
function alexa_rank($url){
    $xml = simplexml_load_file("http://data.alexa.com/data?cli=10&url=".$url);
    if(isset($xml->SD)):
        return $xml->SD->REACH->attributes();
    endif;
}

Works pretty well and free ;)

A: you can use this too
<?php
$url="http://stackoverflow.com/";
$xml = simplexml_load_file('http://data.alexa.com/data?cli=10&dat=snbamz&url='.$url);
$rank=isset($xml->SD[1]->POPULARITY)?$xml->SD[1]->POPULARITY->attributes()->TEXT:0;
$web=(string)$xml->SD[0]->attributes()->HOST;
echo $web." has Alexa Rank ".$rank;
?>

this will output it like
stackoverflow.com has Alexa Rank 55

A: By using
http://data.alexa.com/data?cli=10&url=%YOUR_URL% API you can have all data.

A: Usage for SimilarWeb Traffic API:
function api_traffic (URL, KEY) {

  var apiurl = "http://api.similarweb.com/Site/"
  + URL
  + "/v2/EstimatedTraffic?Format=JSON&UserKey=";
  + "KEY";

var fetch_visitors = UrlFetchApp.fetch(apiurl);
    Utilities.sleep(2000);

      var data = JSON.parse( fetch_visitors);
    return data.EstimatedVisitors;
    }

A: http://www.siteprice.org/api/ is the cheapest I think and easy to use.
$worthofwebsite= file_get_contents('http://www.siteprice.org/WorthApi.aspx?type=1&key=testkey&url=google.com');
echo "Website Worth: ".$worthofwebsite;


text:
Q: One term of (2π+5)^n = 288000π^8, what's n? Without using calculator what's the value of n?
Using binomial expansion I get:
nCp * 2n-p * πn-p * 5p = 288000π8
Easily I know that n-p=8, by the π's power
Then the power of 2 is also 8, so I can divide both sides
nCp * 5p = 1125
Well I know that

*

*n-p=8

*n-8=p

*n=p+8

And with "pascal triangle's" rule(nCp = nCn-p)
nC8 * 5p = 1125
nC8 * 5n-8 = 1125
Well there are definitively many ways to  equate this, but how can I get the value of n without calculator or guessing(Trial and error)?
Or is there any other approach?
The answer is n=10 and p=2...
Sorry for no LaTeX(I don't know how to work with it

A: The term of degree $8$ in the expansion of $(x+a)^n$ is
$$
\binom{n}{8}a^{n-8}x^8
$$
so you want to solve
$$
\binom{n}{8}5^{n-8}2^8=288000=2^83^25^3
$$
hence
$$
\binom{n}{8}5^{n-11}=9
$$
We can exclude $n>11$, because the right hand side is not divisible by $5$.
Therefore you just have to check $n=8,9,10,11$:
\begin{align}
\binom{8}{8}&=1 \\
\binom{9}{8}&=\binom{9}{1}=9 \\
\binom{10}{8}&=\binom{10}{2}=\cdots\\
\binom{11}{8}&=\binom{11}{3}=\cdots
\end{align}

A:
${n\choose 8} * 5^{n-8} = 1125$

But $1125 = 9*5^3$ so $5^{n-8}|5^3$ and $8\le n \le 11$
And $5^{n-11}{n\choose 8} = 9$.
$9\not \mid 5$ so either $n-11=0$ or $5^{11-n}|{n\choose 8}$.
Now as $8\le n\le 11$ and ${n\choose 8}=\frac {9*..n}{(n-8)!}$ then $11 - n$ is at most $1$.
So $n = 10$ or $11$. Now as no prime but $3,5$ divide $\frac {9*..*n}{(n-8)!}$ we can not have $n = 11$ so
so $n =10$.


text:
Q: Facebook - Get photos of a page I would lik to display the photos from an album of a fan page (that I own) on my site. Only from this fan page, not from the visitors their own page.
So I don't won't to see a permessions dialog when a users surfs to the site.
I tried to use the Graph Explorer to generate an Access Token for my App.
https://developers.facebook.com/tools/explorer
With this acces token, I used this url

https://graph.facebook.com/120545691408560/photos?access_token={accessToken}

This worked very well, I got the photos I wanted.
But when I logged out of Facebook, I've got the following error

message: "Error validating access token: The session is invalid
  because the user logged out."

So how do I generate an Acces Token that works when I am not logged in?
Thanks a lot
Vincent

A: You have to GET a new token each time you communicate without the Facebook api. (at least for most queries)
So you have to implement some kind of authentication using the Facebook api.
There are different libraries you can use in JavaScript or Othello languages. Facebook graph explorer just lets you test api functions. Its not a copy paste solution.


text:
Q: $ \exists a, b \in \mathbb{Z} $ such that $ a^2 + b^2 = 5^k $ I saw this problem recently and found an elegant solution to it, and was curious to see if anybody would think of something else. Nice solutions to nice problems are fun to see!

Problem: Prove that, for all non-negative integers $k$, there exist integers $a$, $b$ such that $a^2+b^2=5^k$.
Bonus: Prove that there exist such $a$ and $b$ that furthermore satisfy $(a,b)=1$.

A: At heart, $a^2+b^2$ can be seen as the square of the distance of $a+bi$ to $0$ in the complex numbers. And if $w,z$ are complex numbers, then $|wz|=|w|\cdot |z|$, so $|wz|^2 = |w|^2\cdot |z|^2$.
That means that if $a+bi = (2+i)^n$ then $a^2+b^2 = |a+bi|^2 = \left(|2+i|^2\right)^n = 5^n$.
This approach gets you $a,b$ relatively prime and non-zero.
The other way is just to take the case of $n=2m$ even first:
$$5^{2m} = \left(5^m\right)^2 +0^2$$
For $n=2m+1$ odd, you get:
$$5^{2m+1} = \left(2\cdot 5^m\right)^2 + \left(1\cdot 5^m\right)^2$$
There is another way, closely associated with the complex answer, using determinants of matrices of the form:
$$\begin{pmatrix}x&y\\-y&x\end{pmatrix}$$
Such matrices are closed under multiplication, and the determinant is $x^2+y^2$.
Since the product of determinants is the determinant of the product, you only need to find a solution of $x^2+y^2=5$ and raise that matrix to the $n$th power.
This gives you exactly the same answer(s) as my first approach, since the ring of matrices of this form is "isomorphic" to the complex numbers. But the determinant is in some ways an "algebraic" answer, compared to the distance property.

A: Take the ring $\mathbb{Z}[i]$ and the norm function
$$
N(x+iy) = x^2 + y^2
$$
Then $N(z_1z_2) = N(z_1)N(z_2)$. So just take
$$
z = (2+i)^k = a+bi
$$
Then $a^2+b^2 = N(z) = N(2+i)^k = 5^k$

A: HINT:
Using induction:
$5^1=2^2+1^2$
Let $5^k=a^2+b^2$
$5^{k+1}=(a^2+b^2)(2^2+1^2)=(2a\pm b)^2+(2b\mp a)^2$ (Brahmagupta–Fibonacci identity)
This invites a little generalization: as we which numbers are expressible as the sum of two squares.


text:
Q: CSS 2.1 spec: rationale for not collapsing margins of parent (when parent is float or has overflow other than visible) The CSS 2.1 specification, section 8.3.1 on collapsing margins states:

Margins of elements that establish new block formatting contexts (such
  as floats and elements with 'overflow' other than 'visible') do not
  collapse with their in-flow children.

It took me a while to realize that the block formatting context is the
context that is established by the parent and applied to the children,
so that to make any difference, the float or overflow properties have
to be adjusted on the parent element (rather than to the children).
In the following code snippet, border heights of adjacent child div elements
collapse, so that between any two child div elements there is a vertical spacing
of max(20px, 20px) = 20px instead of 20px + 20px = 40px, and border heights
between the first child element and the parent div, and between the last child element
and the parent div, are also max(20px, 0px) = 20px instead of 20px + 20px = 40px, respectively.
Note that no collapsing appears in the horizontal direction, just as per the CSS 2.1 spec.
<!doctype html>

<meta charset="utf-8">
<title>Test</title>

Had the top margin of the red box1 element not collapsed with its parent, such margin would
not have pushed the black background down below the margin, and the red box1's margin would
be superimposed upon the black background of the parent element. A similar argument applies
to the blue box1 element on the bottom.
Now, just as the CSS 2.1 spec mentions, if either of the "float: left;" or "overflow: hidden;"
parts of the containing div are commented out, then the top and bottom borders of the parent
element (in this case it is 0) and the top (in this case 10px) border of the first child,
and the bottom (in this case 10px) border of the bottom child, are separated, yieling the
result shown below:

Now, and here comes the question:
What was the rationale for introducting this rule into CSS? Was it just a random decision,
or was it motivated by some real, practical example? (knowing this would also help me
remember the rule, other than satisfying my curiosity).
Thanks.

A: The only plausible explanation I can give is that block formatting contexts are atomic, in the sense that boxes in one block formatting context can never interact with boxes in another block formatting context. This rule on collapsing margins appears to be in the same vein as the rule that floats never intrude into other block formatting contexts or exit their own block formatting contexts into ancestor block formatting contexts.
To expand on this: the in-flow descendants of a box that establishes a new block formatting context participate in that box's block formatting context, whereas the box itself participates in a block formatting context that's established somewhere higher up in the layout tree. So the margins of the box itself are expected to collapse with boxes in that same block formatting context, but not descendant boxes.
Section 9.4.1 seems to support this:

Vertical margins between adjacent block-level boxes in a block formatting context collapse.

Notice that it says "adjacent block-level boxes in a block formatting context" — this would imply that the fact that margins don't collapse across block formatting contexts is an inherent property of a block formatting context. But this is only my interpretation of the spec; I'm not the author so I can't say for sure if this was the intended meaning.


text:
Q: pipenv updates all dependencies bringing breaking changes I'm having problems with an app that uses Django. Everything is in a docker container, there is a pipfile and a pipfile.lock. So far, so good.
The problem is when I want to install a new depedency. I open the docker container shell, and I install the dependency with pipenv install <package-name>.
After installing the package, pipenv runs a command to update the pipfile.lock file and doing so updates all packages to their last version, bringing whit these updates a lot of breaking changes.
I don't understand why is this happening, I have all packages listed in my pipfile with ~=, this is suppose to avoid updating to versions that can break your app.
I'll give you an example, I have this dependency in my pipfile: dj-stripe = "~=2.4". But, in the pipfile.lock file, after pipenv runs the command lock, that depedency is updated to its last version (2.5.1).
What am I doing wrong?

A: Are you sure you're installing it within Docker? A common cause of pipfile.lock  conflicts is installing a package locally instead of within Docker and then when the local environment syncs with Docker it will override your pipfile.lock.
Assuming you're using docker-compose, this is how I'm installing my packages:
docker-compose exec web pipenv install <package-name>

A: I discovered what my problem was.
I've been listing the dependencies like this: ~=2.4, I thought that was indicating not to update to 2.5 or greater, but that's not true, that only tells pipenv not to update to 3 or greater.
In order to stay in 2.4 version, I must specify the last number version, for example: ~=2.4.0
That way, I'm telling pipenv not to update from 2.4.


text:
Q: Arithmetic overflow error in SQL So just to give you an example of how our procedure would eventually work with data and come up with this error, here's some SQL:
DECLARE @daysInPeriod  INT
DECLARE @dcFraction    DECIMAL(38,38)
DECLARE @YEAR_360         DECIMAL
SET @YEAR_360 = 360.0000000000
SET @daysInPeriod = DATEDIFF(dd, '12/24/1970', '6/29/07')
SET @dcFraction = @daysInPeriod/@YEAR_360

If you run this in SQL Server 2008 R2, you'll see that you receive an 'Arithmetic overflow error converting numeric to data type numeric.' error.
The decimal that I am setting the value to is max'd out in terms of places it can hold, which I believe is 38. I don't know what else I can do to get this value. Shouldn't you be able to divide an integer with a decimal in SQL and get something out of it, especially if the decimal is max'd out?

A: In your example, the value of @daysInPeriod/@YEAR_360 is 37.0444444444444444444. So you can't assign that value to a parameter of data type DECIMAL(38,38), since you are leaving no room the int part. A DECIMAL(38,38) means that you can store 38 digits, and 38 of them are on the decimal part, so any value greater than 0.999999999999 will throw an error.

A: The problem is your declaration of @dcFraction as DECIMAL(38,38). You're saying you want all 38 digits to the right of the decimal point, with no room for the integer portion to the left.

A: If you give your decimal a smaller scale, it is going to work:
DECLARE @daysInPeriod  INT
DECLARE @dcFraction    DECIMAL(38,12)
DECLARE @YEAR_360         DECIMAL
SET @YEAR_360 = 360.0000000000
SET @daysInPeriod = DATEDIFF(dd, '12/24/1970', '6/29/07')
SET @dcFraction = @daysInPeriod/@YEAR_360
select @dcFraction

This returns 37.044444444444


text:
Q: Which HTML5 microdata do I use for a job (vacancy)? I'm trying to markup a vacancy/job item with microdata but I wonder whether I'm doing it the right way, because my item properties like 'title' and 'date' don't make sense in combination with my itemtype 'organization'. How could one rewrite the following block better leveraging microdata?

                Web developer
                Company Name,
                City

Lorem ipsum dolores amet ...

Published at 28 Jan 2011,
            75 views

Or can I create/suggest an itemtype='job' myself? If so, how?

A: There seems to be a good deal of momentum behind the JobPosting microformat. It's part of schema.org.
Here's the blog post announcing it.
http://blog.schema.org/2011/11/schemaorg-support-for-job-postings.html

A: Answered a long time after the fact, but there is now a "JobPosting" schema at schema.org as cited by Eric. With this your code would look like-

       Web developer

            Company Name
       ,
       City

Lorem ipsum dolores amet ...

Published at <time itemprop='datePosted' datetime='2011-01-28'>28 Jan 2011<time>,
     75 views

I couldn't find a schema containing a Views property.

A: A web developer is not a type of organization, keep the organization itemtype to just describe the organisation offering the job.  For the job itself the closest vocabulary on data-vocabulary.org would appear to be Offer but I would say that's a bit of stretch semantically.
There is a job-listing brainstorming page on the microformats wiki but it hasn't seen much recent activity, you could try posting on the mailing list to see if anyone's interested in taking it forward.  If that gets some traction there may be some benefit to using that vocabulary.
However, I don't think you'll see much immediate benefit to marking up with a non-standard vocabulary so I would recommend confining your microdata to those parts that can be marked up (eg. company contact information) rather than trying to add microdata to everything.

A: i usually get schemas from this website https://issemantic.net/rdf-converter

        <meta itemprop="unitText" content="HOUR" />
        <meta itemprop="value" content="40" />

      <meta itemprop="currency" content="USD" />

    <meta itemprop="jobLocationType" content="TELECOMMUTE" />
    <meta itemprop="validThrough" content="2017-03-18T00:00" />
    <meta itemprop="description" content="
Google aspires to be an organization that reflects the globally diverse audience that our products and technology serve. We believe that in addition to hiring the best talent, a diversity of perspectives, ideas and cultures leads to the creation of better products and services.
" />

      <link itemprop="sameAs" href="http://www.google.com/" />
      <link itemprop="logo" href="http://www.example.com/images/logo.png" />
      <meta itemprop="name" content="Google" />

    <meta itemprop="datePosted" content="2017-01-18" />
    <meta itemprop="title" content="Software Engineer" />

      <meta itemprop="name" content="USA" />

      <meta itemprop="value" content="1234567" />
      <meta itemprop="name" content="Google" />

      <meta itemprop="monthsOfExperience" content="36" />

    <meta itemprop="employmentType" content="FULL_TIME" />

      <meta itemprop="credentialCategory" content="bachelor degree" />

Enjoy !


text:
Q: Compare two wav files in the frequency domain in java I have two wav files ( O and X ) as input and i want to find out the similarity between them in the scale [0 - 1] .  This is the formula that i am trying to apply :
http://i.imgur.com/OnFDBZo.png
O(t,f) is the magnitude of frequency f at time time slice t for wav file O .
I am doing this in java and used "audio-analysis" library to calculate fft .
How do i apply this algorithm in Java ?
float[] samplesa = new float[1024];
float[] samplesb = new float[1024];
WaveDecoder decodera = new WaveDecoder( new FileInputStream( "X.wav" ) );
WaveDecoder decoderb = new WaveDecoder( new FileInputStream( "O.wav" ) );
FFT ffta = new FFT(1024, 44100);
FFT fftb = new FFT(1024, 44100);
while( decodera.readSamples( samplesa ) > 0 )
    {
       ffta.forward(samplesa);
       decoderb.readSamples( samplesb )
       fftb.forward(samplesb);
    }

Here is the "audio-analysis" library  : http://audio-analysis.googlecode.com/svn/trunk/


text:
Q: Statistical Significance Issue in Mixed Model A multilevel model, with one explanatory variable at the individual level (X) and one explanatory variable at the group level (Z):
$$Y_{ij}=\gamma_{00}+\gamma_{10}X_{ij}+\gamma_{01}Z_{j}+\gamma_{11}X_{ij}Z_{j}+u_{0j}+u_{1j}X_{ij}+e_{ij}$$
correlation between $u_{0j}$ and $u_{1j}$ is $0$ .
In This pdf , it is written in p.90 that

The interaction effect of these simulated characteristics are presented in table 4. Tested with a blockwise Bonferroni correction, none of the interactions were statistically significant .

But I found all fixed effect $(\gamma_{00},\gamma_{10},\gamma_{01},\gamma_{11})$ and all random effects $(u_{0j},u_{1j})$ statistically significant except individuals-level residual$(e_{ij})$ .
Now my question is if all of them are insignificant according to the mentioned paper , how can the model be valid ? By indicating all of those insignificant , what do they imply ?
Any help is appreciated. Thanks .
EDIT :
I found all fixed effect $(\gamma_{00},\gamma_{10},\gamma_{01},\gamma_{11})$ and all random effects $(u_{0j},u_{1j})$ statistically significant according to this post and the codes are copied here :
simfun <- function(J,n_j,g00,g10,g01,g11,sig2_0,sig01,sig2_1){
     N <- sum(rep(n_j,J))
     x <- rnorm(N)
     z <- rnorm(J)
     mu <- c(0,0)
     sig <- matrix(c(sig2_0,sig01,sig01,sig2_1),ncol=2)
     u   <- MASS::mvrnorm(J,mu=mu,Sigma=sig)

     b_0j <- g00 + g01*z + u[,1]
     b_1j <- g10 + g11*z + u[,2]
      y <- rep(b_0j,each=n_j)+rep(b_1j,each=n_j)*x + rnorm(N,0,sqrt(0.5))
     sim_data <- data.frame(Y=y,X=x,Z=rep(z,each=n_j),group=rep(1:J,each=n_j))
  }

fit <- function(J,n_j,g00,g10,g01,g11,sig2_0,sig01,sig2_1){
    dat <- simfun(J,n_j,g00,g10,g01,g11,sig2_0,sig01,sig2_1)
    full <- lmer(Y~X+Z+X:Z+(X||group),data=dat,control=lmerControl(optCtrl=list(maxfun=20000)))

  #Testing significance of random intercept
  null.U0 <- update(full, .~.-(1 | group))
  dev.U0 <- as.numeric(2*(logLik(full)-logLik(null.U0)))
  p.U0 <- 0.5*(1-pchisq(dev.U0,1))*(1/6) #multiplied by (1/6) since there are 6 parameters to be tested, that is there are 6 null hypothesis.

 #Testing significance of random slope
  null.U1 <- update(full, .~.-(0 + X | group))
  dev.U1 <- as.numeric(2*(logLik(full)-logLik(null.U1)))
  p.U1 <- 0.5*(1-pchisq(dev.U1,1))*(1/6)

 #Testing significance of intercept of fixed part
 null.int <- update(full, .~.-1)
 dev.int <- as.numeric(2*(logLik(full)-logLik(null.int)))
  p.int <- (1-pchisq(dev.U1,1))*(1/6)

 #Testing significance of X of fixed part
 null.x <- update(full, .~.-X)
 dev.x <- as.numeric(2*(logLik(full)-logLik(null.x)))
  p.x <- (1-pchisq(dev.x,1))*(1/6)

#Testing significance of Z of fixed part
 null.z <- update(full, .~.-X)
 dev.z <- as.numeric(2*(logLik(full)-logLik(null.z)))
  p.z <- (1-pchisq(dev.z,1))*(1/6)

#Testing significance of interaction part
 null.xz <- update(full, .~.-X:Z)
 dev.xz <- as.numeric(2*(logLik(full)-logLik(null.xz)))
  p.xz <- (1-pchisq(dev.xz,1))*(1/6)

 pvals <- data.frame(p.U0=p.U0,p.U1=p.U1,p.int=p.int,p.x=p.x,p.z=p.z,p.xz=p.xz)
}

c1 <- replicate(1000,fit(30,5,1,.3,.3,.3,(1/18),0,(1/18)))
colMeans(apply(c1,2,unlist))

A: There are many questions here, some are a bit confusing. But to get started, and answer your previous post, Bonferroni correction is applied a posteriori, so that raw p-values for each of the factors are essentially divided by n comparisons (hypotheses). So for the Table 4 example, depending how you define family-wise error rate in the context of this question, and what they meant by "block-wise", it can be by parameter (n=27 comparisons for the 7 parameters) or by parameter-group combination (n=9 for 3 groups sizes) vs. 189 (total number of tests).
Secondly, Table 4 refers to interaction terms, not individual effects themselves, which can still be significant. And perhaps clarification is needed on the response variable, which is "Noncoverage" (a type of misclassification indicator) for the 7 regression parameters, not those parameters themselves.
What the quoted statement means is that Noncoverage for some of the 7 parameters (fixed and random effects) depends on Number of Groups and Group Size, but effect of Number of Groups does not vary across levels of Group Size, and the third factor, Intraclass Correlation, which is not significant in any of the interactions or by itself.


text:
Q: How do I prevent accidental rm -rf /*? I just ran rm -rf /* accidentally, but I meant rm -rf ./* (notice the star after the slash).
alias rm='rm -i' and --preserve-root by default didn't save me, so are there any automatic safeguards for this?

I wasn't root and cancelled the command immediately, but there were some relaxed permissions somewhere or something because I noticed that my Bash prompt broke already. I don't want to rely on permissions and not being root (I could make the same mistake with sudo), and I don't want to hunt for mysterious bugs because of one missing file somewhere in the system, so, backups and sudo are good, but I would like something better for this specific case.

About thinking twice and using the brain. I am using it actually! But I'm using it to solve some complex programming task involving 10 different things. I'm immersed in this task deeply enough, there isn't any brain power left for checking flags and paths, I don't even think in terms of commands and arguments, I think in terms of actions like 'empty current dir', different part of my brain translates them to commands and sometimes it makes mistakes. I want the computer to correct them, at least the dangerous ones.

A: It seems like the best way to reduce this risk is to have a two-stage delete like most GUIs. That is, replace rm with something that moves things to a trash directory (on the same volume). Then clean that trash after enough time has gone by to notice any mistake.
One such utility, trash-cli, is discussed on the Unix StackExchange, here.

A: Your problem:

I just ran rm -rf /* accidentally, but I meant rm -rf ./* (notice the star after the slash).

The solution: Don't do that! As a matter of practice, don't use ./ at the beginning of a path. The slashes add no value to the command and will only cause confusion.
./* means the same thing as *, so the above command is better written as:
rm -rf *
Here's a related problem. I see the following expression often, where someone assumed that FOO is set to something like /home/puppies. I saw this just today actually, in the documentation from a major software vendor.
rm -rf $FOO/
But if FOO is not set, this will evaluate to rm -rf /, which will attempt to remove all files on your system. The trailing slash is unnecessary, so as a matter of practice don't use it.
The following will do the same thing, and is less likely to corrupt your system:
rm -rf $FOO
I've learned these tips the hard way. When I had my first superuser account 14 years ago, I accidentally ran rm -rf $FOO/ from within a shell script and destroyed a system. The 4 other sysadmins looked at this and said, 'Yup. Everyone does that once. Now here's your install media (36 floppy disks). Go fix it.'
Other people here recommend solutions like --preserve-root and safe-rm. However, these solutions are not present for all Un*xe-varients and may not work on Solaris, FreeBSD & MacOSX. In addition, safe-rm requires that you install additional packages on every single Linux system that you use. If you rely on safe-rm, what happens when you start a new job and they don't have safe-rm installed? These tools are a crutch, and it's much better to rely on known defaults and improve your work habits.

A: Since this is on "Serverfault", I'd like to say this:
If you have dozens or more servers, with a largish team of admins/users, someone is going to rm -rf or chown the wrong directory.
You should have a plan for getting the affected service back up with the least possible MTTR.

A: One important key factor to avoid such type of mistakes is to not login using root account. When you login using normal non-privileged user, you need to use sudo for each command. So, you should be more careful.

A: When I delete a directory recursively, I put the -r, and -f if applicable, at the end of the command, e.g. rm /foo/bar -rf.  That way, if I accidentally press Enter too early, without having typed the whole path yet, the command isn't recursive so it's likely harmless.  If I bump Enter while trying to type the slash after /foo, I've written rm /foo rather than rm -rf /foo.
That works nicely on systems using the GNU coreutils, but the utilities on some other Unixes don't allow options to be placed at the end like that.  Fortunately, I don't use such systems very often.

A: I like the windows approach of the recycle bin.
I usually create a directory named "/tmp/recyclebin" for everthing I need to delete:
mkdir /tmp/recyclebin

And never use rm -rf, I always use:
mv target_folder /tmp/recyclebin

Then later on, I empty the recyclebin using a a script or manually.

A: The best solutions involve changing your habits not to use rm directly.
One approach is to run echo rm -rf /stuff/with/wildcards* first. Check that the output from the wildcards looks reasonable, then use the shell's history to execute the previous command without the echo.
Another approach is to limit the echo command to cases where it's blindingly obvious what you'll be deleting. Rather than remove all the files in a directory, remove the directory and create a new one. A good method is to rename the existing directory to DELETE-foo, then create a new directory foo with appropriate permissions, and finally remove DELETE-foo. A side benefit of this method is that the command that's entered in your history is rm -rf DELETE-foo.
cd ..
mv somedir DELETE-somedir
mkdir somedir                 # or rsync -dgop DELETE-somedir somedir to preserve permissions
ls DELETE-somedir             # just to make sure we're deleting the right thing
rm -rf DELETE-somedir

If you really insist on deleting a bunch of files because you need the directory to remain (because it must always exist, or because you wouldn't have the permission to recreate it), move the files to a different directory, and delete that directory.
mkdir ../DELETE_ME
mv * ../DELETE_ME
ls ../DELETE_ME
rm -rf ../DELETE_ME

(Hit that Alt+. key.)
Deleting a directory from inside would be attractive, because rm -rf . is short hence has a low risk of typos. Typical systems don't let you do that, unfortunately. You can to rm -rf -- "$PWD" instead, with a higher risk of typos but most of them lead to removing nothing. Beware that this leaves a dangerous command in your shell history.
Whenever you can, use version control. You don't rm, you cvs rm or whatever, and that's undoable.
Zsh has options to prompt you before running rm with an argument that lists all files in a directory: rm_star_silent (on by default) prompts before executing rm whatever/*, and rm_star_wait (off by default) adds a 10-second delay during which you cannot confirm. This is of limited use if you intended to remove all the files in some directory, because you'll be expecting the prompt already. It can help prevent typos like rm foo * for rm foo*.
There are many more solutions floating around that involve changing the rm command. A limitation of this approach is that one day you'll be on a machine with the real rm and you'll automatically call rm, safe in your expectation of a confirmation… and next thing you'll be restoring backups.

A: One of the tricks I follow is to put # in the beginning while using the rm command.
root@localhost:~# #rm -rf /

This prevents accidental execution of rm on the wrong file/directory. Once verified, remove # from the beginning. This trick works, because in Bash a word beginning with # causes that word and all remaining characters on that line to be ignored. So the command is simply ignored.
OR
If you want to prevent any important directory, there is one more trick.
Create a file named -i in that directory. How can such a odd file be created? Using touch -- -i or touch ./-i
Now try rm -rf *:
sachin@sachin-ThinkPad-T420:~$ touch {1..4}
sachin@sachin-ThinkPad-T420:~$ touch -- -i
sachin@sachin-ThinkPad-T420:~$ ls
1  2  3  4  -i
sachin@sachin-ThinkPad-T420:~$ rm -rf *
rm: remove regular empty file `1'? n
rm: remove regular empty file `2'?

Here the * will expand -i to the command line, so your command ultimately becomes rm -rf -i. Thus command will prompt before removal. You can put this file in your /, /home/, /etc/, etc.
OR
Use --preserve-root as an option to rm. In the rm included in newer coreutils packages, this option is the default.
--preserve-root
              do not remove `/' (default)

OR
Use safe-rm
Excerpt from the web site:

Safe-rm is a safety tool intended to prevent the accidental deletion
  of important files by replacing /bin/rm with a wrapper, which checks
  the given arguments against a configurable blacklist of files and
  directories that should never be removed.
Users who attempt to delete one of these protected files or
  directories will not be able to do so and will be shown a warning
  message instead:
$ rm -rf /usr
Skipping /usr

A: You could always do an alias, as you mentioned:
what_the_hell_am_i_thinking() {
   echo "Stop." >&2
   echo "Seriously." >&2
   echo "You almost blew up your computer." >&2
   echo 'WHAT WERE YOU THINKING!?!?!' >&2
   echo "Please provide an excuse for yourself below: "
   read
   echo "I'm sorry, that's a pathetic excuse. You're fired."
   sleep 2
   telnet nyancat.dakko.us
}

alias rm -fr /*="what_the_hell_am_i_thinking"

You could also integrate it with a commandline twitter client to alert your friends about how you almost humiliated yourself  by wiping your hard disk with rm -fr /* as root.

A: It may be complicated, but you can setup roles within SELinux so that even if the user becomes root via sudo su - (or plain su), the ability to delete files can be limited (you have to login directly as root in order to remove files). If you are using AppArmor, you may be do something similar.
Of course, the other solution would be to make sure that you have backups. :)

A: My deletion process on Unix based machines is as follows.

*

*Type ls /path/to/intented/file_or_directory in the terminal window and then hit return (or Tab, as desired), to see the list of files.

If everything looks good,

*

*click the up arrow key to bring ls /path/to/intented/file_or_directory from the terminal history again.

*replace ls with rm or rm -r or rm -rf, as required. I personally don't like to use -f flag.
This process of validation also prevents the premature execution of the rm command, something which has happened to me, before I started following this process.

A: Avoid using globbing. In Bash, you can set noglob. But again, when you move to a system where noglob is not set, you may forget that and proceed as if it were.
Set noclobber to prevent mv and cp from destroying files too.
Use a file browser for deletion. Some file browsers offer a trashcan (for example, Konqueror).
Another way of avoiding globbing is a follows. At the command line, I echo filenamepattern >> xxx. Then I edit the file with Vim or vi to check which files are to be deleted, (watch for filename pattern characters in filenmates.) and then use %s/^/rm -f/ to turn each line into a delete command. Source xxx. This way you see every file that is going to be deleted before doing it.
Move files to an 'attic' directory or tarball. Or use version control (as said before me).

A: The ZSH asks me (as default) before performing a rm -rf *.
And ZSH also provides plugin (zsh-safe-rm) to add safe-rm functionality so that rm will put files in your OS's trash instead of permanently deleting them.

A: There's some really bad advice in this thread, luckily most of it has been voted down.
First of all, when you need to be root, become root - sudo and the various alias tricks will make you weak.  And worse, they'll make you careless.  Learn to do things the right way, stop depending on aliases to protect you.  One day you'll get root on a box which doesn't have your training wheels and blow something up.
Second - when you have root, think of yourself as driving a bus full of school children.  Sometimes you can rock out to the song on the radio, but other times you need to look both ways, slow things down, and double check all your mirrors.
Third - You hardly ever really have to rm -rf - more likely you want to mv something something.bak or mkdir _trash && mv something _trash/
Fourth - always ls your wildcard before rm - There's nothing crazy about looking at something before destroying it forever.

A: The simplest way to prevent accidental rm -rf /* is to avoid all use of the rm command! In fact, I have always been tempted to run rm /bin/rm to get rid of the command completely! No, I'm not being facetious.
Instead use the -delete option of the find command, but first before deleting the files I recommend previewing what files you'll be deleting:
find | less

Note, in modern versions of find if you leave out the name of a directory, it will implicitly use the current directory, so the above is the equivalent of:
find . | less

Once you're sure these are the files you want to delete you can then add the -delete option:
find path/to/files -delete

So, not only is find safer to use, it is also more expressive, so if you want to delete only certain files in a directory hierarchy that match a particular pattern you could use an expression like this to preview, then delete the files:
find path/to/files -name '*~' | less
find path/to/files -name '*~' -delete

There are lots of good reasons to learn and use find besides just a safer rm, so you'll thank yourself later if you take the time to learn to use find.

A: Yes: Don't work as root and always think twice before acting.
Also, have a look at something like https://launchpad.net/safe-rm.

A: The solution to this problem is to take regular backups. Anytime you produce something you don't want to risk losing, back it up. If you find backing up regularly is too painful, then simplify the process so that it's not painful.
For example, if you work on source code, use a tool like git to mirror the code and keep history on another machine. If you work on documents, have a script that rsyncs your documents to another machine.

A: This is standard of mine specifically for regexps in the context of rm, but it would have saved you in this case.
I always do echo foo*/[0-9]*{bar,baz}* first, to see what the regexp is going to match.  Once I have the output, I then go back with command-line editing and change echo to rm -rf.  I never, ever use rm -rf on an untested regexp.

A: Outside of chattr, there's not a whole lot of safeguards from letting root run such a command. That's why proper groups and careful commands are important when running privileged.
Next time; scope out the files you plan on deleting - omit 'f' from rm -rf, or use find and pass it to xargs rm

A: Some safety aliases for other commands, to prevent similar disasters, found here:
# safety features
alias cp='cp -i'
alias mv='mv -i'
alias rm='rm -I'                    # 'rm -i' prompts for every file
alias ln='ln -i'
alias chown='chown --preserve-root'
alias chmod='chmod --preserve-root'
alias chgrp='chgrp --preserve-root'

Notice the uppercase -I, it is different from -i:

prompt once before removing more than three files, or when removing
  recursively.  Less intrusive than -i, while still giving protection
  against most mistakes

A: Just use ZFS to store the files you need to resist accidental removal and have a daemon that:

*

*regularly makes snapshots of this file system

*removes older/unnecessary snapshots.

Should files are removed, overwritten, corrupted, whatever, just rollback your file system to a clone of the last good snapshot and you are done.

A: If you're not in the mood to acquire new habits right now, .bashrc/.profile is a good place to add some tests to check if you are about to do something stupid.
I figured in a Bash function I could grep for a pattern that might ruin my day and came up with this:
alias rm='set -f; myrm' #set -f turns off wildcard expansion need to do it outside of
                        #the function so that we get the "raw" string.
myrm() {
    ARGV="$*"
    set +f #opposite of set -f
    if echo "$ARGV" | grep -e '-rf /*' \
                           -e 'another scary pattern'
    then
        echo "Do Not Operate Heavy Machinery while under the influence of this medication"
        return 1
    else
        /bin/rm $@
    fi
}

The good thing about it is that it's only Bash.
It's clearly not generic enough in that form, but I think it has potential, so please post some ideas or comments.

A: In addition to all other solutions here, when doing a large rm usually use the -v flag to see what is being deleted and have a chance to ^C quickly if I have the slightest doubt. Not really a way to prevent bad rm's, but this can be useful to limit the damage in case something goes wrong.

A: Sadly, I cannot leave a comment above due to insufficient karma, but wanted to warn others that safe-rm is not a panacea for accidental mass-deletion nightmares.
The following was tested in a Linux Mint 17.1 virtual machine (warning to those unfamiliar with these commands: DON'T DO THIS! Actually, even those familiar with these commands should/would probably never do this to avoid catastrophic data loss):
Text version (condensed):
$ cd /
$ sudo safe-rm -rf *
$ ls
bash: /bin/ls: No such file or directory

Image version (full):

A: I think this is a powerful prevention tip, with * expansion shortcut in shell:
First, type rm -rf * or rm -rf your/path/*, DON'T type Enter key.  (of course, you should have a habit of caring not to press Enter fast/accidentally when using rm -rf)
Then, press Alt-Shift-8 (i.e. Alt-Shift-*) to expand the "*" wildcard explicitly in bash.  This also avoid re-entering a "rm -rf *" command when navigating the history.
Finally, after checked the expansion has the right files/directories, press Enter.
Done.

A: In case this helps someone out there for their own case:
1. Use rmsafe:
It moves files to a "trash" folder and you always have the chance to bring them back with a simple mv:
$ rmsafe /path/to/important/files

Source: https://github.com/pendashteh/rmsafe
2. Use safe:
You can set an alias for rm using safe:
$ alias rm="safe rm"

Now if you run rm /* you get this in response:
$ rm /*
Are you sure you want to 'rm /bin /boot /data /dev /etc /home /initrd.img /lib /lib64 /mnt /opt /proc /root /run /sbin /srv /sys /tmp /usr /var'? [y/n]

and I believe you won't type y!
Source: https://github.com/pendashteh/safe

A: Hehe (untested and somewhat facetiously!):
$ cat /usr/local/bin/saferm

#! /bin/bash

/bin/ls -- "$@"

echo "Those be the files you're about to delete."
echo "Do you want to proceed (y/N)?"

read userresponse

if [ "$userresponse" -eq "y" ]; then

  echo "Executing...."
  /bin/rm -- "$@"

fi

And then:
alias rm="/usr/local/bin/saferm"

Realistically, you should have a mental pause before executing that sort of operation with a glob, whether you're running as root, prepending "sudo" to it, etc.  You can run an "ls" on the same glob, etc., but, mentally, you should stop for a sec, make sure you've typed what you wanted, make sure what you want is actually what you want, etc.  I suppose this is something that's mainly learned by destroying something in the first year as a Unix SA, in the same way that the hot burner is a good teacher in telling you that something on the stove may be hot.
And make sure you have good backups!

A: Also, not as a safeguard, but as a way to find out what files were deleted before you hit ^C, you can use locate database (of course only if it was installed and survived rm)
I've learned about it from this blog post

A: not so much an answer but a tip, i always do rm (dir) -rf not rm -rf (dir) i.e: don't go nuclear until the last possible moment.
It helps mitigate situations in which you fat finger the dir name in such a way that it's still a valid deletion, such as slipping and hitting the enter key.

A: I simply did my own script that can simply warn and ask confirmation for every kind of situation, just up to you on how to improve it
#!/bin/sh
# just sudo mv /usr/bin/rm to /usr/bin/rm-original

path=${!#}

color_yel="\x1b[1;33m"
color_rst="\x1b[0m"

function get_yn() {
    read i
    if [ "$i" != "y" ]; then echo "aborted."; exit 1; fi
}

if [ -d ${path} ]; then
    echo -e "${color_yel}You are deleting a folder, it's potentially dangerous, are you sure (y/n) ?${col>
    get_yn
    /usr/bin/rm-original $@
fi

Further idea to improve it:

*

*check particular flags and paths

*move to a trash folder and remove

*empty old stuff in the trash after some time

So a simple customizable script allows to have any special behavior and avoid any additional package to be installed.
With some bash knowledge, you can trash only certain kind of things.

A: If you really are that careless at the shell prompt, or just having a bad day.. then a shell alias of rm to mv can save you from time to time.
https://unix.stackexchange.com/questions/379138/aliasing-rm-to-create-a-cli-recycle-bin


text:
Q: BeanCreationNotAllowedException when creating transactionManager I started noticing this error recently when I deploy my application to tomcat. I have a class (MachineScheduler) that is getting executed as part of an @Scheduled method on startup, that queries the database and some other things. When that method executes is where this error is getting raised from within. It doesn't seem to be preventing anything from running, but it's a bit worrying to think that transaction management isn't running.
org.springframework.scheduling.support.TaskUtils$LoggingErrorHandler - Unexpected error occurred in scheduled task.
org.springframework.beans.factory.BeanCreationNotAllowedException: Error creating bean with name 'transactionManager': Singleton bean creation not allowed while the singletons of this factory are in destruction (Do not request a bean from a BeanFactory in a destroy method implementation!)
  at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:215)
  at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
  at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
  at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:296)
  at org.springframework.transaction.interceptor.TransactionAspectSupport.determineTransactionManager(TransactionAspectSupport.java:337)
  at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:252)
  at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
  at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
  at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
  at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
  at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
  at com.sun.proxy.$Proxy40.getIncompleteParentJobs(Unknown Source)
  at com.web.machine.scheduling.MachineSchedulerImpl.startAdditionalMachines(MachineSchedulerImpl.java:50)
  at com.web.scheduling.SchedulingController.startAdditionalMachines(SchedulingController.java:24)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:606)
  at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:65)
  at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
  at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
  at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:304)
  at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:178)
  at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
  at java.lang.Thread.run(Thread.java:745)

Note: On my configuration class, I do have @EnableTransactionManagement


text:
Q: 64-bit Unsigned Integer concat benchmarking I have a tweak question. I had some repetitive pieces of code in my web-app requests where simple things like fmt.Sprintf("%d%d", 01293123, 234993923) happens.
Now I did some benchmarks and tested a bytes writer, which was quite slow (~400 ns/op). The sprintf itself was about 240 ns/op. Then I did strings joining:
var concatBuffStr []byte

func BenchmarkStringsJoin(b *testing.B) {
    for n := 0; n < b.N; n++ {
        concatBuffStr = []byte(strings.Join([]string{
            strconv.Itoa(2),
            strconv.Itoa(3),
        }, " "))
    }
}

152 ns/op

A big improvement already. But then I tried clunking 2 ints converted to bytes together
var concatBuffStr []byte

func BenchmarkConcatIntsAsBytes(b *testing.B) {
    for n := 0; n < b.N; n++ {
        aBuf := make([]byte, 8)
        bBuf := make([]byte, 8)
        binary.BigEndian.PutUint64(aBuf, uint64(2))
        binary.BigEndian.PutUint64(bBuf, uint64(3))
        concatBuffStr = append(aBuf, bBuf...)
    }
}

57.8 ns/op

Amazing! But I could just avoid glueing them together and already reserve the full 16 bytes for 2 maxed out 64 bit uints spaces:
var concatBuffStr []byte

func BenchmarkCopyIntsAsBytes(b *testing.B) {
    for n := 0; n < b.N; n++ {
        concatBuffStr = make([]byte, 16)
        bBuf := make([]byte, 8)
        binary.BigEndian.PutUint64(concatBuffStr, uint64(123123))
        binary.BigEndian.PutUint64(bBuf, uint64(3453455))
        copy(concatBuffStr[8:], bBuf)
    }
}

30.4 ns/op

By now we're 8 times faster than with the fmt.Sprintf() method.
Was wondering if there is an even faster way than this. I want to avoid unsafe tho.
I was also thinking of checking the max value of both 2 ints and if they are below the MAX of an uint32 or uint16 I could customize the logic. Benchmarking the uint16 downgrade by hand is around 23 ns/op, but that's not realistic as in the web-request itself it would still need to check the size of the ints and do extra logic, which will likely result in more overhead than that 7 ns/op gain.
Update
I managed to simplify it a little bit more:
var concatBuffStr []byte

func BenchmarkCopyIntsAsBytesShort(b *testing.B) {
    for n := 0; n < b.N; n++ {
        concatBuffStr = make([]byte, 16)
        binary.BigEndian.PutUint64(concatBuffStr, uint64(123123))
        binary.BigEndian.PutUint64(concatBuffStr[8:], uint64(3453455))
    }
}

28.6 ns/op


text:
Q: How to add a Angular 2 component to an Angular 1 directive written in Coffeescript? (with webpack) I have a case where I am am working in an Angular application written in coffee-script. I am trying to embed a new component in an existing ng1 directive written in coffee. According to the documentation I should just have to...
1.) Rename file to .ts
2.) Add the following (ish)...
import { HeroDetailComponent } from './hero-detail.component';
/* . . . */
angular.module('heroApp', [])
  .directive('heroDetail', upgradeAdapter.downgradeNg2Component(HeroDetailComponent));

The problem is I am in coffeescript so I can't just do that. So I tried adding that in back ticks (to make it clear JS) like this...
`import { HeroDetailComponent } from '../../../ng2/spinner/spinner.component';`

upgradeAdapter.downgradeNg2Component(HeroDetailComponent));

Then I change my .coffee loader to include
{
  test: /\.coffee$/,
  loaders: ["coffee-loader", "coffee-import", "ts"]
},

But this throws a bunch of errors transpiling. Is there an easier way than transpiling all of the files and changing the extension? This would help so I can still merge.

A: There were a few things wrong with my code but the real problem was the way coffee script requires imports. I changed it to something like this...
{ NgSpinnerComponent } = require '../../../ng2/upgrade.adapter';
...
module.directive("ngSpinner", NgSpinnerComponent)

Where update adapter is...
import { UpgradeAdapter } from '@angular/upgrade';
import { MyModule } from './my.module';
import { SpinnerComponent } from './spinner/spinner.component'
const upgradeAdapter = new UpgradeAdapter(MyModule);
var NgSpinnerComponent = upgradeAdapter.downgradeNg2Component( SpinnerComponent );
export {upgradeAdapter, NgSpinnerComponent}


text:
Q: Exhibit a countable subset $E\subset [0,1]$ so that $J_{*}(E)=1$ where $m_{*}(E)=0$ The outer Jordan content $J_{*}(E)$ of a set $E$ in $\mathbb{R}$ is defined by
$$ J_{*}(E)=\inf \sum^{n}_{j=1}|I_j| $$
where the $\inf$ is taken over every finite covering $E\subset \underset{j\in \mathbb{N}_n}{\bigcup}I_j, $
by closed intervals $I_j$.
($b$) Exhibit a countable subset $E\subset [0,1]$ so that $J_{*}(E)=1$ where $m_{*}(E)=0.$
{Proposition}($14.b.1$): Let $Q'=(0,1)\cap \mathbb{Q}$.
Let $\mathcal{X}=\{I_j\}^{N}_{1} $
of closed intervals be a cover of $Q'$. Then $(0,1)$ is covered by $\mathcal{X}.$

Proof.Let the assumptions be as above. Let $x\in Q'\subset (0,1)$. Then $\exists \delta >0$ such that
$B_\delta(x)\subset (0,1)$. We will prove $\exists \varepsilon >0$ such that
$B_\varepsilon(x)$
 is covered by $\mathcal{X}$. For every
$k\in
\mathbb{N}$, the interval $(x-\frac{\delta}{k})\subset B_{\frac{\delta}{k}}(x)$. We will denote
these intervals by $A_k$. Since $\mathbb{Q}$ is dense in the reals, $A_k\cap \mathbb{Q}$ is non
empty for every $k$. Pick a point in this intersection and denote it as $y_k\in Q'.$ Therefore, we have a sequence
$\{y_k\}_k\subset Q'$
which converges to $x$ since for each $k$ we have
$$ d_{A_k}(x,y_k)=|x-y_k|< \frac{\delta}{k} $$
Therefore, each point in the sequence must be contained by elements of $\mathcal{X}$.
But there are only a finite number of elements in $\mathcal{X}$. Hence, there exists at least
one element, say $I\in \mathcal{X}$, which contains a subsequence of $\{y_k\}_k$. This must
be since if each interval contained only a finite number of points in the sequence, then
not all of the sequence would be covered.
Hence, $\big\{y_{k_m}\big\}_{k_m}\subset I$. Since $I$ is closed, it must contain the limit point $x$.
We can repeat the same procedure for the intervals $(x+\frac{\delta}{k})$ and sequence
$\{z_k\}_k \subset Q'$ associated with it. Therefore,
there $\exists I'\in \mathcal{X}$ which also contains $x$. Thus, $\exists k'\in \mathbb{N}$ such
that $B_{\frac{\delta}{k'}}(x)\subset I\cup I'$. Which must be true since for some $k'$, we'd have
$[y_k',x]\subset I$ and $[x,z_k']\subset I' \Rightarrow [y_k',z_k']\subset I\cup I'.$
(It is by definition of an interval that all those points in between are also contained).
Set $\varepsilon = \frac{\delta}{k'}.$ Then $B_{\varepsilon}(x)$ is covered by
$\mathcal{X}$.
{Claim}($i$): Denote $\underset{x\in Q'}{\bigcup}B_{\varepsilon_x}(x)$ by $\mathcal{Q}$. We claim $\mathcal{Q}=(0,1).$  (Where $\varepsilon_x$ is the required radius
 so that $\mathcal{X}$ covers the associated ball)
Proof. It is clear by construction that $\mathcal{Q}\subset (0,1)$. So let $x\in (0,1).$
Then $\exists \delta>0$ such that $B_\delta(x)\subset (0,1)$. Therefore,
$B_{\frac{\delta}{k}}(x)$
is definitely contained in $(0,1)$, for any $k>2$. By the density of $\mathbb{Q}, \exists$
$y\in B_{\frac{\delta}{k}}(x)$ such that $y\in Q'$. let $p\in B_{\frac{\delta}{k}}(y)$. Then we have
$$ d_\delta(x,p)\leq d(x,y)+d(y,p) $$
$$<\delta/k + \delta/k<\delta $$
Hence, $B_{\frac{\delta}{k}}(y)\subset B_\delta(x)$. Thus, we have
$x\in B_{\frac{\delta}{k}}(y)$. We can then choose $k$ such that $\frac{\delta}{k}\leq \varepsilon_ y$. Which would yield $B_{\frac{\delta}{k}}(y)\subset \mathcal{Q}$, exactly as desired.
Now, Since $\mathcal{Q}=(0,1)$ by {Claim}($i$), it follows that $\mathcal{X}$ covers
$(0,1)$ and our proof is complete.
{Proposition}($14.b.2$): Let $Q'=(0,1)\cap \mathbb{Q}$. Then $J_{*}(Q')=1.$
Proof. Let $\mathcal{X}=\{I_j\}^{N}_{1}$ be a cover of $Q'$. By {Proposition}($14.b.1$),
$ \mathcal{X}$
must cover $(0,1)$. Therefore,
$$ |(0,1)|=1\leq \sum^{N}_{j=1}|I_j| $$
$$\Rightarrow 1\leq J_{*}(Q') $$
Now we will prove the reverse inequality. $I=[0,1]$ covers $Q'$. Therefore,
$$ J_{*}(Q')\leq |I|=1 $$
Thus, we have that $J_{*}(Q')=1$. This completes our proof.
{Proposition}($14.b.3$): $m_{*}(Q')=0.$
Proof. Let $x\in Q'$ and $I_{x,n}=[x-1/n, x+1/n]$. Fix $\frac{\varepsilon}{2N}>0$.
Let $S_{x,n}$ be an open
interval such that
$$ |S_{x,n}|\leq (1+\frac{\varepsilon}{2N})|I{x,n}| $$
Let $\mathcal{X}=\{I_{x,n}\}_{x\in Q'}$ and $\mathcal{Y}=\{S_{x,n}\}_{x\in Q'}$. These are
countable collections since $Q'$ is countable. Both of these collection cover $Q'$. Since
$Q'\subset [0,1]$, compactness implies we only need a finite subcover of $\mathcal{Y}.$
Let
$$ \mathcal{Y}'=\{S_{x_j,n}\}_{j\in \mathbb{N}_{N}} $$
Then we have that
$$ m_{*}(Q')\leq \underset{j\in \mathbb{N}_N}{\sum}|S_{x_j,n}| $$
$$ \leq \underset{j\in \mathbb{N}_N}{\sum}(1+\frac{\varepsilon}{2N})|I_{x_j,n}| $$
$$ \leq \underset{j\in \mathbb{N}_N}{\sum}|I_{x_j,n}|+\frac{\varepsilon}{2N}\underset{j\in \mathbb{N}_N}{\sum}|I_{x_j,n} $$
$$=\frac{2N}{n}+\frac{\varepsilon}{n} < \frac{2N}{n} + \varepsilon $$
As $\varepsilon$ is arbitrary, we have that
$$ m_{*}(Q')\leq \frac{2N}{n} $$
Letting $n\rightarrow \infty$, we have that $m_{*}(Q')=0$ as desired.

I just wanted to check if my proof is correct. Thank you for any feedback.


text:
Q: Summarize the data per column and per row I have a sample data frame below. (1 means Yes, 2 means No)
Age Range        Ans
10 - 20           1
21 - 30           2
31 - 40           1
10 - 20           2
21 - 30           2
21 - 30           1
21 - 30           2

Desired Output :
Age_Range        Yes        No
10 - 20           1         1
21 - 30           1         3
31 - 40           1         0

How can I do it in R?

A: In base R, you're basically just asking for table:
table(dat$Age.Range, dat$Ans)
#           1 2
#   10 - 20 1 1
#   21 - 30 1 3
#   31 - 40 1 0

If you wanted to convert it to have your column names:
tab <- table(dat$Age.Range, dat$Ans)
data.frame(Age_Range=rownames(tab), Yes=tab[,"1"], No=tab[,"2"])
#         Age_Range Yes No
# 10 - 20   10 - 20   1  1
# 21 - 30   21 - 30   1  3
# 31 - 40   31 - 40   1  0

A: I like to use data.table for these tasks.
Make the data frame:
library(data.table)

df <- read.table(text='Age Range        Ans
10 - 20           1
21 - 30           2
31 - 40           1
10 - 20           2
21 - 30           2
21 - 30           1
21 - 30           2',row.names=NULL)

df <- as.data.table(df)

df[,`Age Range`:=paste(row.names,Age,Range)]

Try
df[,list(Yes=sum(Ans==1),No=sum(Ans==2)),by=`Age Range`]

#    Age Range Yes No
# 1:   10 - 20   1  1
# 2:   21 - 30   1  3
# 3:   31 - 40   1  0

Or try a dplyr approach:
library(dplyr)

df %.% group_by(`Age Range`) %.% summarize(Yes=sum(Ans==1),No=sum(Ans==2))

#   Age Range Yes No
# 1   10 - 20   1  1
# 2   21 - 30   1  3
# 3   31 - 40   1  0


text:
Q: get a specific file at special commit url using git cli Can I get the file url from git command line?
For example, In here, https://git.postgresql.org/gitweb/?p=postgresql.git;a=history;f=src/test/regress/sql/alter_table.sql;hb=784cedda0604ee4ac731fd0b00cd8b27e78c02d3
I can see all the changes about file alter_table.sql.
If I choose the latest one, I will get alter_table.sql latest url A: https://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/test/regress/sql/alter_table.sql;h=e7013f5e154404526cd5b920104b77e19ae7dc65;hb=784cedda0604ee4ac731fd0b00cd8b27e78c02d3
But I already pull the code from git. In my local repo, is there any way I can get the specific file at special commit url.


text:
Q: Accept zipped filetypes in HTML input field I have the following line in my HTML:
<input type="file" nv-file-select multiple="" uploader="uploader" accept=".vcf, .vcf.gz"/>

When submitting a file through this, it only allows files that are '.vcf', not the gzipped ones. Can't find anything online pertaining to this issue.

A: Try just ".gz" instead of ".vcf.gz" and then do additional work in the javascript to verify ".vcf.gz"


text:
Q: Why is this method console printing different results on server and client? I have a button that allows saving a restaurant. In the method below I am trying to figure three things:

*

*if user already has a document,

*if this item is in the list,

*or not.

The code is:
'saveRestaurant': function(restId){
    check('restId', String);
    if(Meteor.userId())
    var hasSaved = SavedRestaurants.findOne({userRefId: Meteor.userId()});
    var isSaved = SavedRestaurants.findOne({userRefId: Meteor.userId(),savedRestaurants: {$in: [restId]}});
    if(isSaved){
        console.log('isSaved', hasSaved._id);
        return SavedRestaurants.upsert(
            hasSaved._id,
            {$pull: { savedRestaurants: restId}}
        );

    }
    else {
        if (!hasSaved) {
            console.log('!hasSaved');
            return SavedRestaurants.insert(
                {userRefId: Meteor.userId()},
                {$addToSet: {savedRestaurants: restId}}
            );
        } else {
            console.log('hasSaved && !isSaved', hasSaved._id);
            return SavedRestaurants.upsert(
                hasSaved._id,
                {$addToSet: {savedRestaurants: restId}}
            );
        }
    }
}

On the server console I get:

isSaved oYcsPz6ieoKrBMNkv
hasSaved && !isSaved oYcsPz6ieoKrBMNkv

Which is as expected, but on the browser console I always get:

!hasSaved

And the button is not showing the expected changed status. (saved, not saved)
the methods file is in the lib folder. (client/server)
So, I guess there is a "loop" here which overwrites something, but I don't get it.
Why is this happening and how can I fix it?


text:
Q: Convert CloudFormation template (YAML) to Troposphere code I have a large sized CloudFormation template written in Yaml, I want to start using Troposphere instead. Is there any easy way to convert the CF template to Troposphere code?
I have noticed this script here https://github.com/cloudtools/troposphere/blob/master/troposphere/template_generator.py
This creates a Troposphere python object, but I am not sure if its possible to output it Troposphere code.

A: You can do it by converting the CF YAML to JSON and running the https://github.com/cloudtools/troposphere/blob/master/scripts/cfn2py passing the JSON file in as an argument.

A: Adding to the good tip from @OllieB
Install dependencies using pip or poetry:

*

*https://python-poetry.org/docs/#installation

*https://github.com/cloudtools/troposphere

*https://github.com/awslabs/aws-cfn-template-flip
pip install 'troposphere[policy]'
pip install cfn-flip

poetry add -D 'troposphere[policy]'
poetry add -D cfn-flip

The command line conversion is something like:
cfn-flip -c -j template-vpc.yaml template-vpc.json
cfn2py template-vpc.json > template_vpc.py

WARNING: it appears that the cfn2py script might not be fully unit tested or something, because it can generate some code that does not pass troposphere validations.  I recommend adding a simple round-trip test to the end of the output python script, e.g.
if __name__ == "__main__":

    template_py = json.loads(t.to_json())

    with open("template-vpc.json", "r") as json_fd:
        template_cfn = json.load(json_fd)

    assert template_py == template_cfn

See also https://github.com/cloudtools/troposphere/issues/1879 for an example of auto-generation of pydantic models from CFN json schemas.

A: from troposphere.template_generator import TemplateGenerator
import yaml

with open("aws/cloudformation/template.yaml") as f:
    source_content = yaml.load(f, Loader=yaml.BaseLoader)
    template = TemplateGenerator(source_content)

This snippet shall give you a template object from Troposphere library. You can then make modifications using Troposphere api.


text:
Q: Spring Security default database authentication schema I've been working with the default database model provided by Spring Security to authenticate users. I've realized that Spring Security looks for these tables in the default schema configured for the database engine.
Now, suppose the following:
You are working with PostgreSQL and you have 2 schema: schemaOne and schemaTwo, where schemaOne is configured as the dafault one for the engine. Then, suppose that you have an application that uses schemaTwo, then you will need Spring Security database model to be in that schema. So, once you try to run your application, Spring Security will try to look for the authentication model in schemaOne.
So, my question is: is there a way to push Spring Security to use a different schema than the default one configured for the database engine?.
Thank you.

A: Well, you can configure custom JDBC queries, for example:

*

*With XML - override authorities-by-username-query, etc.

*With JavaConfig - set authoritiesByUsernameQuery(String), etc.

But, I don't think you can just set the schema name.


text:
Q: Enter and Exit subprocess from Shell Script I am trying to enter irb from a shell script, do something, and then return to the shell script.
How can I do this?
#!/bin/bash
#example_app

# Some shell instructions here
irb
four = 2 + 2
exit
echo "This text is not reached and the process hangs open"

NOTE: I should not try to load irb to enter static code, I agree with you guys. I didn't think about what I was doing. I was interacting with an AWS library and I tried to carry that same philosophy into automating this without thinking twice about it.

A: You can pass a here document to irb:
irb <<SCRIPT
  four = 2 + 2
  puts four
SCRIPT

However, I don't think that will accomplish what you are trying to do. Here is the output:
Switch to inspect mode.
  four = 2 + 2
4
  puts four
4
nil

It is similar to bash -x. Why not simply use plain old ruby for this?
ruby <<SCRIPT
  four = 2 + 2
  puts four
SCRIPT
4

There is no need to spawn an interactive shell if you aren't going to interact with it.

A: I think you want the answer explained from
fork and exec in bash
essentially:
function_to_fork() {
   irb
}
function_to_fork &
that may not work if you want some interaction there to influence the parent process or for the parent process to wait.
My comment below didn't format very well:
With the following program I was able to achieve:
#!/bin/bash
# irbb.sh
irb
echo "here"

$ ./irbb.sh
>> four = 2 + 2
=> 4
>> exit
here


text:
Q: HBASE: Get All columns of specific Column Family I created this table in Hbase with 2 Column Family:
connection.create_table(
    'twitter_db',
    {'Hashtag': dict(),
     'Lang': dict(),
   }
)

How can I get all the columns in the Column Family 'Hashtag' of a row key?

A: If you are using happybase, you can use following:
row = table.row('row-key', columns=['cf1'])

It will give you all the columns and value for column family "cf1" for "row-key".
More documentation is available here:


text:
Q: MongoDB query in Java - BSONDecoder doesn't understand type : 19 name: h I am trying to return the results of a MongoDB query but for some reason I get the following error:

java.lang.UnsupportedOperationException: BSONDecoder doesn't understand type : 19 name: h

How do I resolve this issue? This is the code I have at the moment:
public void printData() throws UnknownHostException
{
    MongoClient mongoClient = new MongoClient();
    DB database = mongoClient.getDB("databaseName");
    DBCollection collection = database.getCollection("collectionName");

    DBObject query = new BasicDBObject("status", "A");
    DBCursor cursor = collection.find(query);

    if (cursor.hasNext()) //The error occurs on this line.
    {
        cursor.next();
        System.out.println("Item: " + cursor.curr());
    }
}


text:
Q: Como habilitar a câmera do macBook no Simulador? Estou fazendo um APP no xCode que utiliza a câmera para fazer vídeos porém não consigo usar a câmera pelo Simulador.
Existe alguma forma para habilitar a câmera para o Simulador?

A: Infelizmente não é possível acessar a câmera do MacBook no Simulator. Recursos como a câmera podem ser testados apenas em um aparelho real.
Uma lista completa dos recursos que não podem ser testados no Simulator pode ser vista aqui


text:
Q: Exporting iPhone appicon without loosing clarity? I have a vector image which is larger than 57 x 57 pixels. I resized it to 57 x 57 with Adobe Illustrator and set it as my appicon, but it was blurred when I deployed it into my device.
What is the right way to create icons for my app when using Titanium Studio?

A: This link should help:
http://www.titaniumtips.com/files/creating_universal_titanium_apps.php
Especially the part about icons.

57x57px icon for the standard iPhone display. Before submitting to the
  App Store, you'll need to add icons for the iPhone Retina display (114x114) and
  iPad (72x72). Optionally you can add icons for Spotlight and the Settings
  pages too.


text:
Q: How to fix non-replicatable iOS issue? Users of my app are reporting crashes when a button gets tapped and a view controller gets pushed. However, I'm really unable to replicate the problem on my own iPad or simulator. They all have different iPads (1, 2 and 3) and different iOS versions. I don't think it's a memory leak because nothing should be taking up memory at this point.
My project's base SDK is iOS 5.1 but the deployment target is iOS 4.3. Could that be the issue?
Are there some common issues to look out for? Any help appreciated. Thanks


text:
Q: Use of unresolved identifier 'sizeof' I'm trying to send a position between two devices, so I need to convert the position to NSData. I found something on the net but I have an error: Use of unresolved identifier 'sizeof'. I don't know how to solve, could you help me?. Here's my code:
var error: Error?
    var positionToSend = car.position
    let dataSend = NSData(bytes: &positionToSend, length: sizeof(CGPoint))
    try? match.sendData(toAllPlayers: dataSend, with: .unreliable)
    if error != nil {
    }

A: First of all the error variable is pointless. try? doesn't affect error at all.
sizeof has been changed to MemoryLayout.size(ofValue:. The argument is positionToSend, not the type CGPoint
The Swift 3+ way to create Data (not NSData) from a CGPoint is
let dataSend = Data(bytes: &positionToSend, count: MemoryLayout.size(ofValue: positionToSend))

A: I would rewrite your code in Swift 4 as:
var positionToSend = car.position
let dataSend = Data(bytes: &positionToSend, count: MemoryLayout.size(ofValue: positionToSend))
do {
    try match.sendData(toAllPlayers: dataSend, with: .unreliable)
} catch {
    //Write code for `if error != nil`...
    print(error)
}

You do not need withUnsafePointer.


text:
Q: ¿Como puedo hacer un "cast" a los datos que obtengo con context.Database.SqlQuery de c#? Utilizo un context.Database.SqlQuery<T>() para obtener los datos del query de abajo, pero no logro  por ningun metodo mostrar esos datos en el frontend.
No encuentro la manera de "castear" a una clase llamada Resumen, la cual contiene todos los datos que extrae la consulta.
El error es:

"No se puede convertir del tipo:
  System.Data.Entity.Infrastructure.DbRawSqlQuery'
  to 'System.Collections.Generic.List ''".

He intentado castear de todas las formas, incluso usé List Object para que no tenga problemas de tipo, pero obtengo el mismo error. Estaré muy agradecido por la ayuda de los que ya pasaron por esto.
string query = "SELECT " +
                   "A1.fecha," +

                    "cl.nombre as \"cliente_nombre\"," +
                    "tp.nombre as \"tipo_papel\"," +
                    "A1.GM2_NOM," +
                    "round(AVG(A1.T_LARGO_PROM_2X_BOB), 1) as \"T_LARGO\", " +
                    "round(AVG(A1.T_ANCHO_PROM_2X_BOB), 1) as \"T_ANCHO\", " +
                    "round(AVG((A1.FACTOR_LQ_LC + A1.FACTOR_LQ_LT) / 2), 1) as \"L_Q\", " +
                    "round(AVG(A1.GM2_PROM2), 1) as \"GM2_LAB\", " +
                    "round(AVG(A1.H_PORC_PLS), 1) as \"H_PLS\", " +
                    "round(AVG(A1.COBB_T_PROM_2X_BOB), 1) as \"COBB_T\", " +
                    "round(AVG(A1.COBB_CT_PROM_2X_BOB), 1) as \"COBB_CT\", " +
                    "round(AVG(A1.GURLEY_SEG_PROM), 1) as \"Gurley\" " +
                "FROM " +
                    "ADMIN2.LC_LAB A1 " +
                   " join lc_cli cl on cl.id = A1.CLIENTE_LC " +
                   " join lc_tip_pap tp on tp.id = A1.TIP_PAP_ID " +

               " GROUP BY " +
               "A1.fecha ," +
                   " cl.nombre, " +
                   " tp.nombre, " +
                    "A1.GM2_NOM," +
                    "A1.TIP_PAP_ID" +
                   " order by cl.nombre;";
List<Resumen> result = (List<Resumen>)context.Database.SqlQuery<Resumen>(query);

A contnuación, el codigo del Modelo Resumen:
public class Resumen
{

    public string FECHA { get; set; }
    [System.ComponentModel.DisplayName("Cliente")]
    public string CLIENTE_NOMBRE { get; set; }
    [System.ComponentModel.DisplayName("Papel")]
    public string TIPO_PAPEL { get; set; }
    [System.ComponentModel.DisplayName("Gramaje")]
    public decimal GM2_NOM { get; set; }
    [System.ComponentModel.DisplayName("T. Largo")]
    public decimal T_LARGO { get; set; }
    [System.ComponentModel.DisplayName("T. Ancho")]
    public decimal T_ANCHO { get; set; }
    [System.ComponentModel.DisplayName("L/Q")]
    public decimal L_Q { get; set; }
    [System.ComponentModel.DisplayName("g/m2 Lab.")]
    public decimal GM2_LAB { get; set; }
    [System.ComponentModel.DisplayName("H (%) PLS")]
    public decimal H_PORC_PLS { get; set; }
    [System.ComponentModel.DisplayName("COBB T")]
    public decimal COBB_T_PROM_2X_BOB { get; set; }
    [System.ComponentModel.DisplayName("COBB CT")]
    public decimal COBB_CT_PROM_2X_BOB { get; set; }
    [System.ComponentModel.DisplayName("Gurley")]
    public decimal GURLEY_SEG_PROM { get; set; }

}

A: En este caso, no te va a funcionar un simple cast a (List<Resumen>), ya que el método genérico SqlQuery<Resumen>(query) devuelve un objeto del tipo DbRawSqlQuery<T>.
Lo que debes hacer es transformar el resultado en un List<Resumen>, haciendo el cast ahí mismo:
El código sería así:
var result = context.Database.SqlQuery<Resumen>(query).ToList<Resumen>();

UPDATE: Según el autor de la pregunta, la solución que se ajusta a su desarrollo y resuelve el problema, es la siguiente:
List<Resumen> result = (List<Resumen>)context.Database.SqlQuery<Resumen>(query).ToList();


text:
Q: writing a plugin, how to disable the comment form altogether? I'm writing a protected-page plugin and want to disable comments on protected pages. I'm usually hooking into the_content but that's not enough for comments. I got into comments_array to block the existing comments, but how do I block comments_template?

A: You can control whether comments appear by filtering the comments_open() function. Here is an example from the WordPress codex:
add_filter( 'comments_open', 'my_comments_open', 10, 2 );
function my_comments_open( $open, $post_id ) {

    $post = get_post( $post_id );

    if ( 'page' == $post->post_type )
        $open = false;

    return $open;
}