Q:

Why my rotated tick values are not getting displayed completely d3js?

I was working on a chart where the whole svg object and the tick values are supposed to be in the given height limits. I was wondering why my rotated tick values are not getting displayed completely. The height is 100px and I want my chart and the tick values to be inside that 100. I tried
 .attr("transform", "scale(1,1.4)")
function but no use. Here is the code so far!
The data is this and the code for rendering chart is below that.
 {
  "Height" : 100,
  "Width" : 250,
"margins" : {
    "top": 10,
    "left": 20,
    "right": 10,
    "bottom": 20
  },

  "data":[
          {
             "fruit" : "apple",
             "initialsale" : 40,
             "totalsale": 600
           },
           {
              "fruit" : "orange",
              "initialsale" : 40,
              "totalsale": 60
            },
          {
            "fruit" : "mango",
            "initialsale" : 1420,
            "totalsale": 6000
          }
        ]
}

function stackChart(){

 data =  {
      "Height" : 100,
      "Width" : 250,
    "margins" : {
        "top": 10,
        "left": 20,
        "right": 10,
        "bottom": 20
      },

      "data":[
              {
                 "fruit" : "apple",
                 "initialsale" : 40,
                 "totalsale": 600
               },
               {
                  "fruit" : "orange",
                  "initialsale" : 40,
                  "totalsale": 60
                },
              {
                "fruit" : "mango",
                "initialsale" : 1420,
                "totalsale": 6000
              }
            ]
    };

var margin = data.margins;

var top = margin.top,
    bottom = margin.bottom,
    left = margin.left,
    right = margin.right,
    Width = data.Width,
    Height = data.Height,
    data = data.data;

var width = Width -left -right,
    height = Height -top - bottom;

var svg = d3.select("#stackChart")
  .append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

// Divider functionality
var div = 0;
if(Width>50&&Width<=100){
  div = 1.2
}
else if(Width>100&&Width<=200)
{
  div = 1.5
}
else if(Width>200&&Width<=300){
  div = 2.0
}
else if(Width>300&&Width<=400){
  div = 2.2
}
else if(Width>400&&Width<=500){
  div = 2.4
}
else if(Width>500&&Width<=600){
  div = 2.6
}
else if(Width>600&&Width<=800){
  div = 2.8
}
else if(Width>800){
  div = 3.0
}

var par = Width/div;

// var scale_parameter = Width/par;

var dataset = [];
var arr1 = [];
var arr2 = [];
data.forEach(function(d) {
                var currentObj = {}
                currentObj["os"] = d.os;
                currentObj["value"] = d.total;
                currentObj["percent"] = (d.initial/d.total)*100;
                arr1.push(currentObj);
                currentObj = {}
                currentObj["os"] = d.os;
                currentObj["value"] = d.total;
                currentObj["percent"] = ((d.total - d.initial)/d.total)*100;
                arr2.push(currentObj);
              }
            );
dataset = [{
    data: arr1,
    name: 'initial'
},{
   data: arr2,
  name: 'remaining'
}];

var series = dataset.map(function (d) {
    return d.name;
}),
dataset = dataset.map(function (d) {
    return d.data.map(function (o, i) {
        // Structure it so that your numeric
        // axis (the stacked amount) is y
        return {
            y: o.percent,
            x: o.os,
            v: o.value
        };
    });
}),
stack = d3.layout.stack(); //.layout in v3

stack(dataset);

var h1= Width * 0.7;
// Set x, y and colors
var x = d3.scale.ordinal()
  .domain(dataset[0].map(function(d) { return d.x; }))
  .rangeRoundBands([0, width], 0.15);

var y = d3.scale.linear()
  .domain([0, d3.max(dataset, function(d) {  return d3.max(d, function(d) { return d.y0+d.y; });  })])
  .range([height, 0]);

var colors = ["#14a900", "#cccccc"];

// Define and draw axes
var yAxis = d3.svg.axis()
  .scale(y)
  .orient("left")
  .ticks(5)
  .tickSize(1)
  .tickFormat( function(d) { return d } )

var xAxis = d3.svg.axis()
  .scale(x)
  .orient("bottom")

// Create groups for each series, rects for each segment

var groups = svg.selectAll("g.cost")
  .data(dataset)
  .enter().append("g")
  .attr("class", "cost")
  .style("fill", function(d, i) { return colors[i]; });

  // Height Calculation of the stack bars
  // y0 will be the base, y is the stacked up bar on y0

var crucial = 0;
var cr = 0;
var heightsof = [];
var rects = groups.selectAll("rect")
  .data(function(d) { return d; })
  .enter()
  .append("rect")
  // .attr("transform","scale(1,1.4)")
  .attr("x", function(d) { return x(d.x); })
  .attr("y", function(d) {
    crucial = y(d.y0 + d.y);
    return  crucial;
  })
  .attr("height", function(d) {
     return height - y(d.y);
   })
  .attr("width", x.rangeBand())

// Getting the length of the total bar
// For tilt angle

var calh=0;
  for(i=0;i<data.length+1;i++){
    var j = data.length;
    if(i==j){
      calh = heightsof[j]+heightsof[0];
    }
  }

  console.log(calh);
  var rect_width = Math.round($("rect").outerWidth());

  svg.append("g")
    .attr("class", "y axis")
    .call(yAxis)
    // .attr("transform","scale(1,)")

  var bool = [],
      counter = 0,
      y = [],
      x = 0,
      z = 0; // max value of y[]

  svg.append("g")
    .attr("class", "x axis")
    .attr("transform", function(){
      return "translate(0,"+(h1)+")";
    })
    .call(xAxis)
    .selectAll("text")
            .style("fill","black")
            .each(function(d,i) {
                    var thisWidth = this.getComputedTextLength();
                    var x = Math.round(thisWidth);
                    y.push(x);
                    if(rect_width>x){
                      bool.push(true);
                    }
                    else{
                      bool.push(false);
                      counter++;
                    }
                    z = Math.max.apply(Math, y);
                  })
                  .style("text-anchor",function(d,i){
                    if(rect_width<=20){
                      return "end";
                    }
                    else {
                      return "middle";
                    }
                  })
                  .attr("transform", function(d,i) {      // Rotation Code
                    if(rect_width<=20) {
                      x = -90;
                      return "translate(-13,8) rotate("+x+")"; //  Minimum width rotation
                    }
                    else if (rect_width>z) {
                      return "rotate(0)";
                    }
                    else if(rect_width>20&&rect_width<z) {
                      var tilt = data.length;
                      var angle = Math.cos(z/rect_width)
                      console.log(angle);
                      if(angle>0&&bool[i]==false){
                        return "translate(-10,"+((y[i]/3)+12)+") rotate(-45)";// -(90-angle*100) +")"; // Rotating based on the maximum angle for proper alignment
                      }
                      if(angle>0&&bool[i]==true){
                        return "translate(-10,"+((y[i]/3)+8)+") rotate(-45)"//"+ -(90-angle*100) +")"; // Rotating based on the maximum angle for proper alignment
                      }
                      else{
                        return "translate(-10,"+((y[i]/3)+12)+") rotate("+ -(90+angle*10) +")"; // Rotating based on the maximum angle for proper alignment
                      }
                        }
                  });

}
<div id="stackChart">
  </div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script>
  stackChart();
  </script>

A:

What you need to do is change the height value of the second <svg> (the legend one) from 100 to 120. I don't know enough about d3.js or your script to make it happen internally, in your script. I could write a javascript snippet to do it on the fly, after the <svg> has been generated, but it would be hack-ish.
I guess with this info and what you know about what your own script, you could get this fixed from the source of that legend.
By courtesy of Gerardo Furtado, this is what you need to do in order for your legend svg to have sufficient room (height) to display labels correctly:

in D3, the axis generator is always created at the origin (0,0) of the SVG. Then, it is translated to whatever position the user wants, and the ticks are created below the axis. Right now, OP is translating it by "translate(0,"+(height)+")", and height is Height -top - bottom;. Thus, the solution is just increasing the value of data.margins.bottom. To do not distort the bars, tell the one would need to increase data.height accordingly.

If you must fit your legend into a 100px height, you will need to apply this CSS rule to it:
transform: scale(factor);
transform-origin:left; /* keep it aligned on left side */

, where factor is lower than 1 in order to shrink. If you don't care about scaling it proportionally, you could limit the scale factor to only Y axis. (using scaleY instead of scale) but this will distort everything in your legend svg, including text.


Q:

Is defining TestMethod's in test base classes not supported by MsTest?

This question concerns a general unit test technique with a potentially very useful wide range of applicable scenarios. But it is easier to understand with an example to illustrate my question better.
Let's say I want to test that all types that override Equals() does so correctly. Since Equals() is defined as virtual in System.Object, a wide range of types may change that behavior. Each type that does so, will have to have tests to make sure that the new behavior follows the implicit expectations of a caller of that method. Specifically for Equals(), if you override that method the new implementation must make sure that two equal objects also have equal hash codes, as defined by System.Object.GetHashCode().
Thus to enforce this, multiple test classes will be needed and they will all test for the same consistency of behavior across all these types.
To avoid having to re-type all the TestMethods required to test such a type I instead define a base test class that looks like below, and have those test classes all inherit the same behavior test suite:
/// <summary>
/// Test fixture base class for testing types that overrides Object.Equals()
/// </summary>
/// <typeparam name="T">The production type under test</typeparam>
public abstract class EqualsFixtureBase<T>
{
    #region Equals tests

    protected static void CompareInstances(T inst1, T inst2, bool expectedEquals)
    {
        Assert.AreEqual(expectedEquals, inst1.Equals((T)inst2));
        Assert.AreEqual(expectedEquals, inst1.Equals((object)inst2));
        if (expectedEquals)
        {
            // equal instances MUST have identical hash codes
            // this is a part of the .NET Equals contract
            Assert.AreEqual(inst1.GetHashCode(), inst2.GetHashCode());
        }
        else
        {
            if (inst2 != null)
            {
                Assert.AreNotEqual(inst1.GetHashCode(), inst2.GetHashCode());
            }
        }
    }

    /// <summary>
    /// Creates version 1 instance of the type under test, not 'Equal' to instance 2.
    /// </summary>
    /// <returns>An instance created with properties 1.</returns>
    protected abstract T CreateInstance1();

    /// <summary>
    /// Creates version 2 instance of the type under test, not 'Equal' to instance 1.
    /// </summary>
    /// <returns>An instance created with properties 2.</returns>
    protected abstract T CreateInstance2();

    /// <summary>
    /// Creates an instance equal to the version 1 instance, but not the identical
    /// same object.
    /// </summary>
    /// <returns>An instance created with properties equal to instance 1.</returns>
    protected abstract T CreateInstanceThatEqualsInstance1();

    [TestMethod]
    public void Equals_NullOrDefaultValueTypeInstance()
    {
        T instance = CreateInstance1();
        CompareInstances(instance, default(T), false);
    }

    [TestMethod]
    public void Equals_InstanceOfAnotherType()
    {
        T instance = CreateInstance1();
        Assert.IsFalse(instance.Equals(new object()));
    }

    [TestMethod]
    public void Equals_SameInstance()
    {
        T slot1 = CreateInstance1();
        CompareInstances(slot1, slot1, true);
    }

    [TestMethod]
    public void Equals_EqualInstances()
    {
        T slot1 = CreateInstance1();
        T slot2 = CreateInstanceThatEqualsInstance1();
        CompareInstances(slot1, slot2, true);
        CompareInstances(slot2, slot1, true);
    }

    [TestMethod]
    public void Equals_NonEqualInstances()
    {
        T slot1 = CreateInstance1();
        T slot2 = CreateInstance2();
        CompareInstances(slot1, slot2, false);
        CompareInstances(slot2, slot1, false);
    }

    #endregion Equals tests
}

I can then reuse these TestMethods for each type overriding Equals(). For instance, this would be the test class definition for testing that the System.String type implements Equals() correctly.
[TestClass]
public class ExampleOfAnEqualsTestFixture : EqualsFixtureBase<string>
{
    [TestMethod]
    public void Foo()
    {
        Assert.IsTrue(true);
    }

    protected override string CreateInstance1()
    {
        return "FirstString";
    }

    protected override string CreateInstance2()
    {
        return "SecondString";
    }

    protected override string CreateInstanceThatEqualsInstance1()
    {
        return "FirstString";
    }
}

This can also be extended further. For instance, for types that overload the == and != operators, a second abstract test base class can be defined (i.e. EqualsOperatorsFixtureBase<T> : EqualsFixtureBase<T>) that tests that the implementation of those operators are not only correct, but also consistent with the extended definitions of Equals() and GetHashCode().
I can do this using NUnit, but when using MsTest I get problems.
a) Visual Studio 2010 only discovers the Foo() test method, not the inherited test methods so it can't run them. It seems the Visual Studio test loader does not walk the inheritance hierarchy of the test class.
b) When I check in these types in TFS, TFS finds the abstract EqualsFixtureBase type and thinks it is a test class to be run. But since it can not be created, it can't run it and labels the tests in that type as inconclusive - which fails the test run, and thus the build (!).
Is there a way to get around this, or is this a limitation of MsTest and Visual Studio?
If so, is fixing this in the roadmap for VS/TFS ??
This would be very useful, especially when testing production types that implement an interface, or are part of an inheritance hierarcy, where certain members have semantic 'contract type' properties or invariants - if that makes sense.
Basically, not having support for this inhibits me from refactoring my test code to remove duplication.
Thanks
EDIT: I found this link to one of the MSDN blogs, it says the following

"In Whidbey, support for test class inheritance was missing. In Nunit, it is fully supported. This will be rectified in Orcas."

That was written over three years ago. Why has this not been added yet? I don't get it, there are legitimate reasons to have this and in my mind it would be a minor change. Or am I just not jumping the right hoops here?

A:

Using VS 2010 I am not seeing the same behavior as you are. When I copied your 2 classes into a test project and compiled it I got the output:
UTA004: Illegal use of attribute...The TestMethodAttribute can be
defined only inside a class marked with the TestClass attribute

So I marked EqualsFixutureBase:
[TestClass]
public abstract class EqualsFixtureBase<T>
{
...
}

Now it compiles without warning and when I select run tests for ExampleOfAnEqualsTestFixture it runs Foo and all 5 of the inherited equals tests. Also when I copy the ExampleOfAnEqualsTestFixture and use it for int and run the tests for the solution I see all 5 inherited tests running (and passing) for the example string class and the example int class.
Are you doing something in addition to your example which might be causing your problem?

A:

The TestClassAttribute allows you to put methods in the abstract base.  The IgnoreAttribute excludes the base class from the list of tests. Without the IgnoreAttribute attribute methods within base are executed for both the base class and in subclasses marked with the TestClassAttribute, .
[TestClass][Ignore]
public abstract class EqualsFixtureBase<T>
{
....

A:

Out of the box, it looks like unit test inheritance only works if the base test class is in the same assembly as the derived classes. For me, this usually defeats the purpose of having the base class. I, too, wonder why there isn't more posted about this on blogs, and if I might be missing something.
You might be able to work around the problem by linking the base class into every project where you want to use it. Maybe mark it as internal so the multiple copies don't interfere with each other.
There's also the TestClassExtensionAttribute that you can extend to hook into the test execution engine. I tried using it to reflect over the test classes and load the base class's tests, but a lot of the classes are undocumented, and I couldn't get it to work.


Q:

Rust HashMap find_or_insert

Why does HashMap.find_or_insert(k,v) return a &mut type, and how do it get it to return a type?
I just started using Rust for a course, and I am using a HashMap<int, int> and want to get an int back.
let mut m: HashMap<int, int> = HashMap::new();
println!("{:d}", m.find_or_insert(1,2));

gives me an error saying that it failed to find an implementation of trait std::fnt::Signed for &mut int.

Edit1:
I am using Rust 0.9 on Windows 8.1, using msys.
My code so far
use std::hashmap::HashMap;

fn main() {
    let mut m: HashMap<int, int> = HashMap::new();
    println!("{:d}", *m.find_or_insert(1,2))
}

I tried this code again and it properly returns 2

A:

Why does find_or_insert return a reference? Copying isn’t always possible/efficient.
How can you use that reference in the case of an integer? Dereference it with a *:
let mut m: HashMap<int, int> = HashMap::new();
println!("{:d}", *m.find_or_insert(1,2));


Q:

Insert n rows stored procedure

Trying to insert multiple rows based on a passed parameter.
Tried this and it only repeated once:
ALTER PROCEDURE [dbo].[ActivateCertificates]

    @Count              int,
    @CertificateNumber  int,
    @Buyer              VarChar(50)

AS
Declare @x int
Declare @InitialCharacter   Char(1)
SET @InitialCharacter='C'
Declare @Last3      Char(3)
SET @Last3='867'

    while @x <= @Count
begin
    /* CREATE THE CERTIFICATE NUMBER */
    set @CertificateNumber = @CertificateNumber +1
    /* insert into certificates  cert number and who sold to. */
    INSERT into Certificates (CertificateNumber,Buyer)
    VALUES (@InitialCharacter + ltrim(rtrim(cast(@CertificateNumber as char))) + @Last3, @Buyer)
end
set @x =@x + 1

GO

A:

To achieve your goal using a set-based query instead of a loop (BTW there are lots of such examples here on StackOverflow) you'll have to have a tally (numbers) table or create it on a fly with a subquery or recursive CTE.
CREATE TABLE tally (id INT NOT NULL PRIMARY KEY);

To populate it up to 100000 (Celko-style)
INSERT INTO tally (id)
SELECT a.N + b.N * 10 + c.N * 100 + d.N * 1000 + e.N * 10000 + 1 as N
  FROM (select 0 as N union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) a
      , (select 0 as N union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) b
      , (select 0 as N union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) c
      , (select 0 as N union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) d
      , (select 0 as N union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) e
ORDER BY N;

Now your stored procedure boils down to one statement
CREATE PROCEDURE ActivateCertificates
  @Count              INT,
  @CertificateNumber  INT,
  @Buyer              VARCHAR(50)
AS
INSERT INTO Certificates (CertificateNumber, Buyer)
SELECT 'C' + CAST(q.number + t.id AS VARCHAR(12)) + '867', q.buyer
  FROM
(
  SELECT @CertificateNumber number, @Buyer buyer
) q, tally t
WHERE t.id <= @Count;

Here is SQLFiddle demo
Now if you generate relatively small amounts of certificates (< 32768) then you can use recursive CTE to build a sequence of numbers (and don't need a persisted tally table)
CREATE PROCEDURE ActivateCertificates
  @Count              INT,
  @CertificateNumber  INT,
  @Buyer              VARCHAR(50)
AS
WITH tally AS (
  SELECT 1 id
  UNION ALL
  SELECT id + 1 FROM tally WHERE id < @Count
)
INSERT INTO Certificates (CertificateNumber, Buyer)
SELECT 'C' + CAST(q.number + t.id AS VARCHAR(12)) + '867', q.buyer
  FROM
(
  SELECT @CertificateNumber number, @Buyer buyer
) q, tally t OPTION (MAXRECURSION 32767);

Here is SQLFiddle demo for that case


Q:

Simple button click connection to python function

I have a very simple Qml/Python application with some content in a StackView(), with the first page containing a simple button. My question is, does EVERYTHING between Qml and Python work via signals only? Or can the button click fire/call a function directly from a python script?
Haven't tried much, as I am not sure how to proceed from here
main.qml
import QtQuick 2.12
import QtQuick.Controls 2.5
import QtQuick.Layouts 1.5
import "custom/components"

ApplicationWindow {
    visible: true
    width: 800
    height: 600
    minimumWidth: 800
    minimumHeight: 600

    title: qsTr('Primer')

    property bool authorized: false

    signal change_page(bool change)

    // Main Container - View
    StackView {
        id: view
        anchors.fill: parent
        initialItem: home
    }

    // Page Content
    Component {
        id: home
        Page {
            title: qsTr('Home')

            GenButton {
                text: "To Orders"
                bg_color: "white"
                txt_color: "grey"

                onClicked: homeFunc.changePage()
            }
        }
    }

    Component {
        id: orders
        Page {
            title: qsTr('Orders')
        }
    }

    Component {
        id: quotes
        Page {
            title: qsTr('Quotes')
        }
    }

}

GenButton.qml
import QtQuick 2.12
import QtQuick.Controls 2.5

Button {
    id: ctrl

    property color bg_color: "white"
    property color txt_color: "black"

    background: Rectangle {
        color: ctrl.pressed ? Qt.darker(bg_color, 1.25) : bg_color
    }

    contentItem: Text {
        text: ctrl.text
        padding: ctrl.padding
        horizontalAlignment: Text.AlignHCenter
        verticalAlignment: Text.AlignVCenter
        font.family: "Segoe UI"
        font.pixelSize: 14
        color: txt_color
    }
}

main.py
import sys
from PyQt5.QtGui import QGuiApplication, QIcon
from PyQt5.QtQml import QQmlApplicationEngine
from resources.functions.homeFunctions import HomeFunctions

APP = QGuiApplication(sys.argv)
APP.setWindowIcon(QIcon('resources/img/primerLogo.png'))

home_func = HomeFunctions()

ENGINE = QQmlApplicationEngine()
ENGINE.rootContext().setContextProperty('homeFunc', home_func)
ENGINE.load('resources/qml/main.qml')
ENGINE.quit.connect(APP.quit)

sys.exit(APP.exec_())

homeFunctions.py
from PyQt5.QtCore import QObject

class HomeFunctions(QObject):
    def __init__(self):
        QObject.__init__(self)

    def changePage(self):
        print("Button was pressed")

Expected result would be for the terminal to print the message "Button was pressed", a very simple example, which could probably have been achieved a 1000 different other ways, but this is merely just a test
The error received is the following:
file:///D:/Personal Backups/CodingProjects/PycharmProjects/calico/resources/qml/main.qml:40: TypeError: Property 'changePage' of object HomeFunctions(0xc3f5c8) is not a function

A:

Explanation:
QML uses the MetaObject (MOC) of the QObjects to access the properties, signals and slots, in your case changePage is not a slot but a function that is not accessible from QML.
Solution:
The solution is to make the changePage function accessible in QML using the @pyqtSlot decorator:
homeFunctions.py
from PyQt5.QtCore import pyqtSlot, QObject

class HomeFunctions(QObject):
    @pyqtSlot()
    def changePage(self):
        print("Button was pressed")


Q:

Servlet filters not working properly

I have a login.java servlet, from where after taking the username and password, if correct, we are directed to welcome.java servlet.A filter named loginfilter.java verifies the username and password. If the username and password are not correct, i have an errorpage.java servlet which is then called.
My filter is not working which i dont know why. i think my web.xml code and filters code are correct. Plz help me find out the error.
Here is the code for my filter
package filters;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class loginfilter implements Filter{

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain
    chain throws IOException, ServletException     {
           String u=request.getParameter("username");
           String p=request.getParameter("password");
           String user="akshay";
           String pass="akshay";
           if (u.equals(user) && p.equals(pass)){
               chain.doFilter(request,response);
           }
     }

    @Override
    public void destroy() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    private RequestDispatcher getReuestDispatcher(String loginpage) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

}

Here is the code for web.xml:
<?xml version="1.0" encoding="UTF-8"?>
    <servlet>
        <servlet-name>login</servlet-name>
        <servlet-class>login</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>welcomepage</servlet-name>
        <servlet-class>welcomepage</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>errorpage</servlet-name>
        <servlet-class>errorpage</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>login</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>
    <error-page>
        <error-code>404</error-code>
        <location>/errorpage</location>
    </error-page>
    <error-page>
        <error-code>403</error-code>
        <location>/errorpage</location>
    </error-page>
    <error-page>
        <exception-type>javax.servlet.ServletException</exception-type>
        <location>/errorpage</location>
    </error-page>
    <error-page>
        <exception-type>javax.io.IOException</exception-type>
        <location>/errorpage</location>
    </error-page>
    <filter>
        <filter-name>loginfilter</filter-name>
        <filter-class>filters.loginfilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>loginfilter</filter-name>
        <servlet-name>welcomepage</servlet-name>
    </filter-mapping>
    <servlet-mapping>
        <servlet-name>welcomepage</servlet-name>
        <url-pattern>/welcomepage</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>errorpage</servlet-name>
        <url-pattern>/errorpage</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

A:

Remove the lines with:
throw new UnsupportedOperationException("Not supported yet.");

These lines prevent the filter is initialized, and also stops the application.

The server calls init(FilterConfig) once to prepare the filter for service, then calls doFilter() any number of times for requests specially set up to use the filter. The FilterConfig interface has methods to retrieve the filter's name, its init parameters, and the active servlet context. The server calls destroy() to indicate that the filter is being taken out of service.

http://www.servlets.com/soapbox/filters.html


Q:

Why do I have to enable peripheral clocks one at a time?

In a minimal STM32 application I've written that writes characters to USART1, the USART doesn't seem to work when I try to enable all the clocks I need at once:
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA
                       | RCC_APB2Periph_AFIO
                       | RCC_APB2Periph_USART1, ENABLE);

But when I enable the clocks one at a time, it works:
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,  ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,   ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);

Why is this? Is there a specific order these clocks have to be enabled in? (If so, where is this documented?)
(I've left out all the code following this that initializes the GPIO pins, sets up the USART, and starts sending content, as it's the same in each application. If it's relevant, let me know and I'll include it.)
The device I'm using is the STM32F103VET6.

Since there's some interest in the assembly involved, here it is. For all three clocks at once:
00000000 <main>:
   0:   b590            push    {r4, r7, lr}
   2:   b089            sub     sp, #36 ; 0x24
   4:   af00            add     r7, sp, #0
   6:   f244 0014       movw    r0, #16389      ; 0x4005
   a:   2101            movs    r1, #1
   c:   f7ff fffe       bl      0 <RCC_APB2PeriphClockCmd>

And for one clock at a time:
00000000 <main>:
   0:   b590            push    {r4, r7, lr}
   2:   b089            sub     sp, #36 ; 0x24
   4:   af00            add     r7, sp, #0
   6:   2004            movs    r0, #4
   8:   2101            movs    r1, #1
   a:   f7ff fffe       bl      0 <RCC_APB2PeriphClockCmd>
   e:   2001            movs    r0, #1
  10:   2101            movs    r1, #1
  12:   f7ff fffe       bl      0 <RCC_APB2PeriphClockCmd>
  16:   f44f 4080       mov.w   r0, #16384      ; 0x4000
  1a:   2101            movs    r1, #1
  1c:   f7ff fffe       bl      0 <RCC_APB2PeriphClockCmd>
  ...

And here's RCC_APB2PeriphClockCmd:
00000000 <RCC_APB2PeriphClockCmd>:
   0:   4b04            ldr     r3, [pc, #16]   ; (14 <RCC_APB2PeriphClockCmd+0x14>)
   2:   699a            ldr     r2, [r3, #24]
   4:   b109            cbz     r1, a <RCC_APB2PeriphClockCmd+0xa>
   6:   4310            orrs    r0, r2
   8:   e001            b.n     e <RCC_APB2PeriphClockCmd+0xe>
   a:   ea22 0000       bic.w   r0, r2, r0
   e:   6198            str     r0, [r3, #24]
  10:   4770            bx      lr
  12:   bf00            nop
  14:   40021000        .word   0x40021000

0x40021000 is the base address of the RCC peripheral; the #24 offset points to the RCC_APB2ENR register, which has a bit for each clock that's being enabled. (See page 109 of RM0008 for details.)

A:

Well, I think I figured it out, and it turned out to not be a hardware problem at all... there were a number of problems with my toolchain configuration:

I was setting -nostdlib. This was causing some global initialization code to not be generated. I'm not sure how important that was, but other issues included:
I was not passing -mthumb and other CPU options to the linker. This was causing some of the generated startup code to be garbage.
My startup file didn't contain a call to __libc_init_array. This was causing some more initialization code to be dropped at link time.

I'm still not sure why splitting up the peripheral clock initializations managed to work around this. Perhaps the change in the amount of code was bumping something to just the right alignment? Anyways, solving the underlying issues seems to have patched things up so far (although I'm still kind of suspicious of some of the remaining startup code).


Q:

How to make a script accessible to root user?

A regular user can run this script, but root can't find it.
I have a simple script that I have saved in ~/bin. I updated the .profile file to include this folder in the PATH. I can go into terminal, be working in any directory, type the name of the script and it runs fine.  But if in that terminal I switch to root, the script cannot be found.  I assume there is some file somewhere which needs a new $PATH update, but I don't know which one.

A:

If you're using sudo, which is probably the case, there is a security policy that modifies the $PATH environment variable to a secure path (defined in the file /etc/sudoers). The ~/bin directory isn't included in the default secure_path set in the sudoers file, so running sudo script wouldn't work, but sudo ~/bin/script would.
You can place the script in one of the folders defined in the sudoers configuration file (i.e. /usr/local/bin) to make it directly accessable. The secure_path can also be changed on the configuration file, though it's not recommended.


Q:

taking time to load GWT sample project

I have created one GWT project by using Google plugin. When I run the project, it takes time to display in the browser. Almost it takes 10 seconds to display in the browserI have used google plugin's greeting service. It includes One textfield and one button. .What is the reason for taking this much time? What should I need to take care extra to avoid this delay?
Following are my configurations
 Eclipse3.6, GWT 2.3 and Tomcat 7.

A:

You see the slowdown since 2.0, because 2.0 introduced the new approach with the development mode. See GWT 2.0 release notes. To avoid it, you not only need to compile the code as suggested here, but also remove the ?gwt.codesvr=127.0.0.1:9997 from URL.
Just to add - you should see the slow down only when you enter an URL. Later, when you modify your code and reload only it is much faster. At least this is how it works for me in FF. Surprisingly Chrome is much worse in it from my experience.
Also - development mode is when you make a default run in Eclipse. It does not need to be in debug.


Q:

How to mock classes with constructor injection

How to get constructor injection in Mockito
I have the following class:
class A {

  private B mB;

  A(B b) {
     mB = b;
  }

 void String someMethod() {
     mB.execute();
  }
}

how do I test someMethod using a mock class A and class B using
B b = Mockito.mock(B.class)
Mockito.when(b.execute()).thenReturn("String")

A a = Mockito.mock(A.class)
//somehow inject b into A and make the below statement run
Mockito.when(a.someMethod()).check(equals("String"))

A:

In my opinion, you're mixing up two ways of testing.
If you want to write a test using Mockito, you just create a mock of some class and use it. This mock doesn't have anything related to a real object as you can (should) mock every method that is called in the test. That's why it doesn't make any sense to mock class B - it is simply not used by class A.
Otherwise, if you want to test a real behavior of class A then why do you want to mock it? Create a real instance of class A with a mocked instance of class B.
That's it! Don't mix it up.

A:

Another way of injecting a mock to real object (as A should be a real object) is to use annotations, they will create objects you want:
@Mock
B mockOfB;

@InjectMocks
A realObjectA;

@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
}

Then, like they said, run the method you want to test without mockito (because you want to test it, so call it on real instance) and check the result according to your expectations.
Behaviour of object B can be mocked in any way, to satisfy your needs.

A:

You want to test someMethod() of class A. Testing the execute() of class B should take place in the other test, because instance of B is a dependency in your case. Test for execute() should be made in different test.
You don't need to test how B object will behave, so you need to mock it and afterwards, check that execute() was invoked.
So in your case your test will look something like this:
  B b = Mockito.mock(B.class);
  A a = new A( b );
  a.someMethod();
  Mockito.verify( b, Mockito.times( 1 ) ).execute();


Q:

Max value of feild using Elastic Search Python API

Hello I'm trying to get the max value of a field "UID" from Elasticsearch using its Python API. When I try it using below code I get an error.
res = es.search(index="some_index", body={"query": {"size": 0,
"aggregations": {
"maxuid": {
  "max": {
    "field": "UID"
  }}}}})
print(res)

elasticsearch.exceptions.RequestError: TransportError(400, u'parsing_exception', u'no [query] registered for [aggregations]')

I have a curl command for the same request which works, but when I use query in the body for Python API it gives the above error.
This is the curl request which works and gives me expected results. How to use this in Elasticsearch Python API is the problem I'm facing.
GET some_index/some_doc/_search{
"size": 0,
"aggregations": {
"maxuid": {
"max": {
"field": "UID"
}}}}

Any help on this is greatly appreciated. Thanks.

A:

Something like this would work:
res = es.search(
      index="some_index",
       body={
        "aggs": {
          "maxuid": {
            "max": { "field": "UID"}
          }
       }
    }
)
print(res)

You can't specify aggregations inside query clause, aggregations and query are two different clauses and that's the reason you're getting that exception.
A rough structure looks like this:
res = es.search(
       index="some_index",
       body={
        "query": {},
        "size": 0,
        "aggs": {
          "maxuid": {
            "max": { "field": "UID"}
          }
        }
    }
)

I haven't run the request so you might have to tweak it a bit.
PS: I am not a python guy :)


Q:

is there other styles in visual studio 2013 for my forms

i'm developping on vb using visual studio 2013.
in my application i'm focusing on the graphics part more than the code. I'm looking if there is any other styles that i can apply for my forms, buttons , textboxs ... other than the classic forms and textboxs ?
for example can i create some buttons like the windows 8 buttons without creating a windows store project.

A:

I suppose you work with vb and WinForms? If so, you might wanna try working with WPF instead of WinForms. To describe it very vagualy, it allows you to define your ui by xml (like css).


Q:

Get object on onActivityResult

I make a new activity that create a Bluetooth device object. When I need return this using onActivityResult() method, I have a problem.
Child activity
Intent intent = new Intent();
            intent.putExtra("BluetoothDevice", DeviceArrayList.get(arg2));
            setResult(Activity.RESULT_OK, intent);
            finish();

DeviceArrayList.get(arg2) is the device Object.
Parent activity
 BluetoothDevice btDevice;
...

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

            if (requestCode == 1) {
                if(resultCode == Activity.RESULT_OK){

                    btDevice = data.getExtras("BluetoothDevice");

                }
                if (resultCode == Activity.RESULT_CANCELED) {
                    Toast.makeText(this, "Resultado cancelado", Toast.LENGTH_SHORT)
                            .show();
                }
            }
        }//onActivityResult

Who I can get the object in btDevice?

A:

Make your bluetooth device class serializabale or parceable. And then you can pass it to the second activity using intent:
intent.putExtra("bluetooth", myBluetoothDeviceObject);

And you can get the same in your second activity using:
intent.getParcelableExtra("bluetooth")

I prefer parceable over serializable.
Please look at the android docs for more info:
http://developer.android.com/reference/android/os/Parcelable.html


Q:

XPATH in Android

I have an xml file
XMLParsing.java read all the file XML
My goal is displayed only the part when the text is equal. This code display all the file
if i try this code, it doesn't work
    XPath xpath = XPathFactory.newInstance().newXPath();
    String expression = "/postes/poste";
    InputSource inputSource = new InputSource("postes.txt");
    Node nodes =(Node) xpath.evaluate(expression, inputSource, XPathConstants.NODE);

the error message is on this line Node nodes =(Node) xpath.evaluate(expression, inputSource, XPathConstants.NODE); inputSource can not be resolved
and if i try this code
   XPathFactory xPathFactory = XPathFactory.newInstance();
            // To get an instance of the XPathFactory object itself.
            XPath xPath = xPathFactory.newXPath();
            // Create an instance of XPath from the factory class.
            String expression = "/postes/poste[gouvernorat=text]";
            XPathExpression xPathExpression = xPath.compile(expression);

            // Compile the expression to get a XPathExpression object.
            Object result = xPathExpression.evaluate(R.raw.postes);
            //Evaluate the expression against the XML Document to get the result.

The error is in to lines xPath.compile(expression); and xPathExpression.evaluate(R.raw.postes);
i added this import javax.xml.xpath.*;
but it doesn't work
I Try DOM Parser but it doesn't work also ; i can't read the file
please help me
Thank you in advance.

A:

My guess is you are not targeting you application to API Level 8 (2.2) or higher. You can see on the Xpath Documentation Pages that it is only available since API Level 8 (top right corner). Also shown by this bug.
If you'd still like to support lower versions of Android, you must include a third party library to provide XPath functionality such as dom4j.


Q:

Form in Bootstrap goes wrong

Here's my code:

Keterangan Badan

              Tinggi Badan

                  <input type="text" class="form-control" name="tinggi_badan" id="tinggi_badan" placeholder="Tinggi Badan">

              Berat Badan

                  <input type="text" class="form-control" name="berat_badan" id="berat_badan" placeholder="Berat Badan">

              Jenis Rambut

                  <input type="text" class="form-control" name="alamat" id="alamat" placeholder="Jenis Rambut">

              Bentuk Wajah

                  <input type="text" class="form-control" name="alamat" id="alamat" placeholder="Bentuk Wajah">

              Warna Kulit

                  <input type="text" class="form-control" name="warna_kulit" id="warna_kulit" placeholder="Warna Kulit">

Keterangan Lainnya

But the result is:

And then the other sides had some problems too.
Here's the code:
Tempat Lahir

    <input type="text" class="form-control" name="ttl_propinsi" id="ttl_propinsi" placeholder="ttl_propinsi">
    <input type="text" class="form-control" name="ttl_kota" id="ttl_kota" placeholder="ttl_kota">
    <input type="text" class="form-control" name="ttl_tempat" id="ttl_tempat" placeholder="ttl_tempat">

  Tanggal Lahir

    <input type="text" class="form-control" name="tanggal lahir" id="tanggal lahir" placeholder="Tanggal Lahir">

  Jenis Kelamin

    <select name="jenis_kelamin" class="form-control">
      <option value=""></option>
    </select>

  Gol Darah

    <input type="text" class="form-control" name="gol_darah" id="gol_darah" placeholder="Gol Darah">

And here's the result:

Should I make some CSS there?

A:

The problem in your design is that your labels are not able adjust within their designated space. I'll advice increasing the label's grid size to 3 and decreasing input box's grid size to 9.
Please refer code.
            Tinggi Badan

                <input type="text" class="form-control" name="tinggi_badan" id="tinggi_badan" placeholder="Tinggi Badan">

The other problem simply requires you to add margin.

Now add the class mb10 to your form controls.

    <input type="text" class="form-control mb10" name="ttl_propinsi" id="ttl_propinsi" placeholder="ttl_propinsi">
    <input type="text" class="form-control mb10" name="ttl_kota" id="ttl_kota" placeholder="ttl_kota">
    <input type="text" class="form-control mb10" name="ttl_tempat" id="ttl_tempat" placeholder="ttl_tempat">


Q:

Screen.AllScreen is not giving the correct monitor count

I am doing something like this in my program:
Int32 currentMonitorCount = Screen.AllScreens.Length;

if  (currentMonitorCount < 2)
{
   //Put app in single screen mode.
}
else
{
   //Put app in dual screen mode.
}

It is VERY important my application recognizes how many monitors are currently connected.
However, after I plug/unplug the monitor a couple of times, Screen.AllScreens.Length always returns '2'.
My monitor knows it's not connected (it has entered 'power save' mode), and the control panel knows that it's not connected (it shows only one monitor).
So what am I missing?  How do I figure out that there's only one monitor?

A:

I had a look at the source (remember we can do that using the MS Symbol servers). AllScreens uses an unmanaged API to get the screens on the first access, then stores the result in a static variable for later use.
The consequence of this, is that if the number of monitors changes while your program is running; then Screen.AllScreens will not pick up the change.
The easiest way to get around this would probably be to call the unmanaged API directly.
(Or you could be evil, and use reflection to set the static screens field to null before asking. Don't do that).
Edit:
If you just need to know the count, check whether you can use System.Windows.Forms.SystemInformation.MonitorCount (as suggested in the comments) before going the P/Invoke route. This calls GetSystemMetrics directly, and it is probably correctly updated.
If you find you need to do it using P/Invoke, here is a complete example that demonstrates the usage of the unmanaged API from C#:
using System;
using System.Runtime.InteropServices;

class Program
{
    public static void Main()
    {
        int monCount = 0;
        Rect r = new Rect();
        MonitorEnumProc callback = (IntPtr hDesktop, IntPtr hdc, ref Rect prect, int d) => ++monCount > 0;
        if (EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, callback, 0))
            Console.WriteLine("You have {0} monitors", monCount);
        else
            Console.WriteLine("An error occured while enumerating monitors");

    }
    [DllImport("user32")]
    private static extern bool EnumDisplayMonitors(IntPtr hdc, IntPtr lpRect, MonitorEnumProc callback, int dwData);

    private delegate bool MonitorEnumProc(IntPtr hDesktop, IntPtr hdc, ref Rect pRect, int dwData);

    [StructLayout(LayoutKind.Sequential)]
    private struct Rect
    {
        public int left;
        public int top;
        public int right;
        public int bottom;
    }
}

A:

Building on the previous reply by driis, this is how I handled it.  I should note that the following code lives in my Program.cs file.
First the links to external resources and data structures:
    [DllImport("user32")]
    private static extern bool EnumDisplayMonitors(IntPtr hdc, IntPtr lpRect, MonitorEnumProc callback, int dwData);

    private delegate bool MonitorEnumProc(IntPtr hDesktop, IntPtr hdc, ref Rect pRect, int dwData);

    [StructLayout(LayoutKind.Sequential)]
    private struct Rect
    {
        public int left;
        public int top;
        public int right;
        public int bottom;
    }

Now create a simple object to contain monitor information:
public class MonitorInfo
{
    public bool IsPrimary = false;
    public Rectangle Bounds = new Rectangle();
}

And a container to hold these objects:
    public static List<MonitorInfo> ActualScreens = new List<MonitorInfo>();

and a method to refresh the container:
    public static void RefreshActualScreens()
    {
        ActualScreens.Clear();
        MonitorEnumProc callback = (IntPtr hDesktop, IntPtr hdc, ref Rect prect, int d) =>
        {
            ActualScreens.Add(new MonitorInfo()
                {
                    Bounds = new Rectangle()
                    {
                        X = prect.left,
                        Y = prect.top,
                        Width = prect.right - prect.left,
                        Height = prect.bottom - prect.top,
                    },
                    IsPrimary = (prect.left == 0) && (prect.top == 0),
                });

            return true;
        };

        EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, callback, 0);
    }

Then later on a Form, If I wanted to detect that a display had been added or removed ...
    private const int WM_DISPLAYCHANGE = 0x007e;

    protected override void WndProc(ref Message message)
    {
        base.WndProc(ref message);

        if (message.Msg == WM_DISPLAYCHANGE)
        {
            Program.RefreshActualScreens();
            // do something really interesting here
        }
    }

Might be a few typos in there, but that is the basic idea.  Good luck!


Q:

GROUP_CONCAT: search for subset and retrieve all values

I have this two tables:
posts
+--------------------------------------------------------------------+
|id          ¦status¦type ¦url                                       |
+------------+------+-----+------------------------------------------+
|25949664    ¦80    ¦link ¦http://example.com/25949664               |
|25777570    ¦80    ¦photo¦http://example.com/25777570               |
+--------------------------------------------------------------------+

attributes
╔════════════╦════════════╦══════════════════════════════════════════╗
║id          ║attr        ║value                                     ║
╠════════════╬════════════╬══════════════════════════════════════════╣
║25949664    ║timestamp   ║1430836105                                ║
║25949664    ║tag         ║red                                       ║
║25949664    ║tag         ║yellow                                    ║
║25949664    ║tag         ║brown                                     ║
║25949664    ║source      ║http://example.com/wallin/                ║
║25949664    ║source_title║wallin                                    ║
║25949664    ║state       ║published                                 ║
║25949664    ║format      ║html                                      ║
║25777570    ║timestamp   ║1430836105                                ║
║25777570    ║tag         ║red                                       ║
║25777570    ║tag         ║yellow                                    ║
║25777570    ║tag         ║brown                                     ║
║25777570    ║tag         ║black                                     ║
║25777570    ║tag         ║orange                                    ║
╚════════════╩════════════╩══════════════════════════════════════════╝

Performing this query:
  SELECT posts.id, GROUP_CONCAT(attributes.value) as tags
    FROM posts
    JOIN attributes ON attributes.id = posts.id
   WHERE ( attributes.attr = 'tag' )
     AND ( attributes.value IN ('red','brown') )
GROUP BY posts.id
  HAVING COUNT(DISTINCT attributes.value) = 2

I have this result:
╔════════════╦════════════╗
║id          ║tags        ║
╠════════════╬════════════╣
║25949664    ║red,brown   ║
║25777570    ║red,brown   ║
╚════════════╩════════════╝

I would rather have this:
╔════════════╦════════════════════════════════╗
║id          ║tags                            ║
╠════════════╬════════════════════════════════╣
║25949664    ║red,yellow,brown                ║
║25777570    ║red,yellow,brown,black,orange   ║
╚════════════╩════════════════════════════════╝

Practically, having n tags, I would retrieve all post's tags performing only one query.
Anyone have a suggestion, or this is totally impossible?

A:

  SELECT posts.id, GROUP_CONCAT(attributes.value) as tags
    FROM posts
    JOIN attributes ON attributes.id = posts.id
   WHERE ( attributes.attr = 'tag' )
     AND ( attributes.value IN ('red','brown') )
GROUP BY posts.id

With the and condition, you only get the attributes red and brown. So you need to remove this and condition and rewrite that condition.
I think that this can help you:
 SELECT posts.id, GROUP_CONCAT(attributes.value) as tags
    FROM posts
    JOIN attributes ON attributes.id = posts.id
   WHERE ( attributes.attr = 'tag' )
GROUP BY posts.id
  HAVING Find_In_Set('red',tags)>0 AND Find_In_Set('brown',tags)>0

Online Demo


Q:

Why is phenol more polar than alcohol?

Why is phenol more polar than alcohol. I mean the benzene ring seems to be extremely unpolar. Furthermore, is the hydrogen bonding stronger in phenol than in alcohol? Are polarity and hydrogen bonding related (in hydroxy compounds)?
I am doing TLC and I was taught that hydrogen bonding can occur with the alcohol/phenol and that alcohol has stronger hydrogen bonding to the silica gel than it would have despite the lower polarity a lower Rf value than phenol.
But to be honest I am very unsure about those teachings.

A:

The OH group of phenol is indeed more polarized - and a stronger acid - than the OH group of an aliphatic alcohol - maybe that is what you are asking. There are two contributions to this:
(1) inductive: the sp2 hybridized carbon participating in the sigma bond to the OH group is more electron-withdrawing than the sp3-hybridized carbon of an alcohol bonded to OH; and
(2) mesomeric: the phenyl group allows non-bonding electrons on oxygen to partially delocalize into the ring via pi bonding.


Q:

Does every git tag have an associated commit id?

I ran:
$ git log master

I got:
commit 7940b82568e1d28a76557fbb403c46c3ef3cfe90 (tag: prod-api-2019-04-23, master)
Author: Kent Mills <kent.clark@mwzx.com>
Date:   Tue Apr 23 10:33:12 2019 -0700

I am wondering - wrt git tags - does every git tag have a unique commit id associated with it?
For example, if I run git tag how can I see what the commit id's are for those tags? Something like git tag --full or something.

A:

Tags come in one or two parts:

There's a tag name, which is a reference, much like a branch name, except that branch b has full name refs/heads/b while tag t has full name refs/tags/t.
All references store one (1) hash ID.  Branch names are constrained to store only commit hash IDs, even though there are four object types: commit, tree, blob, and annotated tag.  Tag names are not constrained this way.
If the hash ID stored in the tag reference is the ID of a tag object, the tag object itself stores more data.  The data include:

the name of the tagger;
an optional PGP key;
the hash ID of another Git object.

The other Git object here is usually a commit, but that's not a hard and fast requirement: like a tag reference, the tag object can point to another object of any type, even another tag object.

When a tag name points to a tag object, Git calls that an annotated tag.  Otherwise, Git calls that reference a lightweight tag.
To turn a reference name into its object, use git rev-parse:
git rev-parse refs/heads/master
git rev-parse refs/tags/v1.2

for instance.  By default, git rev-parse finds the target object hash ID and stops there, but you can instruct it to keep going:

The suffix ^{commit} tells git rev-parse that if the object itself is not a commit, but might lead to a commit, keep working.  If the object eventually leads to a commit—e.g., if the object is a tag object and its target is another tag object and that second tag object's target is a commit—this "following" process succeeds, and git rev-parse prints the ID of the commit.  If the object eventually leads elsewhere—e.g., if the object is a tag object, but the target of this tag object is a blob—the operation fails and git rev-parse prints an error message to stderr, and no hash ID to stdout.
The suffix ^{tree} or ^{blob} tells Git to follow tags or commits to their tree or to a blob.  Since every commit object has exactly one tree, the ^{tree} suffix succeeds if the name points to a tag object that points to a commit.  It also succeeds if the name points directly to a tree—possible for both lightweight and annotated tags.  The ^{blob} suffix can only succeed if the tag points to a blob (directly, as a lightweight tag, or indirectly through some number of tag objects), though, because there's no well-defined way to move from a commit or tree to one particular blob: trees typically hold many blob hash IDs.
The suffix ^{} directs git rev-parse to peel a tag.  That is, if the name is a tag name and the first level object is a tag object, Git should follow that object.  If the resulting object is another tag object, Git should follow that one as well.  Git should repeat this until the tag resolves to any non-tag object—any commit, tree, or blob.  Then git rev-parse should produce that non-tag object's hash ID.

Several other Git commands can be told to peel tags, and some do it even without you telling them.  For instance, git ls-remote calls up another Git and has the other Git tell your Git about its references—including tag names—and their object hash IDs.  When their Git tells your Git about one of their tag names, their Git produces both the top level tag object, if any, and the peeled object hash ID.  This shows up as:
<hash1> refs/tags/<tag>
<hash2> refs/tags/<tag>^{}

Here hash1 is the object ID of the annotated tag object, and hash2 is the object ID of the final non-tag object obtained by the peeling process (there must by definition always be such an object).
If you don't see this annotation in git ls-remote output for a tag object, that means their tag is a lightweight tag, pointing directly to the commit, tree, or blob object whose hash ID is listed.
The git for-each-ref command has the * directive to follow tags:

If fieldname is prefixed with an asterisk
   (*) and the ref points at a tag object, use the value for the field
   in the object which the tag object refers to (instead of the field
   in the tag object).

It's not clear from the documentation whether this fully peels a tag, or just goes one level down: if annotated tag X has as its target the annotated-tag-object of annotated tag Y that has, as Y's target, commit C, does %(*objectname) produce hash Y, or hash C?

A:

does every git tag have a unique commit id associated with it?

A git tag is just an alias for a commit (hash). The alias of the tag should be unique. (as Torek mentioned, this could also point something else than a commit, as long as it has an object id)
So every git tag points to a commit, but there could be multiple tags to one commit.

For example, if I run git tag how can I see what the commit id's are for those tags?

You could do:
git show-ref --tags -d

example output:
12d265006e50c61512421e88269f4811d52eaf36 refs/tags/v1.0
06d7af2f64d89551ef6324bc44de2454d228f0a8 refs/tags/v1.0-rc1
41137858e7ab5dc353d2478e2454d20735b050a1 refs/tags/v1.0-rc2
066031c9448170466ce8acd4bb5767a1ad02e2e6 refs/tags/v1.0-rc3
0fa020943977759c2fec1575f6fffa6a7799f44f refs/tags/v1.0-rc4
7cf72a2765525cadf2629eb42241d05304330052 refs/tags/v1.0-rc5
00a88fea533e7dfd12b8b17a82f1b57a486ebd00 refs/tags/v1.0-rc6
67a2d071f078be52776a44fe5105b999a8701944 refs/tags/v1.0-rc7
7f9e410a3bc272f4bfc29ea7a3a830883b47f1c2 refs/tags/v1.0.0-rtm-beta5
a0fc4b158f888c0813a9d4867e0627d1525b3fb1 refs/tags/v1.0.0-rtm-beta6
b77b36388895ac1e61d4b886e02e98861010c569 refs/tags/v1.0.0-rtm-beta7
ebc4180644081f893518bda2c0cab1c0d763cb5e refs/tags/v1.0.1
d5547d8cec7e2e7e7c912a8b56ab54cb92933f57 refs/tags/v1.0.2
3d0d78f4a8ae88c9b573d08aaeabc1430780236c refs/tags/v1.1.0
9f59232807ad963b63a3b634e7ebd2256a1ba0e8 refs/tags/v1.2.0
197deb1adf90bced16d04833b671b7e628505fe7 refs/tags/v1.2.1
759c5c2bc687a63fbb41e50de4e8e40ded449c5d refs/tags/v1.3.0
f009ec166256707f6887e65536d9d63f14894bbb refs/tags/v1.4.0
2560e6d313f2cf6800201b7dcfefe424beb2c675 refs/tags/v1.5.0
896e71519655361ef9b513af4d2538fa7b7c87be refs/tags/v1.5.1

If you need more control, you could use the --format (format options listed here)
git tag --format '%(refname:strip=2) %(objectname)'

output:
v1.0 12d265006e50c61512421e88269f4811d52eaf36
v1.0-rc1 06d7af2f64d89551ef6324bc44de2454d228f0a8
v1.0-rc2 41137858e7ab5dc353d2478e2454d20735b050a1
v1.0-rc3 066031c9448170466ce8acd4bb5767a1ad02e2e6
v1.0-rc4 0fa020943977759c2fec1575f6fffa6a7799f44f
v1.0-rc5 7cf72a2765525cadf2629eb42241d05304330052
v1.0-rc6 00a88fea533e7dfd12b8b17a82f1b57a486ebd00
v1.0-rc7 67a2d071f078be52776a44fe5105b999a8701944
v1.0.0-rtm-beta5 7f9e410a3bc272f4bfc29ea7a3a830883b47f1c2
v1.0.0-rtm-beta6 a0fc4b158f888c0813a9d4867e0627d1525b3fb1
v1.0.0-rtm-beta7 b77b36388895ac1e61d4b886e02e98861010c569
v1.0.1 ebc4180644081f893518bda2c0cab1c0d763cb5e
v1.0.2 d5547d8cec7e2e7e7c912a8b56ab54cb92933f57
v1.1.0 3d0d78f4a8ae88c9b573d08aaeabc1430780236c
v1.2.0 9f59232807ad963b63a3b634e7ebd2256a1ba0e8
v1.2.1 197deb1adf90bced16d04833b671b7e628505fe7
v1.3.0 759c5c2bc687a63fbb41e50de4e8e40ded449c5d
v1.4.0 f009ec166256707f6887e65536d9d63f14894bbb
v1.5.0 2560e6d313f2cf6800201b7dcfefe424beb2c675
v1.5.1 896e71519655361ef9b513af4d2538fa7b7c87be

A:

A tag is just like a branch... in other words: a branch/tag is just a pointer to a revision... the main difference is that tags aren't normally moved around whereas branches move around all the time (even with something as simple as when you commit)... and I'm sure somebody will come up with a simpler trick, but this shows where each tag is pointing to:
git tag | xargs git show --summary


Q:

Trying to use a class but nothing is printed. No errors are generated. Am I missing something?

No errors are generated, but nothing is printed when I run the code. Help?
class NatalieClass{
  public:
    void setName(string x){
      x = name;
    }

    string getName(){
      return name;
    }

  private:
    string name;
};

int main(){
  NatalieClass ob1;
  ob1.setName("Hello World");
  cout << ob1.getName();
  return 0;
}

The function is supposed to print "Hello World" but instead nothing is printed.

A:

In setName:
void setName(string x){
  x = name;
}

You are setting the argument you get passed (which is "Hello World" in this example) to the member variable x, which is an empty string. Then you print out name, which is still an empty string, so it'll look like you print out nothing.
You probably meant to assign name to x instead of the other way around:
void setName(string x) {
  name = x;
}

Side note : seeing your code snippet I'm assuming you have using namespace std; somewhere at the top, this is considered bad practice, use std:: instead..


Q:

DHT22 temp sensor. Randomly dropping

I am having trouble with a dht22 sensor. It works well for most of the time but randomly the library I am using can no longer receive a reading until I unplug then plug the sensor back in. (just disconnecting and reconnecting the GND pin is often enough) Then it will work for a while longer until the problem repeats.
I will try to describe my setup pictured in the drawing above in detail. The picture above is not a proper diagram drawing so please ask any questions if my text description falls short as well...
The DHT22 hookup is pretty straight forward 5V to VCC pin, GND pin to ground, DATA pin to a GPIO pin (GPIO 24 in my case). I am pulling up the DATA to 3V3 with a 4.7K Ohm resistor. I am using the pgpio DHT22 library. Here is the code which involve a loop in order to ignore the first couple of "bad" readings from the DHT22. (the DHT22 always gives the first two or three reading for temp and humidity as -999) also An important note is I am using about 10 feet of cat5e cable to connect the sensor directly to the pi.
#!/usr/bin/python
import pigpio
import DHT22
from time import sleep

# initiate GPIO for pigpio
pi = pigpio.pi()
dht22 = DHT22.sensor(pi, 24)

def readDHT22():
    #get reading
    dht22.trigger()
    humidity = '%.2f' % (dht22.humidity())
    temp = '%.2f' % (dht22.temperature())
    return (humidity, temp)

r = 0

while r < 10:
    humidity, temp = readDHT22()
    print ("trying to read temp...")
    r = r + 1
    if '999' in humidity or '999' in temp:
            sleep(sleeptime)
            continue
    sleep(sleeptime)
    print ("H:"+humidity+"")
    print ("T:"+temp+"")
    sleep(2)
    break

The other part of my diagram shows the connection for a 5V relay. There is actually 5 relays connected. they each share a 5V rail and a Ground rail. Each relay has its own GPIO connection used to send a HIGH signal to a transistor that acts as a switch for the relay.
The reason I mention the relays in my problem is I suspect that my issue could be that I am drawing to much current from the pi.
What basic steps should I take to begin trouble shooting an issue like this?
How can I accurately calculate the amperage of my circuit to determine if I am drawing more than avaible? ( As I understand the mx from the 3v3 rail is 50mA, and the max from 5V is the max of the power supply to the raspberry pi which is 2000mA in my case) I dont know the resistance of the relays or how to figure that out accurately either.
As a secondary question id like to ask about a recommendation for wiring the dht22 that was detailed in the DHT22.py library file:
For 5V operation connect pin 1 to 5V and pin 4 to ground.
The following pin 2 connection works for me.  Use at YOUR OWN RISK.

5V--5K_resistor--+--10K_resistor--Ground
                 |
DHT22 pin 2 -----+
                 |
gpio ------------+

Here is a drawing of how I understand to wire this up... Is it correct?

A:

"I suspect that my issue could be that I am drawing too much current from the pi."
Whether or not that's the case, I'm not a fan of the "modern" practice of sourcing relatively high currents from the Pi. In all my setups, I only source power from a PSU - if not to avoid overloading then simply to avoid introducing ripple and noise in the Pi's power rail that might disturb digital signalling.
Instead of sourcing from the Pi, use a 12 volt supply or a laptop PSU and get some cheap switching regulators for producing the voltages you need.
Rule of thumb in case you're going to do it anyway: never go above 80% capacity in any circuit. Ever.
About the relays... Whenever you're powering coils and other inductive loads (motors, solenoids and relays being the most common examples), you're effectively creating a magnetic field that resists sudden current changes as long as the coil is powered (in practical terms, think of the powered coil as an energy storage area). When you suddenly cut the power, i.e. turn off your relay, the magnetic field collapses and this energy is converted to a huge voltage spike. This phenomenon is typically referred to as "back electromotive force" or "back-EMF" for short. Since the energy can't just disappear, it'll have to travel down the supply line where it hits your controlling circuit. This means that your NPN transistor might be taking a beating whenever you turn your relay off. Transistors and digital logic don't like that one bit!
Oscilloscope output showing the voltage spike in a solenoid being turned off:
https://upload.wikimedia.org/wikipedia/commons/8/81/BackEMFWaveform.png

Basically your current relay setup (No back-EMF protection)
To mitigate the problem, it's common practice to add a flyback diode across the terminals of the inductive load (in parallel from GND to the positive terminal). You have to insert it so the little ring/stripe on one end of the diode is closer to the positive terminal than GND. Be careful with the orientation of the diode; put it in the wrong way and you've created a very good connection (low resistance path) from the positive to the negative terminal, also referred to as a short circuit.

How it could/should look (with back-EMF protection in the form of a flyback diode. The term "flyback" only refers to the application, not the diode itself. For your low current setup, use any regular diode capable of handling hundreds of volts. Eg. a 1N4001)
Check the schematic above... Here you see a circuit with voltage spike/back-EMF protection added in the form of a diode. There's a DC power source (Vs) on the left, a coil (L1) at the top that could be your relay, a resistance (R1), a switch (SW1) and a diode (D) placed across the coil. See how the diode is "pointing towards" the positive terminal on the power supply? This means that no current can flow through it during normal DC operation. However, as soon as you turn off the relay the diode will ensure that the power stored in the coil will loop around in the coil itself until the resistance in the copper windings has "eaten up" all the energy; thus sparing your controlling circuit (SW1) from a nasty shock.
The same solenoid setup as before but this time WITH a flyback diode across the load. See that nice, horisontal line? That's safety.
https://en.wikipedia.org/wiki/File:FlybackWaveform.gif
But wait, there's more!
Instead of mucking about with individual transistors and diodes, I suggest you buy 10 trusty old ULN2803 ICs for ~£1 on ebay including free shipping.
(I'm not affiliated with any vendors. I simply picked the cheapest product).
The ULN2803 is a so-called Darlington transistor array. A single chip effectively gives you 8 individual NPN transistors in one small package (it actually contains 16 transistors but that's hidden away in the chip). They are perfect for your application since they have built-in flyback-diodes and each output can handle up to 500mA (~300mA when controlled from 3v3). They even have built-in input resistors of 2.7 K so you can and should connect them directly to the Pi's 3v3 GPIO.
If you get these ICs, you can safely connect up to 8 relays/motors/whatever and control them via 8 GPIO pins. Providing that all the relays are powered from an external supply - not straight from the Pi - this is a safe, cheap and stable solution.
It could be done like this.
"Do you know of a way to trigger a "power cycle" for the pin without having to physically unplug the ground connection?"
Yes! Let a semiconductor do the dirty work! Simply connect GND from your sensor to one of the outputs of your newest investment - the ULN2803 :) To reset your sensor, you simply write a low/0 to the GPIO pin, wait a few seconds and then write a high/1.


Q:

How to use in node properties for deployment and local usage

I've created node application which I can run locally and in the cloud
Now I want that it be done somehow smoother and cleaner ,so I try to put some property in config.json file to check if I want to deploy the app or use it locally but I need to update manually this property before I change the propose , there is a better way to do it with node ?
let runnerServer = `http://localhost:8060/service/runner/${server.address().port}`;
if (cfg.isHosted) {
    blogServer = `http://${serverName}/service/runner/${server.address().port}`;
}

and in the conig.json I've the field isHosted which I change manually(true/false) if I want to deploy or not...
update
maybe I can use process.env.PORT but this is just one example that I need to use in my code , currently I've several of fork that need to konw if Im in deployment or running locally ..

A:

One option is to use use node's in built object called process.env (https://nodejs.org/api/process.html) and use two config files per se. This approach is somewhat similar to what you are doing but may be cleaner

config.localhost.json
config.production.json

then by setting properties on this object based on environment such as process.env.NODE_ENV = 'localhost' or process.env.NODE_ENV = 'production', you could read the corresponding file to import the configurations.
var config =  require('./config.production.json');
if(process.env.NODE_ENV === 'localhost')
{
    config = require('./config.localhost.json');
}

So to set this environment variable when running locally on your dev box , if
OSX - then on terminal export NODE_ENV=localhost
WINDOWS - then on cmd line  set NODE_ENV=localhost


Q:

redirect loop when redirecting to another page when logged in

I am getting a redirect loop and I dont know why. I have this simple code being used so that if someone goes to default.aspx and is already logged in it should redirect them to inside.aspx. Why am I getting a redirect loop?
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (User.Identity.IsAuthenticated) // if the user is already logged in
        {
            Response.Redirect("inside.aspx");
        }
    }

}

Edit:
both pages share a master page with the following code, this only goes off when the logoff control is pushed:
public partial class template : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void LoginStatus1_LoggingOut(object sender, LoginCancelEventArgs e)
    {
        Response.Redirect("default.aspx");
        Session.Abandon();
    }
}

A:

The problem was that the CodeFile reference for both files was the same. Silly mistake but if you have this problem make sure to check it!


Q:

ajax post data in flask view

Here is my view function
@app.route('/share', methods=['GET', 'POST'])
def share():
    form = ShareForm(request.form)
    if request.method == 'POST':
        title = form.title.data
        body = form.body.data
        share_id = form.share_id.data
        print 'form data %s %s %s' % (title, body, share_id)
        if not share_id:
            share = Shares(title, body, 'PUBLISHED', current_user.id)
            db.session.add(share)
            db.session.commit()
            form.share_id.data = share.id
        return jsonify({'status': 204, 'body': {'status': True}})
    else:
        return render_template('share.html', form=form)

The code for ajax post request
<script>
    $(function(){
      $('#share').on('click', function(e){
        e.preventDefault(); // preventing default click action
        $.ajax({
          url: '/share',
          type: 'post',
          contentType: "application/json; charset=utf-8",
          data: $('#share-form').serialize(),
          success: function(){
            console.log('success');
            console.log( $('#share-form').serialize());
          }, error: function(xhr, textStatus, errorThrown) {
            alert(xhr.responseText);
            console.log( $('#share-form').serialize());
          }});
        })
        //return false;
      });
</script>

in the view, when i try to print the request object, I get the following data
print request.data
'title=adsl%3Blsaj%3Blj%3Bl&body=j%3Bas%3Bl%3Bl+&share_id='

But if I try to do,
print request.form.get('title', 'None')

I get 'None'
Can somebody tell me how to fix this ?

A:

You are setting the content type to application/json but are sending application/x-www-form-urlencoded data instead.
Set the correct content type:
$.ajax({
  url: '/share',
  type: 'post',
  contentType: "application/x-www-form-urlencoded",
  data: $('#share-form').serialize(),

or better still, leave it at the default by omitting the contentType key altogether.


Q:

What is the meaning of these red bars in git file difference

There is a red bar after + sign. What is this ?

A:

Potentially bad indentation. You may have used tabs when you configured Git to prefer spaces, or vice-versa.
Check git config core.whitespace; it might contain tab-in-indent, space-before-tab, or indent-with-non-tab. You should change it to suit your preferences if this isn’t really a mistake.

A:

Here are the possible values for the core.whitespace.
Your configuration value will be one of the tabs value below
core.whitespace

A comma separated list of common whitespace problems to notice.
  git diff will use color.diff.whitespace to highlight them, and git apply
--whitespace=error will consider them as errors.
  You can prefix - to disable any of them (e.g. -trailing-space):

blank-at-eol
treats trailing whitespaces at the end of the line as an error (enabled by default).
space-before-tab###
treats a space character that appears immediately before a tab character in the initial indent part of the line as an error (enabled by default).
indent-with-non-tab
treats a line that is indented with space characters instead of the equivalent tabs as an error (not enabled by default).
tab-in-indent
treats a tab character in the initial indent part of the line as an error (not enabled by default).
blank-at-eof
treats blank lines added at the end of file as an error (enabled by default).
trailing-space
a short-hand to cover both blank-at-eol and blank-at-eof.
cr-at-eol
treats a carriage-return at the end of line as part of the line terminator, i.e. with it, trailing-space does not trigger if the character before such a carriage-return is not a whitespace (not enabled by default).
tabwidth=n
tells how many character positions a tab occupies; this is relevant for indent-with-non-tab and when Git fixes tab-in-indent errors. The default tab width is 8. Allowed values are 1 to 63.

Sample for output when tabs are uses as the configuration value:


Q:

Xamarin : Unable to save a sms programmatically in android

I am coding in xamarin android using c# and am trying to restore sms to a phone from an existing file. I have fetched all the sms and have put them in a list ready to be saved. Now the problem is when I try to save it I get a message that sms saved but in my original messaging app I don't see the newly added sms. I have used below line of code in my function :
My first try
ContentValues values = new ContentValues();
values.Put(Telephony.Sms.Conversations.InterfaceConsts.Body, "Hello folks");
values.Put(Telephony.Sms.Conversations.InterfaceConsts.Address, "6879890");
// values.Put(Telephony.Sms.Conversations.InterfaceConsts.Type, 0);
values.Put(Telephony.Sms.Conversations.InterfaceConsts.Read, 1);
values.Put(Telephony.Sms.Conversations.InterfaceConsts.Date, "1513071781");
Application.Context.ApplicationContext.ContentResolver.Insert(Telephony.Sms.Inbox.ContentUri, values);

My second attempt to do the same
var context = Application.Context.ApplicationContext;
var values = new ContentValues();
values.Put("address", "+9868665567");
values.Put("body", "Added via Xamarin");
values.Put("read", false);
values.Put("date", "1513071781");

try
{
    context.ContentResolver.Insert(Telephony.Sms.Inbox.ContentUri, values);
    Toast.MakeText(this, "SMS saved ! ", ToastLength.Short).Show();
}
catch(Exception ex)
{
    Toast.MakeText(this, "SMS not saved ! "+ex.Message, ToastLength.Long).Show();
}

Always I get the success message and never get an error but I can never see the reflected changes

A:

with the help of @mike here , I have resolved the problem and can now add sms.
here is the final code :
        private void SMS_test_Click(object sender, EventArgs e)
    {
        var context = Application.Context.ApplicationContext;
        String defaultSmsApp = Telephony.Sms.GetDefaultSmsPackage(context);
//Add this to make your app default
        Intent intent = new Intent();
        intent.SetAction(Telephony.Sms.Intents.ActionChangeDefault);
        intent.PutExtra(Telephony.Sms.Intents.ExtraPackageName, context.PackageName);
        StartActivity(intent);

//Save the message
        var values = new ContentValues();
        values.Put("address", "+982323855");
        values.Put("body", "Added via Xamarin");
        values.Put("read", false);
        values.Put("date", "1513071781");
        context.ContentResolver.Insert(Telephony.Sms.Sent.ContentUri, values);

        Toast.MakeText(this, "Message added : ", ToastLength.Long).Show();

//Add this to revert the default app to what it previously was.
        intent = new Intent();
        intent.SetAction(Telephony.Sms.Intents.ActionChangeDefault);
        intent.PutExtra(Telephony.Sms.Intents.ExtraPackageName, defaultSmsApp);
        StartActivity(intent);
    }


Q:

Would it be possible to dictate a bech32 address as a list of English words?

One of the reason for bech32 address is: "it'easier to dictate it over the phone".
Is there an algorithm to convert a bech32 address into a list of English words that would make it even easier?
Something like BIP39 but inverted (address to words instead of words to seed).
The dictionary used in BIP39 would be enough?
How many words would be necessary at best to express an address?
Probably it is better to dictate the address than 50 words but what about 25 or so?.

A:

The NATO phonetic alphabet is designed for this purpose and is very widely recognized by a number of people in communication critical industries. The words are clearly recognizable even to the unfamiliar and is intended to not be able to be mistaken. Due to bech32 encoding there’s no need for communication of capital letters as you would need for p2pkh addresses.
bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq

becomes

Bravo Charlie One Quebec Alpha Romeo Zero Sierra Romeo Romeo Romeo Seven X-ray Foxtrot Kilo Victor Yankee Five Lima Six Four Three Lima Yankee Delta November Whiskey Nine Romeo Echo Five Nine Golf Tango Zulu Zulu Whiskey Foxtrot Five Mike Delta Quebec


Q:

Has any two teams in the World Series ever get there without losing a game during the postseason?

Related: Has there been a time the 2 NBA or NHL teams in the playoffs final series got there without losing any games?
MLB Postseason Format Timeline:

Before 1969, the team with the best record from the AL and the team with the best record from the NL during the regular season played in the World Series.
Between 1969 and 1993, there was one playoff round before the World Series (AL/NLCS).
Between 1995 and 2011, there were two playoff rounds before the World Series (AL/NLDS, AL/NLCS).
Since 2012, there has been a play-in game for Wild Card teams, adding an additional game to the format for Wild Card teams.

Has any two teams in the World Series ever get there without losing a game during the postseason?

A:

Has any two teams in the World Series ever get there without losing a game during the postseason?

Yes. However, all these instances took place during the "one playoff round before the World Series" format between 1969 and 1993. Each of these teams went 3-0 before reaching the World Series.

1969 - Mets vs. Orioles
1970 - Orioles vs. Reds
1975 - Reds vs. Red Sox

Between 1969 and 1993, 14 teams reached the World Series without losing a game. Since 1995, two teams have reached the World Series without losing a game:

2007 Rockies (3-0 NLDS, 4-0 NLCS)
2014 Royals (1 Wild Card play-in win, 3-0 ALDS, 4-0 ALCS)

The Royals were the first team in history to win their first eight playoff games(1). The Rockies, along with the Reds in 1976, won their first seven playoff games(2). Given the format at the time, seven consecutive playoff wins gave the Reds an undefeated postseason.


Q:

Access to a website only when I grant them access

I have made a registration form and a login form using PHP.The registration form saves user's information to a database.
But as I am pretty new to PHP I want to achieve this think. I have also made a whole template/theme of an e-commerce website but I want as an entrance page to be this registration form and when I grant them access to be able to see the whole content of my e-commerce website.While i say grant them access when they give me the fields of the registration form,they wont be able to enter the website until I send them a password.So my question is how can i achieve not be able to see the entire website?What I need to do to protect it? i mean I need to add code on the registration form? on the login form or the template/theme?
Thanks!

A:

try using a $_SESSION variable. For example, create a $_SESSION['loggedIN'] variable that is initally false. The page would always verify that variable to allow or deny access to the content.
I'm guessing there is also a log-in form, right?
So, you would only allow acces ($_SESSION['loggedIN']=TRUE) once the log-in form action allows it. Of course there is all the verification and database access process, but that is a simple idea to solve your problem.


Q:

inserting splitted text to ms access?

How can I insert splitted texts to my ms access database?
I can't seem to find the logic in it. :(
Please help me.
Here are my codes:
This is where i split the texts that are inputted in textBox1, textBox2, and textBox3
string items = textBox2.Text;
string[] splittedText1 = items.Split(' ');
string quantity = textBox1.Text;
string[] splittedText2 = quantity.Split(' ');
string price = textBox3.Text;
string[] splittedText3 = price.Split(' ');

and this is the code where I will insert those texts to my database:
OleDbCommand CmdSql = new OleDbCommand("Insert into [sales] ([productname], productquantity, productprice) VALUES (splittedText1, splittedText2, splittedText3);

is this even correct? Please help!

A:

You can execute query like this.
string[] splittedText1 = textBox2.Text.Split(' ');
string[] splittedText2 = textBox1.Text.Split(' ');
string[] splittedText3 = textBox3.Text.Split(' ');

string _sql = "Insert into [sales] ([productname], productquantity, productprice) VALUES (?,?,?)";
OleDbCommand CmdSql = new OleDbCommand();
CmdSql.Connection = Cnn;

CmdSql.Parameters.Add("@productname", OleDbType.VarChar);
CmdSql.Parameters.Add("@productquantity", OleDbType.VarChar);
CmdSql.Parameters.Add("@productprice", OleDbType.VarChar);

decimal dQty = 0m;
decimal dPrice = 0m;
for (int i = 0; i < splittedText1.Length; i++)
{
    Decimal.TryParse(splittedText2[i], out dQty);
    Decimal.TryParse(splittedText3[i], out dPrice);
    CmdSql.Parameters["@productname"].Value = splittedText1[i];
    CmdSql.Parameters["@productquantity"].Value = dQty;
    CmdSql.Parameters["@productprice"].Value = dPrice;
    CmdSql.ExecuteNonQuery();
}


Q:

Produce a graph from an editable table in Shiny

I have a shiny application with the following ui:
library(rhandsontable)
library(shiny)
library(ggplot2)

ui =  fluidPage(

  # App title ----
  titlePanel("Tabsets"),

  # Sidebar layout with input and output definitions ----
  sidebarLayout(

    # Sidebar panel for inputs ----
    sidebarPanel(

    ),

    # Main panel for displaying outputs ----
    mainPanel(

      # Output: Tabset w/ plot, summary, and table ----
      tabsetPanel(type = "tabs",
                  tabPanel("Summary", rHandsontableOutput('contents'),
                           actionButton("saveBtn", "Save changes")
                  ),
                  tabPanel("Tab",
                           rHandsontableOutput('contentFinal')),
                  tabPanel("Dashboard",
                           plotOutput('dashboard1'))

      )

    )
  )
)

And the following server
library(dplyr)
library(rhandsontable)
options(shiny.maxRequestSize = 9*1024^2)

server = function(input, output) {

  values <- reactiveValues()

  Post <- c("", "")
  list2 <- c(12,13)
  df <- data.frame(Post, list2)

  output$contents <- renderRHandsontable({

    rhandsontable(df, width = 550, height = 300) %>%
      hot_col(col = "Post", type = "dropdown")
  })

  saveData <- eventReactive({input$saveBtn},{
    finalDF <- hot_to_r(input$contents)
    finalDF$Post <- ifelse(finalDF$Post =="",NA,finalDF$Post)
    newDF <- finalDF[complete.cases(finalDF),]
    return(newDF)
  })

  output$contentFinal <- renderRHandsontable(
    rhandsontable(saveData())
  )

  output$dashboard1 <- renderPlot(
    ggplot(input$contentFinal, aes(x = Post, y = list2 )) +
      geom_bar(stat = "identity")

  )
  observeEvent(input$saveBtn, saveData())

}

shinyApp(ui = ui, server = server)

The flow is like this:

In the first tab, I bring up data with an empty post column
In this tab, I can add a name for the post and save it.
As soon as I save he rows with values for post become visible in the next tab.

Then the next thing I want to do is to have a visual in the dashboard tab that shows the data. Therefore I create:
output$dashboard1 <- renderPlot(

    ggplot(input$contentFinal, aes(x = Post, y = List2 )) +
      geom_bar(stat = "identity")

  )

This however gives me the following ggplot2 errror:

ggplot2 doesn't know how to deal with data of class list

Any thoughts on what goes wrong here?

A:

The problem is because input$contentFinal is handsontable data. We need to convert it to R object using hot_to_r function.
The ggplot should be plotted using the following:
ggplot(hot_to_r(input$contentFinal), aes(x = Post, y = list2 )) +
      geom_bar(stat = "identity")
Hope it helps!


Q:

com.arangodb.velocypack.exception.VPackParserException: java.lang.InstantiationException

i am trying to connect my ArangoDb database with scala, but when the connection is made, and i am doing the operation, i have an VPackParserException error. My code:
import com.arangodb.spark.{ArangoSpark, ReadOptions}
import org.apache.spark.SparkContext
import org.apache.spark.SparkConf
import scala.beans.BeanProperty

object ArangotoSpark {

def main(args: Array[String]) {
  case class netflow(@BeanProperty SrcHost: String,
                   @BeanProperty DstHost: String,
                   @BeanProperty SrcPort: String,
                   @BeanProperty DstPort: String,
                   @BeanProperty Protocol: String,
                   @BeanProperty StartTS: String,
                   @BeanProperty EndTS: String,
                   @BeanProperty Packets: Int,
                   @BeanProperty Bytes: Int) {  }

  val conf = new SparkConf().setAppName("Simple Application").setMaster("local[*]")
    .set("arangodb.host", "127.0.0.2")
    .set("arangodb.port", "8529")
    .set("arangodb.user", "root")
    .set("arangodb.password", "rut")
    .set("arangodb.database", "netflow")
  val sc = new SparkContext(conf)
  val rdd = ArangoSpark.load[netflow](sc, "N201701031130", ReadOptions("netflow"))
  val rdd2 = rdd.filter { x => x.SrcHost.matches("15.33.165.30") }
  rdd2.count()
  }
}

Any help is appreciated. Thank you.
UPDATE: Now my code looks like this:
case class nf (@BeanProperty cadena: String){
   def this() = this(cadena = null)}
val rdd = ArangoSpark.load[nf](sc, "N201701031130", ReadOptions("netflow"))
println(rdd.count())
println("*************************************")
rdd.collect.foreach(println(_))

rdd.count gives the correct number of documents, but when i try to print them, i only have nf(null) lines

A:

your class netflow needs a parameterless constructor.
The VelocyPack deserializer which deserialize incoming VelocyPack into Java/Scala objects - under the hood of the Java driver - needs it to instantiate your class.
update:
You don't have to parse it to work with the field names. Your case class can have the same fields as the stored documents. The serializer/deserializer from the java driver can work with it. But you also need a parameterless constructor.
Your case class could look as follow:
case class netflow(@BeanProperty SrcHost: String,
                   @BeanProperty DstHost: String,
                   @BeanProperty SrcPort: String,
                   @BeanProperty DstPort: String,
                   @BeanProperty Protocol: String,
                   @BeanProperty StartTS: String,
                   @BeanProperty EndTS: String,
                   @BeanProperty Packets: Int,
                   @BeanProperty Bytes: Int) {
  def this() = this(null,null,null,null,null,null,null,null,null)}
}


Q:

Finding $\mathrm{Cov}(X,Y)$ and $E(X\mid Y=y)$ given the joint density of $(X,Y)$

The continuous random variables $X$ and $Y$ have joint density function $f_{xy} = 1$ for $0 < x < 1$ and $2x < y < 2$, and zero otherwise.
I am stuck on the above question, with parts a and b below:
a) Find the $cov(x,y)$.
Work:
$cov(x,y) = E(XY) - E(X)E(Y)$
$= \int_0^1\int_{2x}^2 xydydx - \int_0^1\int_{2x}^2 xdydx\int_0^1\int_{2x}^2 ydydx$
= $\frac{-1}{18}$
However I am given the answer $\frac{1}{18}$.  Did I make a mistake in my computation or is the answer incorrect?
b) Find $E(X|Y = y)$.
Work:
$E(X|Y=y) = \int_{-\infty}^{\infty}xf_{x|y}(x|y)dx$
This is where I am puzzled.  I know that $f_{x|y}(x|y) = \frac{f_{xy}(xy)}{f_yy}$, and $f_yy= \int_{-\infty}^{\infty}f_{x,y}(x,y)dx$.  That means $f_yy = 1$ and therefore $f_{x|y}(x|y) = 1$.  However I am given the answer $E(X|Y=y) = \frac{y}4$. Again, did I make a computational mistake or am I not getting something?
Thanks.

A:

The densities are usually denoted with subscripts in capital letters for the random variables.
For part (a), it is an algebraic error on your part. For part (b), you are not paying attention to the supports of the random variables in your calculations. Hence the absurd answers.
Define the indicator $$1_A(x)=\begin{cases}1&,\text{ if }x\in A\\0&,\text{ otherwise }\end{cases}$$
Then joint density of $(X,Y)$ is $$f_{X,Y}(x,y)=1_{(0,1)}(x)1_{(2x,2)}(y)$$
So density of $Y$ is
\begin{align}
f_{Y}(y)&=\int f_{X,Y}(x,y)\,dx\,1_{(0,2)}(y)
\\&=\int_0^{y/2}\,dx\,1_{(0,2)}(y)
\\&=\frac{y}{2}\,1_{(0,2)}(y)
\end{align}
Thus giving the density of $X$ conditioned on $Y=y$ for each $y\in(0,2)$:
$$f_{X\mid Y=y}(x)=\frac{2}{y}\,1_{(0,y/2)}(x)$$
Hence $$\mathbb E\left[X\mid Y=y\right]=\int x f_{X\mid Y=y}(x)\,dx=\frac{y}4$$


Q:

How to find the eigenvalue of this block matrix.

Here is a $4\times 4$ matrix:
\begin{pmatrix}
\xi\delta_{ij} &\Delta_{ij}\\
\Delta_{ij}^\dagger& -\xi\delta_{ij}
\end{pmatrix}
In the above, $\delta_{ij}$ represent a $2\times2$ identity matrix, $\Delta_{ij}^\dagger$ is the hermitian conjugate of the $2\times2$ matrix $\Delta_{ij}$.
Question is: how to get the eigenvalue of the above matrix and the corresponding matrix that diagonalize it.

A:

Let $A=\begin{pmatrix}\xi I_2&\Delta\\\Delta^*&-\xi I_2\end{pmatrix}$. Then $\det(A-\lambda I_4)=\det((\lambda^2-\xi ^2)I_2-\Delta\Delta^*)$. Let $(\sigma_i)_{i\leq 2}$ be the singular values of $\Delta$ and $(\lambda_j)_{j\leq 4}=spectrum(A)$; since $\det(\sigma_i^2 I_2-\Delta\Delta^*)=0$, one obtains $\lambda^2-\xi^2=\sigma^2$, that is, $\lambda_1=\sqrt{\sigma_1^2+\xi^2},\lambda_2=-\lambda_1,\lambda_3=\sqrt{\sigma_2^2+\xi^2},\lambda_4=-\lambda_3$.
Let $\Delta=U\Sigma V^*$ be a SVD of $\Delta$. We assume that $\sigma_1>\sigma_2>0$.
Let $[x,y]^T$ be an eigenvector of $A$ associated to $\lambda=\pm\sqrt{\sigma^2+\xi^2}$. One has $\xi x+\Delta y=\lambda x,\Delta^*x-\xi y=\lambda y$. Then $\Delta y=(\lambda-\xi)x$ and $\Delta^*\Delta y=\sigma^2 y$; thus $y$ is an eigenvector of $\Delta^*\Delta$, that is a column of $V$; in the same way, $x$ is the column of $U$ with the same index as the previous column, that defines $x$ up to signum; the previous signum is given by the relation $x=1/(\lambda-\xi)\Delta y$.


Q:

How to setBackgroundDrawable without stretching an image

in my Android App I am using android.support.v7.widget.Toolbar and setting background image of Action Bar in MainActivity:
// Custom Action Bar
if(getSupportActionBar() != null){
    getSupportActionBar().setDisplayShowTitleEnabled(false);
    getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_tug));
}

Problem is that icon is stretching to the width of the action bar and I don't know how to change it into scaling to the height of the action bar, so that icon will not lose quality.
<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="top"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:gravity="top"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

Wrong Image
How it should look like

A:

Use an ImageView inside Toolbar and set the background as source in the ImageView
  <android.support.v7.widget.Toolbar
       style="@style/ToolBarStyle"
       xmlns:android="http://schemas.android.com/apk/res/android"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:background="?attr/colorPrimary"
       android:minHeight="@dimen/abc_action_bar_default_height_material">

        <ImageView
            android:layout_width="wrap_content"
            android:contentDescription="@string/logo"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:src="@drawable/ic_launcher"/>

     </android.support.v7.widget.Toolbar>


Q:

htaccess HTTPS only no redirect

I want to block port 80 (HTTP) completely and only allow HTTPS requests. I have found many examples of how to redirect from HTTP to HTTPS but I would prefer to display an error instead. I cannot block port 80 in my config file as my hosting provider does not allow me to modify these files. If possible, how can I achieve the same results with htaccess.
The reason for me wanting this on my api.domain.com is for added security after reading this article.
Quote from article...

Aside from abandoning HTTP Basic altogether there is an easy fix. close port 80 on your API host. This stops a connection being made dead in its tracks, preventing any credentials being sent in the clear

A:

Try:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} !/error\.php
RewriteRule ^ http://%{HTTP_HOST}/error.php [L,R]

or
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^ - [L,F]


Q:

Can we replace UPPER function by making upper in java?

I want remove upper function used in hql and make in upper at java side. following is the query:-
String hql = "SELECT addType FROM addrDO WHERE **UPPER**(id.address) = **UPPER**('"+ address +"')";

I want use toUpperCase() java funtion instead of using UPPER in query, like "id.address".toUpperCase() and address.toUpperCase() at java side and now query should be like
String hql = "SELECT addType FROM addrDO WHERE id.address = address;

Will above work any side effect.

A:

The first query uses the UPPER function to implement a case insensitive comparison in the WHERE clause, the second uses case sensitive comparison.
Because the comparison has to be done in the database, you cannot replace it with Java's toUpperCase in the application layer.