text:
Q: Conjecture $\lim\limits_{x\to 0}\prod\limits_{n=1}^{\infty}\left(\arctan\left(x^{n}\right)+1\right)^{\frac{1}{x}}=e$ I cannot figure why but let me propose  it:
$$\lim_{x \to 0}\prod_{n=1}^{\infty}\left(\arctan\left(x^{n}\right)+1\right)^{\frac{1}{x}}\overset?=e$$
We have a more obvious statement:
$$\lim_{x\to 0}\prod_{n=1}^{\infty}\left(\tanh\left(x^{n}\right)+1\right)^{\frac{1}{x}}=e$$
If we replace a $\arctan$ by a similar function, for example $\operatorname{erf}$, we don't have the same result.
If the conjecture is true I think we may need complex numbers to prove it but it's my supposition.
I have checked the conjecture up to $n=100$ with Desmos. How should I prove or disprove it?

A: Using $O$ notation and $\arctan(x)=x+O(x^3)$ you have
$$\log\left(\prod_{n=1}^{\infty}\left(\arctan\left(x^{n}\right)+1\right)^{\frac{1}{x}}\right)=\frac{1}{x}\sum_{n=1}^\infty \log\left(1+x^n+O(x^{3n})\right) = \frac1x \sum_{n=1}^\infty \left(x^n + O(x^{2n}) \right)\\
=\frac1x \left( \frac{x}{1-x} + O\left(\frac{x^2}{1-x^2}\right)\right)=\frac{1}{1-x}+O(x) = 1 + O(x) \, .$$
Your statement is true for any function $f$ with $f(x)=x+o(x)$ about $x=0$.

A: Let us denote $S(x) = \sum \limits_{n=2}^{\infty} \log\big(\arctan(x^n)+1\big)$, for $x \in \big[-\frac{1}{\sqrt{2}}, \frac{1}{\sqrt{2}}\big]$ (so it is well defined; see later for the proof of the proof that it converges). We want to show that $S(x) = O(x^2)$.
For $x \ge 0$ the bound is very simple to write. Let us directly write the general case where $x$ can also be negative. We will use the two following inequalities:

*

*for all $x \in \big[-\frac{1}{\sqrt{2}}, \frac{1}{\sqrt{2}}\big]$ $n \ge 2$, $|\arctan(x^n)| \le |x|^n \le \frac{1}{2}$,

*for $t \in \big[-\frac{1}{2}, \frac{1}{2}\big]$, $|\log(1+t)| \le |t|+t^2$. A proof can be found here for $-\frac{1}{2} \le t \le 0$, and the result is obvious for positive $t$.
Now we write, for $x \in \big[-\frac{1}{\sqrt{2}}, \frac{1}{\sqrt{2}}\big]$:
\begin{align*}
|S(x)| & \le \sum \limits_{n=2}^{\infty} \big|\log\big(\arctan(x^n)+1\big)\big| \\
& \le \sum \limits_{n=2}^{\infty} \big|\arctan(x^n)\big| + \arctan(x^n)^2 \\
& \le \sum \limits_{n=2}^{\infty} |x|^n + |x|^{2n} = \frac{|x|^2}{1-|x|} + \frac{x^4}{1-x^2}
\end{align*}
and thus $S(x)=O(x^2)$; and this also proves that the series converges for these values of $x$. This allows us to conclude for your initial question, since for these $x$, the series converges, so the infinite product also does and we can write:
\begin{align*}
\prod \limits_{n=1}^\infty \big(\arctan(x^n)+1\big)^{\frac{1}{x}} & = \exp\Big(\frac{\log\big(1+\arctan(x)\big)}{x} + \frac{1}{x}\sum\limits_{n=2}^{\infty} \log\big(1+\arctan(x^n)\big)\Big) \\
& = \exp\big(1 + O(x)\big)
\end{align*}
since $\arctan(x) = x+O(x^3)$ and $\log(1+x)=x+O(x^3)$. The limit is indeed $e$.

Erratum on my initial comment about this also working for $\mbox{erf}$: I didn't realize that the derivative at $0$ was actually important for the actual value of the limit. If you replace $\arctan$ with a function that has a derivative $\alpha$ at $0$, a similar product will converge to $\exp(\alpha)$. Again, that would be because of the first term of the series, the rest of the terms being negligible.


text:
Q: MySql how can I fix this category table structure? I have a category lookup table with 3 columns
MyISAM Approx 500k rows
listing_id          | int(11)
category_id         | int(11)
parent_category_id      | int(11)

This table is joined on listing when browsing or searching by category.
As parent_category_id is repeated for each category_id when searching on a parent category the query includes
 SQL_CALC_FOUND_ROWS DISTINCT ...

to get unique rows and the total number of results found.
Additionally, we have a range of WHERE and ORDER BY thrown into the mix  (from user filters)
I tried two options;
Remove parent_category_id column and insert unique parents as category_id.
This would enable removing DISTINCT from the query, but as a down side it also increases the amount of rows to scan but i can get a index this way for most common cases.   I've done a test and this seems to work well. Query from 20+ secs to  0.4secs
Or should I create a separate table for parent_category_id.? eg (listing_is, parent_id)
BTW: Listings can have more than one parent and more than 1 category.
What would you recommend?
Thanks in advance

A: Normalize parent_category_id into a separate table. The benefits of a smaller index in this case outweigh a single table with more data. Indexes that fit into memory are always faster.

redpajama_set_name: RedPajamaStackExchange


text:
Q: toString() not working with super and sub classes I am having an issue getting my toString() method to display properly. I have it overloaded in each of my subclasses and I am calling for it in the main method. I get the beginning of the desired output, but afterwards all I get is a hash. I am also trying to display the results of the array as well using this toString() method.
    //main method

    public class PublicationArray
{
public static void main(String[] args)
{
  Publication[] publications = new Publication[10];

  publications[0] = new Magazine("American Fisherman", 2.0, 100);
  publications[1] = new Book("C++ Programming", 25.0, 70);
  publications[2] = new Magazine("Time", 1.5, 100);
  publications[3] = new Book("Morning Dove", 15.0, 39);
  publications[4] = new Magazine("Nerd", 3.0, 10);
  publications[5] = new Book("Walking and Chewing Gum for Dummies",14.0,40);
  publications[6] = new Magazine("New Yorker", 2.25, 28);
  publications[7] = new Book("J++ Programming", 30.0, 55);
  publications[8] = new Magazine("Devorced", 1.75, 33);
  publications[9] = new Book("Doing Nothing for Dummies", 10.0, 10);

  for(int i = 0; i < publications.length; i++)
  {
     System.out.println("Publication [" + i + "] is " + publications.toString());
  }

}
}

   //one of the subclasses, the other is identical except for the formula

public class Magazine extends Publication
{
public Magazine(String title, double cost, int quantity)
{
  super(title, cost, quantity);
}

String month;

public void setMonth(String pubMonth)
{
  month = pubMonth;
}
@Override
public double setPrice()
{
  double price = cost * 1.6;
  return price;
}

@Override
public String toString()
{
  String display = "Title " + title + ",Price " + setPrice() +
     ", Cost " + cost + ", Quantity " + quantity;
  return display;
}
}

//Output

Publication [0] is Title ,Price 0.0, Cost 0.0, Quantity 0
Publication [1] is Title ,Price 0.0, Cost 0.0, Quantity 0
Publication [2] is Title ,Price 0.0, Cost 0.0, Quantity 0
Publication [3] is Title ,Price 0.0, Cost 0.0, Quantity 0
Publication [4] is Title ,Price 0.0, Cost 0.0, Quantity 0
Publication [5] is Title ,Price 0.0, Cost 0.0, Quantity 0
Publication [6] is Title ,Price 0.0, Cost 0.0, Quantity 0
Publication [7] is Title ,Price 0.0, Cost 0.0, Quantity 0
Publication [8] is Title ,Price 0.0, Cost 0.0, Quantity 0
Publication [9] is Title ,Price 0.0, Cost 0.0, Quantity 0

public abstract class Publication
{
String title = "";
double cost;
int quantity;

//Constructor
public Publication(String pubTitle, double pubCost, int pubQuantity)
{
  pubTitle = title;
  pubCost = cost;
  pubQuantity = quantity;
}

//Set Methods
public void setTitle(String pubTitle)
{
  title = pubTitle;
}
public void setCost(double pubCost)
{
  cost = pubCost;
}
public void setQuantity(int pubQuantity)
{
  quantity = pubQuantity;
}

//Get Methods
public String getTitle()
{
  return title;
}
public double getCost()
{
  return cost;
}
public int getQuantity()
{
  return quantity;
}

public abstract double setPrice();

}

A: This is because using the toString() method on an array gives you the memory address of that array. You want to be using Arrays.toString(publications) in your custom toString() method.
Also, you are looping through to display every object in your array, but printing the whole array instead of a single instance:
for(int i = 0; i < publications.length; i++)
{
    System.out.println("Publication [" + i + "] is " + publications[i].toString());
}

For your issue of your output only being zeroes, make sure the variables in the super class are protected or public. then in your subclass' toString() method access them using the this keyword:
public String toString()
{
    String display = "Title " + this.title + ",Price " + setPrice() + ", Cost " + this.cost + ", Quantity " + this.quantity;
    return display;
}

You should also use the this keyword to access cost in your setPrice() method.
EDIT:
The issue of getting zeroes as output is likely due to your constructor in your Publication class. You are assigning your variables the wrong way around. It should look like this:
public Publication(String pubTitle, double pubCost, int pubQuantity)
{
    title = pubTitle;
    cost = pubCost;
    quantity = pubQuantity;
}


text:
Q: How to make a cicrle around radius using latitude and longitude in MAPBOX I am using Geofence in MapBox, so I want to make a circle for destination based on radius and latitude and longitude in MapBox.Please kindly help me.
For GoogleMap the code will be like this:
Circle circle = googleMap.addCircle(new CircleOptions()
                .center(new LatLng(latLng.latitude, latLng.longitude))
                .radius(Constants.GEOFENCE_RADIUS_IN_METERS)
                .strokeColor(Color.RED)
                .strokeWidth(4f));

For MapBox I need code like this or how to customize the circle.Please help me


text:
Q: Workflow Manager Auto Generated Certificates I have SharePoint Farm with 2 Web front end servers, 2 application servers, and Database server. I have installed and configure Workflow manager on one of the application server with auto generated certificates.I have added one the certificate to SharePoint Server which host Central admin by going to the SharePoint Management shell and running the New-SPTrustedRootAuthority cmdlet.Do I have to add all four certificates from workflow manager server to all SharePoint servers in a farm? Please advise.
Thanks
Ronak

A: You don't need to install the certificate on all servers, this command will add it on required location. You can add the same certificate via central admin. Check this TechNet wiki which explains it.
https://social.technet.microsoft.com/wiki/contents/articles/34451.sharepoint-2016-step-by-step-guide-to-add-workflow-manager-certificate-into-sharepoint-trust.aspx


text:
Q: How to slice array values by two I have a javascript array of values [A,B,C,D,E.....] that i need to split with this syntax:
[ [A, B], [C, D], [E, F] ]
and so on (it will be always a pair).
So it should be a loop that returns a string.
I've tried to do like so, and it's almost what i wanted:
text = '['+array[0]+','+array[1]+']';
for (index = 2; index < array.length; index++) {
    text += '['+array[index]+','+array[index+1]+']';
    console.log(text);
}

I get
[10:00,15:45][18:30,20:00]
[10:00,15:45][18:30,20:00][20:00,undefined]

instead i need to get only this:
[10:00,15:45][18:30,20:00]

A: Could try making text an actual array and pushing pairs in, like so

var orig=['A','B','C','D','E','F'];
var text=[];
for (index = 0; index < orig.length-1; index+=2) {
    text.push([orig[index],orig[index+1]]);
    console.log(JSON.stringify(text));
}

A: Something in the lines of:
var groupArray = function(arr){
    var groupedArray = [];
    for(var i = 0, len = arr.length; i < len; i += 2){
        groupedArray.push([arr[i], arr[i + 1]]);
    }
    return groupedArray;
};

This obviously only works for arrays with an even number of elements. If you need the function to work with arrays with an odd number of elements, too, you need to acomodate for that.

A: Here's a small method for grouping array elements. You can just check that your inner arrays have a length of 2 afterwards, if you only care about pairs.

if (!Array.prototype.group) {
  Array.prototype.group = function (length) {
    var a = this.slice(), r = [];
    length = length || 1;

    while (a.length > 0) {
      r.push(a.splice(0, length));
    }

    return r;
  };
}

var arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'].group(2);

console.log(arr);

A version for if you want to discard a final group that doesn't match your expected length.

if (!Array.prototype.group) {
  Array.prototype.group = function (length, req) {
    var a = this.slice(), r = [], h;
    length = length || 1;

    while (a.length > 0) {
      h = a.splice(0, length);

      if (!req || h.length === length) {
        r.push(h);
      }
    }

    return r;
  };
}

var arr = ['an', 'odd', 'number', 'of', 'elements'].group(2, true);

console.log(arr)


text:
Q: Вопрос по list.append() У меня есть небольшой код:
from collections import defaultdict
basket = defaultdict(lambda: [])
basket = {670142777:[{'id': 2, 'cou':6},{'id': 1, 'cou':2}]}
item = dict.fromkeys('id','cou')

item['id'] = 3
item['cou'] = 12

basket[670142777].append(item)

print(basket)

На выводе получаю это:
{670142777: [{'id': 2, 'cou': 6}, {'id': 1, 'cou': 2}, {'i': 'cou', 'd': 'cou', 'id': 3, 'cou': 12}]}

Почему оно разделяет словарь на непонятные ключи і и d? и как это исправить?


text:
Q: Flutter align widgets in an expanded container, to the top left and bottom right? I have a layout in my application which comprises of some text and a timestamp. I'm looking to have the timestamp (clock icon in the picture) be at the bottom left corner of the expanded widget, while the text ("what" string in the picture) should start from the top right.
Representation:
|text|              |
|    -----------    |
|    empty space    |
|    -----------    |
|              |time|

Currently, what I managed below have them aligned to the extreme left and right, but they seem to be constrained by the Column widget and as such, are aligned to the centre of the widget. And I cannot seem to get expanded to work within another Expanded.

Widget code:
return new Container(
      child: new Row(
        children: <Widget>[
          new Column(
            children: <Widget>[
              new MaterialButton(
                minWidth: 60.0,
                child: new Icon(Icons.keyboard_arrow_up),
                onPressed: () => null,
              ),
              new Container(
                padding: new EdgeInsets.all(5.0),
                child: new Text("1231"),
              ),
              new MaterialButton(
                minWidth: 60.0,
                child: new Icon(Icons.keyboard_arrow_down),
                onPressed: () => null,
              ),
            ],
          ),
          new Expanded(
            // child: new Container(
            // padding: EdgeInsets.all(10.0),
            child: new Column(
              // mainAxisAlignment: MainAxisAlignment.end,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                new Align(
                  alignment: Alignment.topLeft,
                  child: new Text("what"),
                ),

                // "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."),
                new Align(
                  // padding: new EdgeInsets.all(10.0),
                  alignment: Alignment.bottomRight,
                  child: new Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: <Widget>[
                      new Container(
                        padding: new EdgeInsets.all(2.0),
                        child: new Icon(
                          Icons.access_time,
                          size: 12.0,
                        ),
                      ),
                      new Container(
                        padding: new EdgeInsets.all(2.0),
                        child: new Text("1 hr"),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            // ),
          ),
          new Column(
            children: <Widget>[
              new MaterialButton(
                minWidth: 60.0,
                child: new Icon(Icons.save, size: 20.0),
                onPressed: () => null,
              ),
              new Container(
                padding: new EdgeInsets.all(5.0),
                child: new Text("8"),
              ),
              new MaterialButton(
                minWidth: 60.0,
                child: new Icon(Icons.comment, size: 20.0),
                onPressed: () => null,
              ),
            ],
          ),
        ],
      ),
    );
  }

A: Ok, so I modified your Widget and I added some Colors to the container to track the changes very easy:
        double maxHeight = 130.0;

    Widget _buildLeft() {
      return Container(
        height: maxHeight,
        color: Colors.red,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            new MaterialButton(
              minWidth: 60.0,
              child: new Icon(Icons.keyboard_arrow_up),
              onPressed: () => null,
            ),
            new Container(
              padding: new EdgeInsets.all(5.0),
              child: new Text("1231"),
            ),
            new MaterialButton(
              minWidth: 60.0,
              child: new Icon(Icons.keyboard_arrow_down),
              onPressed: () => null,
            ),
          ],
        ),
      );
    }

    Widget _buildCenter() {
      return Expanded(
        child: Container(
          height: maxHeight,
          color: Colors.blue,
          child: Stack(
            children: <Widget>[
              Positioned(
                child: new Text("what"),
                top: 0.0,
                left: 0.0,
              ),
              // "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."),
              Positioned(
                bottom: 0.0,
                right: 0.0,
                child: new Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: <Widget>[
                    new Container(
                      padding: new EdgeInsets.all(2.0),
                      child: new Icon(
                        Icons.access_time,
                        size: 12.0,
                      ),
                    ),
                    new Container(
                      padding: new EdgeInsets.all(2.0),
                      child: new Text("1 hr"),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      );
    }

    Widget _buildRight() {
      return Container(
        height: maxHeight,
        color: Colors.green,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            new MaterialButton(
              minWidth: 60.0,
              child: new Icon(Icons.save, size: 20.0),
              onPressed: () => null,
            ),
            new Container(
              padding: new EdgeInsets.all(5.0),
              child: new Text("8"),
            ),
            new MaterialButton(
              minWidth: 60.0,
              child: new Icon(Icons.comment, size: 20.0),
              onPressed: () => null,
            ),
          ],
        ),
      );
    }

    @override
    Widget build(BuildContext context) {
      return new Container(
        child: new Row(
          children: <Widget>[
            _buildLeft(),
            _buildCenter(),
            _buildRight(),
          ],
        ),
      );
    }

A: try using alignment: Alignment.bottomRight as a named parameter of Container class

A: You can use a Container wrap the Align, This can stop Align from expanding itself
Container(
  color: darkBlue,
  child: Align(
    alignment: Alignment.center,
    heightFactor: value,
    child: Container(
    // alignment: Alignment.center, //<--must not uncomment this
      padding: const EdgeInsets.all(16),
      color: Colors.red,
      child: child,
    ),
  ),
)


text:
Q: Combining two special jQuery functions I have here this jQuery code:
$(window).on("load", function(){
$(".img-one").height($(".img-two").eq(0).width());
$(".img-one").css("width", "auto");
});

$(window).resize(function(){
$(".img-one").height($(".img-two").eq(0).width());
$(".img-one").css("width", "auto");
}).trigger("resize");

How is it possible to combine this .on and .resize, inclusive .trigger?

A: Like this:
function myFunc(){
  $(".img-one").height($(".img-two").eq(0).width());
  $(".img-one").css("width", "auto");
}

$(window).on("load resize", myFunc).resize();


text:
Q: MS SQL Selecting Specific dates with condition Ins No  AimSeqNumber    LearnRefNumber  LearnStartDate  DateEmpStatApp  EmpId
1000214  1                  10v1         2017-06-30     2016-08-30  900271388
1000214  1                  10v1         2017-06-30     2016-07-30  900271388
1000214  1                  10v1         2017-06-30     2014-07-30  900871388
1000214  1                  10v1         2017-06-30     2015-07-30  905271388

Hi I have a table like this. I want to get the empID where Latest DateEmpStatApp  on or before the LearnStartDate
I am not sure how to approach this. My initial logic was to use date-part function and find the difference in days. Then use min function to get the selected row. However I will still get more than one row. As I only want the empid for latest DateEmpStatApp  date that corresponds to the learnstartdate

A: SELECT TOP (1) EmpId
FROM MyTable
WHERE DateEmpStatApp < LearnStartDate
ORDER BY DateEmpStatApp DESC

Simply limit to the first row that meets your conditions

*

*"DateEmpStatApp on or before the LearnStartDate"

*"Latest DateEmpStatApp"

Edit, after comment
SELECT EmpId, LatestDateEmpStatApp = MAX(DateEmpStatApp)
FROM MyTable
WHERE DateEmpStatApp < LearnStartDate
GROUP BY EmpId


text:
Q: Directory path in C# In my winform application i need a path like
"D:\NEWD\WIN_NEW\Sales\Report\Report2.rdlc"

But i  have only "Sales\Report\Report2.rdlc" the thing is dat i can't predict this path D:\NEWD\WIN_NEW but when am using
Directory.GetCurrentDirectory() + "\\Sales\\Report\\Report2.rdlc";

the path includes my bin\debug directory. How can i get the desired path?

A: While youre debugging, the Path of the current directory (the path where the program is executed) will be in the .\bin\debug\ dir.
When you deploy the tool, you wont have this problem anymore.
It seems, you want to deploy the "Sales" directory with your tool: so maybe you should include this in your solution and select it to be copied to the output-directory (.\bin\debug) with your executable.

A: If you know that you are always going to be in bin\debug you could just do
 var path=System.IO.Path.GetFullPath(@"..\..\Sales\Report\Report2.rdlc");

Or you could do some detection
var path=@"Sales\Report\Report2.rdlc";
var currentDir=System.IO.Directory.GetCurrentDirectory();
if (currentDir.ToLower().EndsWith(@"\bin\debug") ||
    currentDir.ToLower().EndsWith(@"\bin\release")) {

  path=System.IO.Path.GetFullPath(@"..\..\" + path);
} else {
  path=System.IO.Path.GetFullPath(path);
}

Another form of detection would be to do the path strip only if you are debugging in which case DEBUG should be set so you could do...
var path=@"Sales\Report\Report2.rdlc";
#if DEBUG

path=@"..\..\"+path;

# end if
path=System.IO.Path.GetFullPath(path);

This last version has the advantage that all the extra detection is not compiled into your release code.

A: Hmm, I think this is more triccky question as it seems:
Considering that now you have bin\Debug, on deploy that path disappears, so saying GetCurrentDirectory(), I would say its better to use Path.GetDirectoryName(Application.ExecutablePath), you will be retrieved your deploy path. And also one day you may need to change file structure of your deploy, so...
Just in your bin\Debug or bin\Release replicate your future deploy files/folders layout, so your app will work in DEBUG and in DEPLOY in a same way. Always if it's possible.
Hope this helps.


text:
Q: How to write '&' in xml? I am using xmlTextWriter to create the xml.
writer.WriteStartElement("book");
writer.WriteAttributeString("author", "j.k.rowling");
writer.WriteAttributeString("year", "1990");
writer.WriteString("&");
writer.WriteEndElement();

But now i need to write '&' but xmlTextWriter will automatically write this one as "&amp";
So is there any work around to do this?
I am creating xml by reading the doc file.So if I read "-" then in xml i need to write "&ndash";.So while writing it's written as "&amp";ndash.
So, for example, if I am trying to write a node with the text good-bad, I actually need to write my XML such as <node>good–bad</node>.  This is a requirement of my project.

A: In a proper XML file, you cannot have a standalone & character unless it is an escape character.  So if you need an XML node to contain good–bad, then it will have to be encoded as good&ndash;bad.  There is no workaround as anything different would not be valid XML.  The only way to make it work is to just write the XML file as a plain text how you want it, but then it could not be read by an XML parser as it is not proper XML.
Here's a code example of my suggested workaround (you didn't specify a language, so I am showing you in C#, but Java should have something similar):
using(var sw = new StreamWriter(stream))
{
    // other code to write XML-like data
    sw.WriteLine("<node>good–bad</node>");
    // other code to write XML-like data
}

As you discovered, another option is to use the WriteRaw() method on XmlTextWriter (in C#) will write an unencoded string, but it does not change the fact it is not going to be a valid XML file when it is done.
But as I mentioned, if you tried to read this with an XML Parser, it would fail because &ndash is not a valid XML character entity so it is not valid XML.
– is an HTML character entity, so escaping it in an XML should not normally be necessary.
In the XML language, & is the escape character, so & is appropriate string representation of &.  You cannot use just a & character because the & character has a special meaning and therefore a single & character would be misinterpreted by the parser/
You will see similar behavior with the <, >, ", and' characters.  All have meaning within the XML language so if you need to represent them as text in a document.
Here's a reference to all of the character entities in XML (and HTML) from Wikipedia.  Each will always be represented by the escape character and the name (>, <, ", ')

A: In XML, & must be escaped as &. The & character is reserved for entities and thus not allowed otherwise. Entities are used to escape characters with special meanings in XML.
Another software reading the XML has to decode the entity again. < for < and > for > or other examples, some other languages like HTML which are based on XML provide even more of these.

A: I think you will need to encode it. Like so:
colTest = "&"
writer.WriteEncodedText(colTest)


text:
Q: Saving data to a model with association hasMany does not work I want to keep the information about posts to the user. Save turns. But at the output of the data on the posts no longer exists.
Why are not posts stored?
Fiddle: https://fiddle.sencha.com/#view/editor&fiddle/22mp
    Ext.define('Post', {
        extend: 'Ext.data.Model',

        fields: [{
            name: 'title',
            type: 'string'
        }]
    });

    Ext.define('User', {
        extend: 'Ext.data.Model',

        fields: [{
            name: 'name',
            type: 'string'
        }],

        hasMany: 'Post'
    });

    var user = Ext.create('User', {
        name: "user1"
    });

    user.posts().add({
        title: 'Post 10'
    });

    user.posts().sync();

    console.log(user.getData()); // There are no posts!

A: You have to use
user.getData({associated:true}); to get the associated data for more information please see the documentation.
https://docs.sencha.com/extjs/6.5.0/modern/Ext.data.Model.html#method-getData


text:
Q: RESTful API request with "Bearer" authentication for AppAnnie in Powershell I want to get data from AppAnnie via their API through Powershell.
Authentication is described here:
http://support.appannie.com/entries/23215057-2-Authentication
My code looks like:
$apiKey = "someApiKey"
$url = "api.appannie.com/v1.1/apps/ios/app/661947195/ranks?start_date=2014-04-23&end_date=2012-04-23&interval=hourly&countries=US+CN"
$headers = @{"Authorization" = "Bearer " + $apiKey}
$appAnnieResult = Invoke-RestMethod -Uri $url -Headers $headers
$appAnnieResult

The result:
Invoke-RestMethod : Der Remoteserver hat einen Fehler zurückgegeben: (401) Nicht autorisiert.

What am I missing?
Tried with and without http://, https:// in front of URL
To try it out you'll need an APIKey from AppAnnie (for which you'll need a free account)
Thank you!
Sandro
Update: with the suggest https prefix and extensive logging I get this as header information
Transfer-Encoding=chunked
Connection=keep-alive
Keep-Alive=timeout=10
Vary=Accept-Language,Cookie
Content-Language=en
Content-Type=application/json
Date=Thu, 24 Apr 2014 16:03:06 GMT
Set-Cookie=sessionId="someLongSessionId";
Path=/
Server=nginx
sessionId="theSameLongSessionId"=

The response type now is
"StatusCode":  400,
"StatusDescription":  "BAD REQUEST"

And I thought "Bad request" would be worse than "Unauthorized". But it looks like authorization is no longer the issue (there seems to be a session), but then something with my request must be wrong, right? From the given example I only changed the appId and the dates (checked the date for correct position of day and month)
Update 2:
Attempts with different parameters, responses as a comment at the end of the lines
$url = "https://api.appannie.com/v1.1/apps/ios/app/848160327/ranks?start_date=2014-04-23&end_date=2012-04-24" #400, bad request
$url = "https://api.appannie.com/v1.1/apps/ios/app/848160327/ranks?countries=US+CN" #403, forbidden
$url = "https://api.appannie.com/v1.1/apps/ios/app/848160327/ranks?interval=hourly" #403, forbidden
$url = "https://api.appannie.com/v1.1/apps/ios/app/848160327/ranks?countries=US+CN&interval=hourly" #403, forbidden
$url = "https://api.appannie.com/v1.1/apps/ios/app/848160327/ranks?start_date=2014-04-23&end_date=2012-04-24&interval=hourly" #400, bad request
$url = "https://api.appannie.com/v1.1/apps/ios/app/848160327/ranks?start_date=2014-04-23&end_date=2012-04-24&countries=US+CN" #400, bad request

I think the responses are what is to be expected from the docs, as start_date and end_date are the only required parameters. As long as they are in, it's a bad request (400), if not it becomes a forbidden (403)

A: Resolutions

*

*End date needs to be GREATER than start date

*I can not retrieve that kind of data for apps, which are not in my account (are not my own)

So all attempts would have been fruitless in some way

A: The doc seems to specify that "bearer" is lowercase.  Do you get the same error if you don't capitalize that word?
Also, it looks like you might need to encode the header like:
$headers = @{"Authorization"="bearer "+
[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($apiKey))}

Code to dump response exception details and headers:
try{
    $appAnnieResult = Invoke-RestMethod -Uri $url -Headers $headers
} catch {
    write-host (Convertto-Json $_.Exception.Response)
    $headers = $_.Exception.Response.Headers
    $cookies = $_.Exception.Response.Cookies
    $headers |% { write-host "$_=$($headers[$_])"}
    $cookies |% { write-host "$_=$($cookies[$_])"}
}

And you definitely want to keep the https:// in the uri.


text:
Q: Access DSL modem web configuration through Wireless Router. . I am having a DSL Modem ZTE 831 Series. To have Wireless Connectivity at home, I have connected Tenda WiFi Router W316R.
The address of DSL Modem is 192.168.1.1 The address of Wifi Router is 192.168.0.1
The physical connection settings are as below:
Modem has only one Lan port e.g before attaching WLAN router i was able to connect only one pc so after purchasing WLAN router, i connected that one Lan port of modem with WLAN router's internet port. So now traffic of modem directed to WiFi Router.
The Wifi Router has 4 Lan Ports and one internet port (connected with modem) and out of 4 remaining LAN ports, 1 of them i am using to connect a PC as i am not having WiFi adapter on that desktop PC.
Other devices are WiFi enabled like laptop and phones etc so i connect them wirelessly.
Now after clearing the scenario, i want to come to the original question that i am want to access DSL modem configuration through browser while being connected to Wifi Router.
I am able to access DSL modem configuration while internet is connected mean when DSL is UP, so I go to 192.168.1.1 through browser and can easily access mode configuration.
But as soon as Internet gets disconnected like when DSL goes down, I can not access modem configuration page.
I am wandering that why it is issue when DSL is down because I am connecting to device on my Local Area.
Can any expert me with that Please.

A: Your modem and router are on diffirent networks (192.168.1.1 and 192.168.0.1), consider using the router as a switch. If your router does not allow itself being used as a switch then consider upgrading your router firmware to DD-WRT. Check compatibility for your exact model before you do.


text:
Q: User stopped being sudoer after release upgrade I've upgraded one of web server, that was running Ubuntu from 11.10 to 12.04 (No downtime since it's creation, though serving 10-40k requests/daily).
 sudo apt-get install update-manager-core
 do-release-upgrade

During upgrade everything seemed normal. Restarted the instance (EC2): apache2, mysql - all seem to be running. But:
g****c@ip-10-**-**-***:~$ sudo apt-get install libssh2-php
[sudo] password for g****c:
g****c is not in the sudoers file.  This incident will be reported.

(I've backed up the instance before upgrading: On origin this user is sudoer).
How can I solve this issue ?
How do I do regain su on remote server?

A: You are in for some troubles. Unless you have a root user password set or access to another user still having sudo capabilities, you are out of luck and will have to get the machine into recovery mode somehow.
This may require physical access, but if you are using a hosted server, your hosting provider usually offers a web interface that may get your machine into that mode. Back up everything NOW if you haven't done so already.
If you can manage to get your machine into recovery mode, follow this post to regain sudo capabilities:
Lost my root access and unable to install any software or any other priviliged operations


text:
Q: Is any method to connect to iphone by bluetooth without asking accept? Is any method to connect to iphone by bluetooth without asking accept?
I want to write program with witch user can connect to each other without asking acception to connect to this program?
Is any solution for this?

A: NO.
And to fulfill the 30 character limit: is it possible on any device? can you imagine the consequences if this is possible?


text:
Q: Installing django-cms on Ubuntu 14.04 I've been trying to install django-cms into a virtual environment on Ubuntu. I've exactly followed the installation instructions in the docs (http://django-cms.readthedocs.org/en/support-3.0.x/introduction/install_from_scratch.html) but I keep getting an error after the following command.
djangocms -p . mysite

Error:
Path '.' already exists and is not empty, please choose a different one
If you want to use this path anyway use the -s flag to skip this check.

What does this mean and how do I resolve this?

A: You need to give the command a non-existing path as an argument in which it will create the project.
For example djangocms -p mysite mysite


text:
Q: Android Navigation Component: How to solve the circular navigation with nested graph? In our user requirement we have a flow like this.

I have searched the following:
https://developer.android.com/guide/navigation/navigation-principles
Circular Reference with Nested Nav Graphs
But nothing can help...
What I have done?
Currently I split 2 graph and add duplicate Fragment C in Graph2. Also, I change the graph start destination to Fragment C in graph 1 programmatically only I clicked from graph2. This is an ugly solution But I have no idea how to solve this issue.
My question is : Is there any way to do it rather making a duplicate destination and changing the start destination?
Graph 1:
<include app:graph="@navigation/graph2" />
<dialog
        android:id="@+id/fragmentA"
        android:label="Fragment A"
        tools:layout="@layout/fragmentA"/>
<dialog
        android:id="@+id/fragmentB"
        android:label="Fragment B"
        tools:layout="@layout/fragmentB">
    <action
            android:id="@+id/NavigateToGraph2"
            app:destination="@id/graph2">
</dialog>
<dialog
        android:id="@+id/fragmentC"
        android:label="Fragment C"
        tools:layout="@layout/fragmentC"/>
<dialog
        android:id="@+id/fragmentD"
        android:label="Fragment D"
        tools:layout="@layout/fragmentD"/>
<dialog
        android:id="@+id/fragmentE"
        android:label="Fragment E"
        tools:layout="@layout/fragmentE"/>

Graph 2
<dialog
        android:id="@+id/fragmentF"
        android:label="Fragment F"
        tools:layout="@layout/fragmentF"/>
<dialog
        android:id="@+id/fragmentG"
        android:label="Fragment G"
        tools:layout="@layout/fragmentG"/>
<dialog
        android:id="@+id/fragmentC"
        android:label="Fragment C"
        tools:layout="@layout/fragmentC"/>

A: I think it is better to create a graph for fragment F and break the circular loop.


text:
Q: macro for colouring track changes I am revising an article and have to put in colour the changes.
I do this manually (I created a macro) but it is tedious and imply another work when the article will be accepted (if it is^^).
\definecolor{green(munsell)}{rgb}{0.0, 0.66, 0.47}
\newcommand{\revONE}[1]{{\color{green(munsell)}#1}}

Is there a way to define a macro which will automatically colour the added text (using track changes) in the output file?
ps: I am totally new to latex...

A: You could check out latexdiff, which can highlight changes between different revisions of the latex source file.
I used it to highlight changes in a manuscript as requested by the reviewers and it work quite well for that purpose. In my case it had some kinks with changes in tables (if I recall correctly), but nothing that couldn't be easily fixed (manually) with the help of the package's issue tracker.


text:
Q: How can I access the fields of an interface in Go? I'm trying to do this:
if event.Type == sdl.QUIT {
    utils.Running = false
}

But I can't because when I try to build, I get this error:
 ./mm.go:11: event.Type undefined (type sdl.Event has no field or method Type)

Here is the relevant source code of the library I'm trying to use:
type Event interface{}

type CEvent struct {
    Type uint32
    _    [52]byte // padding
}

type CommonEvent struct {
    Type      uint32
    Timestamp uint32
}

// WindowEvent (https://wiki.libsdl.org/SDL_WindowEvent)
type WindowEvent struct {
    Type      uint32
    Timestamp uint32
    WindowID  uint32
    Event     uint8
    _         uint8 // padding
    _         uint8 // padding
    _         uint8 // padding
    Data1     int32
    Data2     int32
}

As you can see, all of the other Events have the field Type. How can I access this?
Solution
This how I ended up polling events in this SDL2 binding for Go, in case anyone is wondering:
func PollEvents() {
    for {
        if event := sdl.PollEvent(); event != nil {
            switch event.(type) {
            case *sdl.QuitEvent:
                utils.Running = false
            }
        } else {
            break
        }
    }
}

A: You actually can't. Interfaces only define a method set that is available on a type, they do nothing to expose fields. In your case I would recommend doing a type switch. It would look a little like this;
     switch v := myInstance.(type) {
                case CEvent:
                        fmt.Println(v)
                case CommonEvent:
                        fmt.Println(v)
                case WindowEvent:
                        fmt.Println(v)
                default:
                        fmt.Println("unknown")
        }

You may want to structure your code a bit differently depending on what you're doing with the instance after this but that gives you the basic idea. You can also do a type assertion with a single type like; v, err := myInstance.(CommonEvent) but I doubt it would be as effective here. It also returns an error if the type of myInstance is not CommonEvent so it's not really the best way to go about figuring out what type and interface instance may be.

A: You will need to know the type. Let's say we know it's a CEvent:
cEvent, ok := Event.(CEvent)
if !ok {
    // You lied, not a CEvent
    return
}

// Otherwise, you can get the type!
fmt.Println(cEvent.Type)

Of course if you don't know the type, you can keep type asserting until you get it right. Otherwise, throw an error, return a default value, etc:
func getType(i interface{}) uint32 {
    cEvent, ok := i.(CEvent)
    if ok {
        return cEvent.Type
    }

    commonEvent, ok := i.(CommonEvent)
    if ok {
        return commonEvent.Type
    }

    // Etc

    return <default>
}

A: You can spend a lot of time doing reflection calls or trying to guess the type or using type switches.
Or you can just define an interface with functions that return the information you need.
For example you could do
type Event interface {
    GetCommonEvent() *CommonEvent
    GetWindowEvent() *WindowEvent
}


text:
Q: Recovering mysql database from an unbootable hard disk We have installed a Linux Authentication Gateway (run on Ubuntu Server) for more than a year ago. It has several features built in upon install such as Squid, php5, mysql, etc.
The thing is this: we see that the OS might have some corrupted crucial data structures. The system is now no longer usable. For instance, upon booting up, it complains a lot of "segmentation fault" and several commands have [fail] instead of [ok]. The list is just huge and let's just say that we can't do anything from there any more. We can't even log in. When you log in as root, the OS simply bounces you back, asking you for your username again and again, in an infinite loop.
So, now, we want to at least recover our mandatory files. We basically use a live CD, boot it up and see things in our hard disk. But the mandatory directory: "mysql" located at var/lib/ is inaccessible. On the window GUI, the directory is visible but it has a rectangle with an X on it. When trying to access, copy or compress the directory, a message box popped up and complained that we do not have the privilege to do such action. Sounds like a privilege problem? Well, we simply turn on the terminal and navigate to the var/lib/ directory, hoping to do some simple chmod. However, what is shocking is the mysql directory is INVISIBLE. ls command does not list it out. Using some directory check bash command, the program says that there is no mysql directory to be found as well. And all these commands are already under root privilege.
So in this problem, we want to retrieve everything in the mysql directory via Live CD. How do we accomplish this?

A: I think you mounted the root directory with your live cd, but forgot to mount /var where the mysql data lives, and that why you couldn't see the mysql data. Find which partition /var was mount on and mount it, and the mysql data should be there.

A: We have consulted with the software developer ourselves, and it turned out that they embedded homebrew scripts to prevent typical users from messing with their crucial stuff.
We simply turn the machine in to their company and let them fix it...


text:
Q: Working with Date functions mysql and adding day to date while keeping track So I have this table
CREATE TABLE `chittytransactions` (
  `ChittyTransactionID` int(11) NOT NULL,
  `AuctionID` int(11) NOT NULL,
  `ChittyAccNo` int(11) DEFAULT NULL,
  `Date` datetime DEFAULT NULL,
  `Amount` double DEFAULT NULL,
  `Description` varchar(50) DEFAULT NULL,
  `TransRefence` varchar(50) DEFAULT NULL COMMENT 'Reference from actual Bank transaction',
  `TransStatus` tinyint(1) DEFAULT NULL COMMENT 'If Transaction Pending or Cleared',
  `ClearanceDate` datetime DEFAULT NULL,
  `PaymentMethod` int(1) DEFAULT NULL COMMENT '0- Cash, 1- bank transfer, 2- personal credit etc'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Im creating a trigger that checks the Date and the clearanceDate to see if the clearanceDate is greater than the actual date then add a late fee. I have this so far:
DROP TRIGGER IF EXISTS chitty_before_trig;

DELIMITER ;;
CREATE TRIGGER chitty_before_trig BEFORE INSERT ON chittytransactions
FOR EACH ROW
  BEGIN
  DECLARE `userId` INT(11);

  SELECT `UserId`
  INTO `userId`
  FROM chittyusers
  WHERE ChittyAccNo = NEW.ChittyAccNo;

    IF NEW.ClearanceDate <> NEW.`Date` THEN
            UPDATE `chittyusers` SET LatePaymentFee = 50 WHERE UserId = userId;
    END IF;
 END;;
 DELIMITER;

Using the date functions how can i check if a day has gone by etc and add a calculate late payment for each day?Please anything would be great Thank you.

A: If I've understood the question, then something like
IF NEW.ClearanceDate > NEW.`Date` THEN
  UPDATE chittyusers
    SET LatePaymentFee = 10 * DATEDIFF(NEW.ClearanceDate, NEW.`Date`)
    WHERE UserId = userId;
END IF;

would work with your current schema. DATEDIFF(date1, date2) returns the number of days between date1 and date2 - the result is negative if date1 is earlier than date2. Note I've changed the comparison operator from <> to > so the late fee is applied if ClearanceDate is after Date, but not if it's before.
I should point out that having a bare numeric constant like 10 in your code like that is considered very bad form. A slightly better way would be to declare a local variable named something like baseLateFee, set it to 10, and then use the variable in your calculation. A much better alternative, especially if there's any possibility that baseLateFee will ever change, would be to store it in a table somewhere so you can update it without having to find and change all the code that depends on it.


text:
Q: unable to delete a content type from a webpart Sharepoint2013 We have a custom webpart with a dropdown menu which contains some content types. We have changed some of the types but now I cannot change or delete the old content types. Its in use because before some documents have been created base don those contens. I cannot also delete those documents. Just want to delete or hide the content types. Is it possible?

A: As @Christoffer stated in comment, open document library with explorer which option is available in ribbon. Copy all documents in folder in local drive. Delete documents from document library. Delete content type and again copy all documents in document library with explorer.


text:
Q: HTML Select Input Bug on iOS11 HTML Select Input Dropdown is not getting dismissed properly on iOS 11. Upon closing the dropdown, an empty dropdown with blank options reappears in its place.
Nothing has changed, and we started getting complaints from iOS users, we could not replicate. Updated iOS to latest and now can replicate. The issue is, that they are always blank, from then on.
Pressure has been put on us to resolve this issue, has anyone came across this issue and have a workaround to resolve?
This is a cordova application, jQuery, bootstrap and knockoutjs. Any help be appreciated. I know it may be vague and no code but this is basic html selects.

A: Update to ios 11.2 and issue has been resolved. After reading plenty of news articles this was nothing compared to the list of bugs that went out on this version.


text:
Q: Find a triplet with sum=0 in a BST - Time complexity with below code I wrote the below code for finding a Triplet in a BST that adds upto 0. But having difficulty determining the time complexity.
The find() method's time complexity is O(logn). Is the time time complexity of isTriplet() O(n^2) ?
bool find(Node* root, int target) {
  if (root == NULL)
      return false;

  if (root->data == target)
      return true;

  return (target < root->data) ?  find(root->left, target) :  find(root->right, target);
}

bool isTriplet(Node* root, Node* actualRoot) {
  if (root == NULL)
     return false;

  if (root->left == NULL && root->right == NULL)
      return false;

  int sum = root->data;
  if (root->left)
      sum += root->left->data;
  else if (root->right)
      sum += root->right->data;

  sum = -1 * sum;

  return (find(actualRoot, sum) || isTriplet(root->left, actualRoot) || isTriplet(root->right, actualRoot));
}

A: A triplet with sum = 0 means a node, a left and a right child having the sum of the three elements equals to 0.
Let's think logically. Where should we search for such triplets starting from the root of the tree? Basically, if the root is a positive, then to the left and if the root is a negative, then to the right.
When should we check whether such a triplet is found? In the case when there is at least a negative and at least a positive among the three numbers. 0 is a special case, I will deal with it separately.
If such a sum is found, then we should return it and should stop the algorithm. So, if the node is not 0 and there is no triplet, then we know which sub-tree to search in. If it is a triplet, then we have a trivial case, since the solution is found. If the current node is 0, then we should check whether its triplet is 0. If it is not, then we can stop the search, as no sub-tree will contain positives and negatives. The exception, off course is when the current node is 0 and exactly one of its children is also 0. In that case we need to check that subtree as well.
The algorithm should have a base 2 logarithmical complexity for worst-case scenario. Proof:

*

*When such a triplet is found, the algorithm should stop.

*If no such triplet is found yet and the current node is not 0, then we have an interesting and a non-interesting subtree.

*If no such triplet is found yet and the current node is 0, then either:
3.1. Both its children are 0 and we have found such a triplet,
3.2. None of its children are 0 and therefore it is provable that no such triplet exists, or
3.3. One of its children is 0 but the other is not, in which case the 0 child defines the interesting subtree and the other child deinfes the non-interesting subtree.
Since all the cases are either trivially stopping the algorithm due to the existence or inexistence of a solution, or halve the tree into interesting and non-interesting subtrees, the algorithm traverses a single node the most on each level and therefore its complexity in worst case equals the height of the tree, which is binary logarithmical.


text:
Q: How to implement some convenient methods (e.g., flat_map, flatten) on Option? It would be nice if Rust's Option provided some additional convenience methods like Option#flatten and Option#flat_map, where flatten would reduce an <Option<Option<T>> to Option<T>, and flat_map would work like map, but takes a method/closure that returns an Option and flattens it.
flat_map is pretty straightforward:
fn opt_flat_map< T, U, F: FnOnce(T) -> Option<U> >(opt: Option<T>, f: F) -> Option<U> {
  match opt {
    Some(x) => f(x),
    None => None
  }
}

flatten is more complex, and I don't really know how to go about defining it. It might look something like:
fn opt_flatten<T, U>(opt: Option<T>) -> Option<U> {
  match opt {
      Some( Some(x) ) => flatten_option( Some(x) ),
      _ => opt
  }
}

But that certainly doesn't work. Any thoughts?
Also, how would I go about implementing these methods on the Option enum, so that I can use them natively on an Option instance? I know I need to add the type signature in somewhere around impl OptionExts for Option<T>, but I'm at a loss...
Hope this makes sense and I apologize for my imprecise terminology--I'm brand new to Rust.

A: fn flatten<T>(x: Option<Option<T>>) -> Option<T> {
    x.unwrap_or(None)
}

In my case, I was dealing with an Option-returning method in unwrap_or_else and forgot about plain or_else method.

A: These probably already exist, just as different names to what you expect. Check the docs for Option.
You'll see flat_map more normally as and_then:
let x = Some(1);
let y = x.and_then(|v| Some(v + 1));

The bigger way of doing what you want is to declare a trait with the methods you want, then implement it for Option:
trait MyThings {
    fn more_optional(self) -> Option<Self>;
}

impl<T> MyThings for Option<T> {
    fn more_optional(self) -> Option<Option<T>> {
        Some(self)
    }
}

fn main() {
    let x = Some(1);
    let y = x.more_optional();
    println!("{:?}", y);
}

For flatten, I'd probably write:
fn flatten<T>(opt: Option<Option<T>>) -> Option<T> {
    match opt {
        None => None,
        Some(v) => v,
    }
}

fn main() {
    let x = Some(Some(1));
    let y = flatten(x);
    println!("{:?}", y);
}

But if you wanted a trait:
trait MyThings<T> {
    fn flatten(self) -> Option<T>;
}

impl<T> MyThings<T> for Option<Option<T>> {
    fn flatten(self) -> Option<T> {
        match self {
            None => None,
            Some(v) => v,
        }
    }
}

fn main() {
    let x = Some(Some(1));
    let y = x.flatten();
    println!("{:?}", y);
}

Would there be a way to allow flatten to arbitrary depth

See How do I unwrap an arbitrary number of nested Option types?


text:
Q: PyTorch: Multi GPU error: RuntimeError: binary_op(): expected both inputs to be on same device, but input a is on cuda:0 and input b is on cuda:7 When I use multiple GPUs
and also when I use .cuda() for the tensors
in the middle of training, I got following error
RuntimeError: binary_op(): expected both inputs to be on same device,
but input a is on cuda:0 and input b is on cuda:7

which means following R2 is on cuda:7 (not sure R2 in on cuda:0 or cuda:7) and
R1 is on cuda:0
so, operation is impossible because they're on difference GPU
R2=torch.where(R2<1e-4,torch.Tensor([1e-4]).squeeze().cuda(),R2)
div_R1_R2=torch.div(R1,R2)

I get exactly same error in the following code
complaining O_img_tc and R_gt_img_tc can't be calculated
because they're on different GPU
R_gt_img_tc=torch.where(
  torch.abs(R_gt_img_tc)<1e-4,
  torch.Tensor([1e-4]).squeeze().cuda(),R_gt_img_tc)
sha=torch.clamp(torch.div(O_img_tc,R_gt_img_tc),0.0,1.3)[:,0,:,:].unsqueeze(1)

How to solve this, and what am I doing wrong?

What I've tried:
- Use horovod: got same error.
- Check the GPU number by using dense_O_img_tc.get_device() and dense_S_gt_img_tc.get_device()
When they were like dense_O_img_tc.get_device() returned 0, dense_S_gt_img_tc.get_device() returned 7
And I tried this
same_cuda=torch.device('cuda:'+str(dense_O_img_tc.get_device()))
dense_S_gt_img_tc=torch.where(
  torch.abs(dense_S_gt_img_tc)<1e-4,
  # Note here that I'm using cuda(same_cuda)
  torch.Tensor([1e-4]).squeeze().cuda(same_cuda),dense_S_gt_img_tc)

ref=torch.div(dense_O_img_tc,dense_S_gt_img_tc)

That actually could resolved "different GPU issue"
but only GPU:0 was used, resulting in full of GPU:0 error.

*

*So, I tried to move dense_O_img_tc which is on the GPU:0 towards GPU:7 (or anywhere dense_S_gt_img_tc is on by using dense_S_gt_img_tc.get_device()), I might have got following illegal memory access error

RuntimeError: cuda runtime error (77) : an illegal memory access was encountered at /opt/conda/conda-bld/pytorch_1544199946412/work/aten/src/THC/generic/THCTensorMath.cu:238


text:
Q: How can I disable/hide the Dev Tools plugin in Kibana I want to hide the Dev Tools menu item in Kibana, but according to their roadmap, that's not possible with their permission system nor will it be anytime soon. (see https://discuss.elastic.co/t/disable-hide-management-plugin-kibana-5/72763)
Kibana is inside an iFrame hosting a site on the container's domain.

A: I ended up using MutationObservers in JavaScript to watch for changes to the DOM inside the iFrame in order to hide the menus I didn't want non-admins to see.  Solution written in AngularJS 1.2 and is known to work with Kibana 6.2 and 6.3.  This will hide several "left side" menus as well as a bunch of Management sub-menus. You can use or modify the code to hide/show additional UI elements. Unfortunately, I had to rely on classes a lot since very few elements contained IDs I could reference.
I hope this at least helps you think of your own solution to managing Kibana display elements outside of their permission structure.
HTML:
    <iframe id="AnalysisFrame" ng-src="{{kibanaUrl}}" ng-init="setupFrame()"></iframe>

JavaScript:
    $scope.setupFrame = function() {
        //iframes are excluded from mutation observation, so we will
        //  need to create an observer _inside_ the iframe content.
        var theFrame = document.querySelector('#AnalysisFrame');
        //once the frame is loaded, that is when we can now attach our
        //  observer to the frame's content.
        theFrame.onload = function() {
            //console.log('[TRACE] iframe is completely loaded');
            var bIsKibanaAdmin = $scope.bIsKibanaAdmin;
            //the above is TRUE|FALSE set by some outside logic
            //  which does not pertain to this exercise.

            //create an observer instance for Management sub-menus
            var observerMan = new MutationObserver(function(mutations) {
                mutations.forEach(function(mutation) {
                    //console.log('[TRACE] ', mutation);
                    //sub-menus of the Management console area
                    var manArea = theFrame.contentDocument.body.querySelector('kbn-management-landing');
                    if ( manArea ) {
                        //Management area is divided up by panels of related subjects
                        var manPanels = manArea.querySelectorAll('div[class*="page-row"]');
                        if ( manPanels ) manPanels.forEach(function(aPanel) {
                            //console.log('[TRACE] panel=', aPanel);
                            //6.2.4 had <div> titles, 6.3.x has <h3> titles, select based on their class only
                            var panelTitle = aPanel.querySelector('.kuiPanelHeader__title');
                            //if a panel has a title (version panel does not have one), see if hide or not.
                            if ( panelTitle ) switch ( panelTitle.innerText ) {
                                case 'Kibana':
                                    //only hide the Advanced Settings item off this panel
                                    var panelItem = aPanel.querySelector('li > a[href*="#/management/kibana/settings"]');
                                    if ( panelItem ) panelItem.parentElement.hidden = !bIsKibanaAdmin;
                                    break;
                                default:
                                    //most management panels are hidden from non-admins
                                    aPanel.hidden = !bIsKibanaAdmin;
                            }//switch
                        });
                    }
                });
            });
            //configuration of the left menu becomes active observer
            var configMan = {
                    attributes: true, //for when Management becomes the Active menu
                    attributeFilter: ['class'],
                    //attributeOldValue: true,
                    childList: false,
                    characterData: false,
                    //characterDataOldValue: false,
                    //subtree: true,
            };
            //the Management menu item does not exist yet, cannot start observing until later.

            //create an observer instance for left menu
            var observer = new MutationObserver(function(mutations) {
                mutations.forEach(function(mutation) {
                    //console.log('[TRACE] ', mutation);
                    var leftMenus = mutation.target.querySelectorAll('.global-nav-link');
                    //since the menus do not have IDs, we are searching for their outer
                    //  DIV class unique to all left menu items. Their first element child
                    //  will be the <a href> link we can use to filter out ones we
                    //  wish to show or not.
                    if ( leftMenus ) leftMenus.forEach(function(aMenu) {
                        if ( aMenu.firstElementChild ) {
                            switch ( aMenu.firstElementChild.hash ) {
                                case "#/dev_tools":
                                    aMenu.hidden = !bIsKibanaAdmin;
                                    break;
                                case "#/account":
                                    aMenu.hidden = true;
                                    break;
                                case "":
                                    if ( aMenu.innerText=='Logout' ) {
                                        aMenu.hidden = true;
                                    }
                                    //else console.log('[TRACE] menu=', aMenu);
                                    break;
                                case "#/management":
                                    //we only want to hide certain sub-menus
                                    //  our menu item exists, attach observer for when
                                    //  user clicks it to make it "active"
                                    observerMan.observe(aMenu, configMan);
                                    break;
                                default:
                                    //console.log('[TRACE] menu=', aMenu);
                            }//switch
                        }
                    });
                });
            });
            //configuration of the left menu creation observer
            var configLM = {
                    attributes: false,
                    //attributeFilter: ['src'],
                    //attributeOldValue: true,
                    childList: true,
                    characterData: false,
                    //characterDataOldValue: false,
                    //subtree: true,
            };
            //start observing the contents of the iframe changes
            observer.observe(theFrame.contentDocument.body, configLM);
        };
    };


text: Q: How to update the existing custom domain in APIM using Azure cli or PowerShell command I am trying to update the existing APIM custom domain with new ssl certificate which is in keyvault. But couldn't find the command for the same. Can any one help me with cli or PowerShell command to achieve this.


text:
Q: Cloud-init: Add apt source key gnupg not installed I've a cloud-init script that is used to create and configure a Debian 10 VM and since I want to install nginx I have to add its repository to APT.  I'm trying to do it like this:
apt:
  preserve_sources_list: true
  sources:
    nginx:
      source: "deb http://nginx.org/packages/debian $DEBIAN_RELEASE nginx"
      key: |
          -----BEGIN PGP PUBLIC KEY BLOCK-----
          Version: GnuPG v2.0.22 (GNU/Linux)

          mQENBE5OMmIBCAD+FPYKGriGGf7NqwKfWC83cBV01gabgVWQmZbMcFzeW+hMsgxH
          QxnZZIbETgcSwFtDun0XiqPwPZgyuXVm9PAbLZRbfBzm8wR/3SWygqZBBLdQk5TE
          ...
          =EWWI
          -----END PGP PUBLIC KEY BLOCK-----
packages:
  - nginx

It doesn't work and cloud-init's log file at /run/cloud-init/result.json shows the following:
{
 "v1": {
  "datasource": "DataSourceConfigDrive [net,ver=2][source=/dev/vdb]",
  "errors": [
   "('apt-configure', ProcessExecutionError(\"Unexpected error while running command.\\nCommand: ['apt-key', 'add', '-']\\nExit code: 255\\nReason: -\\nStdout: \\nStderr: E: gnupg, gnupg2 and gnupg1 do not seem to be installed, but one of them is required for this operation\"))"
  ]
 }
}

Why? It complaints it can't use apt-key because gnupg isn't present however how can I make sure it exists? According to /etc/cloud/cloud.cfg cloud-init runs the APT modules before installing packages so how am I supposed to get a working apt-key with gnupg?
Thank you.

A: Add this to your configuration, which causes apt-get to run after the network is up but before the official cloud-init sections:
bootcmd:
  - DEBIAN_FRONTEND=noninteractive apt-get -yq update
  - DEBIAN_FRONTEND=noninteractive apt-get -yq install gnupg

There's another solution on the Debian Bug Tracking System which shows you how to specify a new source and key without causing a call to gnupg, but (for me) that makes your cloud-init configuration less clear.


text:
Q: iPhone 6 iOS 9.3.2 – How to change date years back? There are several recommendations to set back the date in order to delete some photos, but I can't find a way to do that.

A: Settings > General > Date & Time
Switch off Set Automatically, then tap on the date underneath.
You get a standard date/time scroller.


text:
Q: KeyError: "None of [Int64Index([ ... dtype='int64', length=802)] are in the [columns] How to deal with this index problem when using keras? Looking at my shape everything looks normal:
X = DF.iloc[:, 0:10]
Y = DF.iloc[:, 10:15]

X.shape, Y.shape

((1003, 10), (1003, 5))

X e Y:

Training:
for train, test in kfold.split(X,Y):

    model = Sequential()
    model.add(Dense(10,
                kernel_regularizer=l2(0.001),
                kernel_initializer=VarianceScaling(),
                activation='sigmoid',
                name='hidden-input'))
    model.add(Dense(5,
                kernel_regularizer=l2(0.001),
                kernel_initializer=VarianceScaling(),
                activation='sigmoid',
                name='output'))

    model.compile(loss='mse', optimizer='adam', metrics=['mse'])

    model.fit(X[train], Y[train], epochs=50, batch_size=5, verbose = 0,
              validation_data=(X[test], Y[test]))

    scores = model.evaluate(X[test], Y[test], verbose=0)
    print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
    cvscores.append(scores[1] * 100)

Output:
KeyError: "None of [Int64Index([ 201,  202,  203,  204,  205,  206,  207,  208,  209,  210,\n            ...\n             993,  994,  995,  996,  997,  998,  999, 1000, 1001, 1002],\n           dtype='int64', length=802)] are in the [columns]"


text:
Q: Source Control Base Eclipse Configurations Short Version:
Is there an easy way to source control a project configuration for eclipse? I'm okay with source controlling an export of configs that others can import when they first setup the project. So that when others roll on the project they don't have to do a ton of configurations to get this more complex project running.
Details:
1) Specifically for my main question, I'm working on a project that I had to get working that has submodules of sub modules, so I've had to right click on the project -> Configure -> Configure and Detect Nested Projects and import the submodules several times. After that on each module I had to right click -> Configure -> Convert to Maven Project. In addition to this, I had to set a lot of Derived folders so that searches were more meaningful in the IDE.
2) Lastly I think this is specific to the eclipse instance, however think there should be a way to export/import this as well. In order to get the project running, I have to setup a couple maven run/debug configurations that target jetty:run and pass like 4 params.
Ideally, I'd like it to be in a way that others can quickly clone the repo, import the configuration easily and be working with a baseline configuration, so that they don't have to be an eclipse expert to load the project and do simple things with it.

A: Everything you've described so far is contained between the .settings, .classpath and .project folder and files.  you should be able to commit those file to your source repository and check them out as java projects.
Even though this is against the typical Maven guidance.
The classpath file will likely cause your project to have errors though if someone checks that file out without having run maven to actually download those dependencies to their local artifactory.

A: Want to make a note here for others, in case they have a similar question. Props to Aleksandr who commented on this yesterday, which I didn't understand until today. This adds more detail on his comment.
My process I described in number 1 is not the proper process I should of followed. I was trying to do things the difficult way. Instead of opening the folder then trying to configured everything I should of instead did a File -> Import -> Existing Maven Project.
If you are in a similar state. Kill your folder, do the equivalent of re-cloning the git repo into a clean folder, then do the import as stated above.
The above detects the submodules from the parent pom file. This also helps everything display properly in the IDE. It will also handle the build and target folders properly, so avoid derived folder issues and much much more.


text:
Q: Retrieve specific type of activity from vactivity feed Youtube api V3 I would like to retrieve only certain type of activities of the youtube api v3 activites list. there are so many types:
-bulletin
-channelItem
-comment
-favorite
-like
-playlistItem
-recommendation
-social
-subscription
-upload
I want to be able to retrieve only upload,comment and recommendation. How would I do that? I have the following request and this retrieves all types:
function requestVideoPlaylist() {
    var requestOptions = {
    home: 'true',
    part: 'snippet, contentDetails',
    maxResults: 8
  };

  var request = gapi.client.youtube.activities.list(requestOptions);
  request.execute(function(response) {

    var activityItems = response.result.items;

});}


text:
Q: Xcode Project File Reference Paths for Frameworks for Different Build Configurations I am having a problem with the "Link Binary with Libraries" and "Copy Files" paths in my workspace when I try to build for different configurations - "Debug" and "Release" Those paths are stored in the pbxproj file of the xcodeproj package and do not vary with build configuration.
I have a workspace, Application.xcworkspace, that builds two frameworks and an executable that uses those frameworks. My Derived Data Location is set to "Workspace-relative" Here is roughly how they are laid out:
Framework_1 - Built and output to the Derived Data path.

Framework_2 - Depends on Framework_1, which is included in the Frameworks area of the project and specified in the "Link Binary with Libraries" Build Phase, and output to Derived Data path.

Application - Depends on Framework_1 and Framework_2, which are included in the Frameworks area of the project and specified in the "Link Binary with Libraries" Build Phase. Output directory is again the Derived Data path.

The paths in the project file for the referenced frameworks are the Derived Data path - they are like
Workspace Path/DerivedData/Workspace Name/Build/Products/Debug/Framework_1.framework

That path is the same regardless of what I build for - running (debug), testing (debug) or profiling (release).
My problem is when I build for profiling (release), the paths to the frameworks are still the debug paths, and thus the release version of the app links to debug frameworks and the debug frameworks get bundled into app->Contents->Frameworks (via a Copy Files build phase). Even worse, if I do a Clean, or delete the Derived Data directory, and try to build for profiling (release), it will not build or run because the referenced files (debug) do not exist.
I know one way to do make this work is to have two workspaces - one for debug and the other for release. That would be a big hassle.
Would another way to do it be to have another target?
What is the correct way to resolve this issue? Any help appreciated.

A: I think I figured out a fairly clean way to get this problem solved.
My first stab at it was two targets - one set up to link to and copy the debug framework, the other to do the same with the release framework. Very much a hack and the output from the second target had a different name, and each of the targets still had the original problem. However, I could get the same app functionality with a separate configuration build of the framework (Debug with Debug, Release with Release).
I then stepped back to think about the problem, and realized I just needed a single directory to house the link-to and copy-file version of the framework, but I needed to populate it differently depending on configuration. That made me think of scripts, and that worked out. I ended up adding a pre-action Run Script Build Phase to clean away any old copies of the framework and copy in the correct one. Here is the script for a framework called Simple.framework where the DerivedData location is Workspace-relative:
rm -R "${SRCROOT}/../Frameworks/Simple.framework"
cp -R "${SRCROOT}/../DerivedData/TestTarget/Build/Products/${CONFIGURATION}/Simple.framework" "${SRCROOT}/../Frameworks/Simple.framework"

So, for my project outlined above, I would put a phase like that for each of the frameworks in the app Build Phases.

A: I made a script via your idea.
You even don't need to change DerivedData location( set to Default Location ).

*

*Edit scheme... > Build (expand) > Post-actions

*Change 'Provide build settings from 'None' to 'SCHEME_NAME'

*Paste command below
if [ -n "${SRCROOT}" ] && [ -n "${FULL_PRODUCT_NAME}" ] && [ -d "${SRCROOT}/../Frameworks/${FULL_PRODUCT_NAME}" ]; then rm -rf "${SRCROOT}/../Frameworks/${FULL_PRODUCT_NAME}"; fi
if [ -n "${BUILT_PRODUCTS_DIR}" ] && [ -n "${SRCROOT}" ] && [ -n "${FULL_PRODUCT_NAME}" ]; then cp -aR "${BUILT_PRODUCTS_DIR}/${FULL_PRODUCT_NAME}" "${SRCROOT}/../Frameworks/"; fi

*close & enjoy


text:
Q: Aspose.Word template foreach syntax I try build template in .doc file. I use mail merge to bind data. In my template I use field like <<TableStart:ListData>> ... <<TableEnd:ListData>> to building table. I now how add if statement {IF ="True" ... }. But how add foreach loop? In this page: Mustache syntax is description of mustache syntax with foreach. How add this code to template.docx ?
My c# code - it may be usefull:
        var document = GetDocumentFromTemplate("SystemConfigurationTemplate.docx");
        var model = BuildModel();
        var asposeDataSource = new AsposeDataSource(document, model);
        document.MailMerge.Execute(asposeDataSource);
        document.Save(stream, SaveFormat.Pdf);

A: Please paste the following syntax in Word document:
{{ #foreach list }}{{ Number }}{{ /foreach list }}

You then need to call MailMerge.ExecuteWithRegions method to see foreach tag in action. Please see following code:
DataTable dataTable = new DataTable("list");
dataTable.Columns.Add("Number");

for (int i = 0; i < 10; i++)
{
    DataRow datarow = dataTable.NewRow();
    dataTable.Rows.Add(datarow);
    datarow[0] = "Number " + i.ToString();
}

Document doc = new Document(MyDir + @"in.docx");

doc.MailMerge.UseNonMergeFields = true;
doc.MailMerge.ExecuteWithRegions(dataTable);

doc.Save(MyDir + @"17.8.docx");

I work with Aspose as Developer Evangelist.


text:
Q: Does NetBIOS do any caching? If I read a file from a UNC network share does Windows cache parts of that file?
For example: If I read the whole file byte for byte, will each read call result in a request over the network, or does Windows read larger blocks internally, and serve subsequent request from memory?

A: If I understand it correctly contents of the file may be cached.
To make sure that all reads will be done against the actual file and not from any system buffer or disc cache one could use the FILE_FLAG_NO_BUFFERING in a call to CreateFile.
You can also disable caching for a shared resource using net share <sharename> /cache:none


text:
Q: The Functional Equation $ ( x + y ) \big( f ( x ) - f ( y ) \big) = ( x - y ) f ( x + y ) $, need solution have answer Find all functions $ f: \mathbb R \to \mathbb R $ such that for all reals $ x $ and $ y $,
$$ ( x + y ) \big( f ( x ) - f ( y ) \big) = ( x - y ) f ( x + y ) \text . $$
I actually got the answer by guessing and checking, $ f ( x ) = a x ^ 2 + b x $, but I want to see the solution. My friend suggested surjectivity but I don't see how to continue.
$ f ( x ) = f \left( \frac x { f ( x ) ^ 2 } \right) $;
this is what I just got.
The answer is correct, just need a solution. Thanks!

A: For differentiable functions, the only solution is as you have suggested (I can't tell if differentiability can be dropped). To see this, first let $y=0$ and $x\ne 0$, and you obtain
$$x(f(x)-f(0))=xf(x)\implies f(0)=0\,.$$
Now, assume $xy\ne0$ and rewrite your identity as follows:
$$\frac{f(x+y)-f(y)}{x}+\frac{f(x)}{x}=\frac{f(x+y)-f(x)}{y}+ \frac{f(y)}{y}\,$$
which upon taking the limit as $y\to 0$ on the both sides gives us
$$\frac{f(x)}{x}+\frac{f(x)}{x}= f'(x) +f'(0)\implies f'(x)-\frac{2}{x}f(x)+f'(0)=0\,.$$
Using the integrating factor method, the solution to this becomes $$f(x)=ax^2+f'(0)x\,,$$ for some constant $a$.

A: For any real numbers $ a $ and $ b $, if we define the function $ g : \mathbb R \to \mathbb R $ with $ g ( x ) = f ( x ) - a x ^ 2 - b x $, then using the original functional equation, we'll have
$$ ( x + y ) \big( g ( x ) - g ( y ) \big) = ( x - y ) g ( x + y ) \text . \tag 0 \label 0 $$
In particular, setting $ a = \frac { f ( 1 ) + f ( - 1 ) } 2 $ and $ b = \frac { f ( 1 ) - f ( - 1 ) } 2 $, we will also have $ g ( 1 ) = g ( - 1 ) = 0 $. Letting $ y = 1 $ in \eqref{0}, we get
$$ ( x + 1 ) g ( x ) = ( x - 1 ) g ( x + 1 ) \text , \tag 1 \label 1 $$
while substituting $ x + 1 $ for $ x $ and $ - 1 $ for $ y $ in \eqref{0} we have
$$ x g ( x + 1 ) = ( x + 2 ) g ( x ) \text . \tag 2 \label 2 $$
\eqref{1} and \eqref{2} together show that
$$ 2 g ( x ) = x ( x + 1 ) g ( x ) - ( x - 1 ) ( x + 2 ) g ( x ) = x ( x - 1 ) g ( x + 1 ) - ( x - 1 ) x g ( x + 1 ) = 0 \text . $$
Therefore $ g $ is the constant zero function, and hence $ f ( x ) = a x ^ 2 + b x $ for all $ x \in \mathbb R $. It's straightforward to see that any function of this form satisfies the original functional equation, and thus they form the class of all the solutions.


text:
Q: Repainting/Refreshing Graph in D3 I currently have a dropdown and datepicker that when clicked, returns a new data source. A similar method is seen here.
This data source is used to create my graph and scale up/down the amount of data shown.
Generally, my source code follows this construct:
var updateGraphData = function(error, json) {
    updateGraph(json);
}

    // datepicker code goes here
    // url param update code as seen in linked jsfiddle goes here

function MakeUrl() {
    var urlSource = BaseURL + param1 + param2; /*these values are defined in the param code mentioned */
    d3.json(urlSource, updateGraphData);
}

    //set dimensions
var margin = {top: 30,right: 60,bottom: 30,left: 60
};
var width = 800 - margin.left - margin.right;
var height = 400 - margin.top - margin.bottom;
var color = d3.scale.category10();

function updateGraph(json_data) {
    /* everything I want drawn goes here, i.e. axes, lines, points, labels, etc.*/
};

Now, my appended url source code works -- the graph does re-render with the proper data set. BUT ONLY when I define my SVG element inside the updateGraph function. When I do that, a new graph renders with the proper, BUT it pops a new graph below the old one. Which is not what I want. I want my new graph to replace the old one.
When I tried pulling my SVG element before the updateGraph function (so defined where the margin and dimensions are defined), the graph didn't repeat on dropdown change, but it layered the data in such a way that I was unable to see any useful data.
Basically, I am not able to remove all my graph elements on a new data request. How would you suggest going about this? I feel like it should be as easy as using a svg.selectAll("*").remove() in my updateGraphData() function, but that just stops any data from being rendered inside the SVG at all.
Any advice for me?
Thank you very much! Let me know if I'm not being clear.

A: Alright Team,
After hours and hours of searching for an answer, I finally found one. Hopefully, this will help someone else.
So like I said, I was getting new graphs to append below the old graph. I was having issues getting the previous data to clear out, and I couldn't seem to figure out how to specify a specific graph to clear without clearing all of my data (old and new) away.
The solution is simply adding the line:
d3.selectAll("g > *").remove()

In my updateGraph() function.
This deletes all of the "g" elements you previously created. That way, the svg container remains and you can populate with new data.


text:
Q: I got stuck on Python error TypeError: unhashable type: 'slice' from informedSearch import *
from search import *

class EightPuzzleProblem(InformedProblemState):
    """
    Inherited from the InformedProblemState class. To solve
    the eight puzzle problem.
    """
    def __init__(self, myList, list = {}, operator = None):
        self.myList = list
        self.operator = operator
    def __str__(self):

       ## Method returns a string representation of the state.

        result = ""
        if self.operator != None:
            result += "Operator: " + self.operator + ""
        result += " " + ' '.join(self.myList[0:3]) + "\n"
        result += " " + ' '.join(self.myList[3:6]) + "\n"
        result += " " + ' '.join(self.myList[6:9]) + "\n"
        return result
    def illegal(self):
        ## Tests whether the state is illegal.
        if self.myList < 0 or self.myList > 9: return 1
        return 0

    def equals(self, state):

        ## Method to determine whether the state instance
        ## and the given state are equal.

        return ' '.join(self.myList) == ' '.join(state.myList)

    ## The five methods below perform the tree traversing
    def move(self, value):
        nList = self.myList[:] # make copy of the current state
        position = nList.index('P') # P acts as the key
        val = nList.pop(position + value)
        nList.insert(position + value, 'P')
        nList.pop(position)
        nList.insert(position, val)
        return nList

    def moveleft(self):
        n = self.move(-1)
        return EightPuzzleProblem(n, "moveleft")

    def moveright(self):
        n = self.move(1)
        return EightPuzzleProblem(n, "moveright")

    def moveup(self):
        n = self.move(-3)
        return EightPuzzleProblem(n, "moveup")

    def movedown(self):
        n = self.move(+3)
        return EightPuzzleProblem(n, "movedown")

    def operatorNames(self):
        return ["moveleft", "moveright", "moveup", "movedown"]

    def enqueue(self):
        q = []
        if (self.myList.index('P') != 0) and (self.myList.index('P') != 3) and (self.myList.index('P') != 6):
            q.append(self.moveleft())
        if (self.myList.index('P') != 2) and (self.myList.index('P') != 5) and (self.myList.index('P') != 8):
            q.append(self.moveright())
        if self.myList.index('P') >= 3:
            q.append(self.moveup())
        if self.myList.index('P') >= 5:
            q.append(self.movedown())

    def applyOperators(self):
        return [self.moveleft(), self.moveright(), self.moveup(), self.movedown()]

    def heuristic():
        counter = 0
        for i in range(len(self.myList)):
            if ((self.myList[i] != goal.myList[i]) and self.myList[i] != 'P'):
                ## Position of current:
                current = goal.myList.index(self.myList[i])

            if current < 3: goalRow = 0
            elif current < 6: goalRow = 1
            else: goalRow = 2
            if i < 3: initRow = 0
            elif i < 6: initRow = 1
            else: startRow = 2

            initColumn = i % 3
            goalColumn = current % 3
            counter += (abs(goalColumn - initColumn) + abs(goalRow - initRow))
            return counter

#Uncomment to test the starting states:
init = ['1','3','P','8','2','4','7','6','5'] #A
#init = ['1','3','4','8','6','2','P','7','5'] #B
#init = ['P','1','3','4','2','5','8','7','6'] #C
#init = ['7','1','2','8','P','3','6','5','4'] #D
#init = ['8','1','2','7','P','4','6','5','3'] #E
#init = ['2','6','3','4','P','5','1','8','7'] #F
#init = ['7','3','4','6','1','5','8','P','2'] #G
#init = ['7','4','5','6','P','3','8','1','2'] #H
goal = ['1','2','3','8','P','4','7','6','5'] #goal state

InformedSearch(EightPuzzleProblem(init), EightPuzzleProblem(goal))

I run it and it shows error
line 34, in __str__ result += " " + ' '.join(self.myList[0:3]) + "\n"
TypeError: unhashable type: 'slice'

Any Ideas?

A: You're setting the "list" to a dictionary as a default value: list = {} in:
def __init__(self, myList, list = {}, operator = None):

and then assigning it to myList with:
self.myList = list

A dictionary cannot be sliced like a list. So when you try to slice it:
self.myList[0:3]

it fails.


text:
Q: Meteor EADDRINUSE exception on remote method with Fibers Below is my code in server/server.js file. When I call Meteor.apply('testMethod') I get Error: listen EADDRINUSE. I am running meteor app with meteorite, the only non-generic package installed is npm
var Fiber = Meteor.require('fibers');
var fiber = Fiber.current;
Meteor.methods({
    testMethod: function(){
        setTimeout(function(){fiber.run('test')}, 2000);
        res = Fiber.yield();
        console.log(res);
        return res;
    }
})

I know the most obvious solution here is to use Meteor's wrappers around fiber, but what I really want to implement is yielding from fiber on async call and then resuming within some event handler. And I have not found anything suitable for that.
Stack trace:
Error: listen EADDRINUSE
    at errnoException (net.js:901:11)
    at Server._listen2 (net.js:1039:14)
    at listen (net.js:1061:10)
    at net.js:1135:9
    at dns.js:72:18
    at process._tickCallback (node.js:415:13)

A: I answered this on the Meteor IRC.
Move this line:
var fiber = Fiber.current;

into the first line of the 'testMethod' function. Like so:
var Fiber = Meteor.require('fibers');

Meteor.methods({
    testMethod: function(){
        var fiber = Fiber.current;
        setTimeout(function(){fiber.run('test')}, 2000);
        res = Fiber.yield();
        console.log(res);
        return res;
    }
});

I believe why you're experiencing this is because each user gets their own "fiber". So when the client calls the server, the current fiber is different than the fiber you declared in the outer scope.


text:
Q: How to prevent CSS Grid blowout so that text-overflow ellipsis will work I am having some issues with CSS Grid "blow out" which is causing my text property text-overflow: ellipsis to not work.
I have seen many posts on this, and tried many things, but just don't understand what I have wrong. I can reproduce in a simple example.
In my case, I am using a third part component, where I want to put my UI inside one of it's elements.
For example, below the element third-party-container is the third part component, and my UI is contained in my-containerm where I wish to completely fill the third-party-container
HTML

S1

S2

aaaaaaaabbbbbbbbbbbccccccccccccccccccccccccccddddddddddddddd

CSS
    #third-party-container {
        height: 40px;
        width: 140px;
        background: orange;
    }

    #my-container {
        background: yellow;
        height: 100%;
        width: 100%;
        display:grid;
        align-items: center;
        justify-items: left;
        grid-template-columns: min-content 13px minmax(0, 1fr);
        grid-template-rows: 1fr;
        column-gap: 2px;
        white-space: nowrap;
    }

    #s1 {
        background: red;
         grid-row: 1;
         justify-items: left;
         grid-column: 1;
         align-items: stretch;
    }

    #s2{
        background: green;
        grid-row: 1;
        overflow: hidden;
        grid-column: 2;
    }

    #s3 {
        background: pink;
        grid-row: 1;
        justify-items: left;
        display: grid;
        align-items: center;
        grid-column: 3;
        min-width: 0;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

Also available at this Plunkr
So in my-container I have a single row, and 3 columns. The first two columns have quite small widths. The first columns may vary slightly, but will always be quite small. The 2nd is just fixed.
The third column s3 (coloured pink) is the one that may sometimes have longer text than can fit in the containers. However, this is what I see in the above example...

When I look at this in dev tools, I can see the s3 is "blowing out", ie not being contained within its container.

I had got around this before by using the minmax(0, 1fr) but it is not working here.
The outer container has a fixed width, and my-container is 100% of this.
What am I doing wrong and how I can get this to work?

A: The issue is the use of display:grid on #s3. Remove it and also add width:100%

#third-party-container {
  height: 40px;
  width: 140px;
  background: orange;
}

#my-container {
  background: yellow;
  height: 100%;
  display: grid;
  align-items: center;
  justify-items: left;
  grid-template-columns: min-content 13px minmax(0, 1fr);
  grid-template-rows: 1fr;
  column-gap: 2px;
  white-space: nowrap;
}

#s1 {
  background: red;
}

#s2 {
  background: green;
  overflow: hidden;
}

#s3 {
  background: pink;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  width:100%;
}

S1

S2

aaaaaaaabbbbbbbbbbbccccccccccccccccccccccccccddddddddddddddd


text:
Q: Using .shp files in R with leaflet and shiny I'd like to use the following .shp file to plot area development outlines for KY using leaflet in a shiny app. I use the code below, but I get an error that ".prj file is missing." Also, no outline shows up when I run the second line.
add<-shapefile("~/kyaddbnds.shp")
leaflet(add) %>% addTiles()

A: Here's what I did.
First, try assigning it to projection epsg:3857 - this is what Google Maps uses, and is in metres. So I did:
projection(add)="+init=epsg:3857"

Now I can transform that to lat-long and see where on the earth it thinks it is:
> bbox(spTransform(add,"+init=epsg:4326"))
       min      max
x 34.12644 54.06393
y 28.78893 36.04800

Okay, that's the wrong place. Kentucky is 89W to 82W, a span of 7 degrees, but this was making it about 20 degrees. A factor of three. Which is about the same factor as metres to feet. So I figured it might be one of those American state coordinate systems that uses feet rather than metres.
A little searching led me to EPSG:3091...
http://spatialreference.org/ref/epsg/3091/
So let's reassign and see where that projects to:
> projection(add)="+init=epsg:3091"

> bbox(spTransform(add,"+init=epsg:4326"))
        min       max
x -89.57120 -81.96479
y  36.49706  39.14773

Winner winner chicken dinner, as we say over here.
I can plot this on the Kentucky state map from the maps package:
> library(maps)
> map("state","kentucky", col="red",lwd=4)
> plot(spTransform(add,"+init=epsg:4326"),add=TRUE)

To use it in leaflet you probably need to transform it, so:
add2 = spTransform(add, "+init=epsg:4326")

gives you add2 in lat-long coordinates.
If you want to create a .prj file so that reading the shapefile results in the correct projection, download it from the ".PRJ file" link on the spatial reference web site: http://spatialreference.org/ref/epsg/3091/prj/
It should look something like this:
PROJCS["NAD83(HARN) / Kentucky Single Zone (ftUS)",GEOGCS["NAD83(HARN)",DATUM["D_North_American_1983_HARN",SPHEROID["GRS_1980",6378137,298.257222101]],P
RIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]],PROJECTION["Lambert_Conformal_Conic"],PARAMETER["standard_parallel_1",37.08333333333334],PARAM
ETER["standard_parallel_2",38.66666666666666],PARAMETER["latitude_of_origin",36.33333333333334],PARAMETER["central_meridian",-85.75],PARAMETER["false_ea
sting",4921250],PARAMETER["false_northing",3280833.333],UNIT["Foot_US",0.30480060960121924]]


text:
Q: Setup unique user before tasks run? How does one setup a user before any "tasks" are run? I would like to populate a bunch on self.my_value variables which are to be used in the tasks. I tried doing it in the on_start function but it runs in parallel with the tasks.
Is there a way to do this?


text:
Q: How to use filter function on string I have a string that looks like this: (5 Sonuç)
How do I extract number using filter function and not any string related function?
Filter function works on array but how do I make it work for a string
I can't use replace or match functions.

A: You can use filter on a string by calling Array.prototype.filter.call with your string as the "this" argument and the filter function as second arguments.
example :

var str = "5 dfkdf9 eofh"
let res = Array.prototype.filter.call(str, n=>!isNaN(parseInt(n)))

console.log(res)

A: Use the split() function to return an array then use the filter() function to take out the non-numbers in the array.
You can then convert back to a string (if needed) using string related functions

let myString = "5 Sonuç"

let myNum = myString.split("").filter(e => !isNaN(e));
console.log(myNum)

A: You can use the spread operator:
const str = "test99"
[...str].filter(c => c == "99");

And if, you faced the error:

Type 'IterableIterator' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators.

Instead of
[...str]

you can rely on
Array.from(str)

More on downlevelIteration


text:
Q: Display/Track/Delete Mysql Rows via JSP pages Im having the following Problem:
I Have made a web application which runs on Apache Tomcat.
Im using a Mysql Database as backend database for my application. The application Simply provides a GUI for entering rows,updating and deleting them
The problem is this, that when I insert a new row in my database using the MySql Database Interface (by passing an sql query directly), I can manipulate the rows From my JSp Pages (delete,select,Update)
However If i enter a new row in the database By using a JSP Page (JDBC connection), The row does get entered ,however Im unable to delete/select/update any columns
No errors are displayed. So can anyone kindly point out why is this happening? and how to resolve this?
Thanks
Here is the code for the jdbc Connection I use to insert the row in the Mysql database.

<%@page import="java.io.*"%>
<%@
 page import="java.sql.*"
 %>

<%

Connection connection = null;
Statement st = null;
ResultSet rs = null;
%>

<link href="style.css" rel ="stylesheet" type="text/css">

 Order Tracker

    <% if(session.getAttribute("username") !=null)
 {
 %>

New Order

Update Order

Track Order

Track Delay

View Database

Delete Order

Logout

<%
 String SNo=request.getParameter("Sno");
 String ProductName=request.getParameter("ProductName");
 String ProductType=request.getParameter("ProductType");
 String Model=request.getParameter("Model");
 String Make=request.getParameter("Make");
 String LicenseVoucher=request.getParameter("LicenseVoucher");
 String Location=request.getParameter("Location");

 %>

 <%
 try
 {

 Class.forName("com.mysql.jdbc.Driver").newInstance();
connection=DriverManager.getConnection("jdbc:mysql://localhost:3307/test","root"
,"root");
 st = connection.createStatement();

 String query="insert into inventory values
(' "+SNo+" ',' "+ProductName+" ','"+ProductType+" ',' "+Model+" ',' "+Make+" ','
 "+LicenseVoucher+" ','        "+Location+" ')";
  st.execute(query);
   out.println("DATA INSERTED");

 }

  catch(Exception e)
 {
  out.println("DATA NOT INSERTED");
 }
%>

 <%
 }
else { %>
 you are not logged in click here to login

 <%
} %>

A: The most straightforward way I have found to manipulate SQL from JSP is to use the tag library:
<%@ page import="java.io.*,java.util.*,java.sql.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%@ taglib prefix="sql"
           uri="http://java.sun.com/jsp/jstl/sql" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver"
     url="jdbc:mysql://localhost/TEST"
     user="user_id"  password="mypassword"/>
<sql:query dataSource="${snapshot}" var="result">
SELECT * from Employees;
</sql:query>

Emp ID
First Name
Last Name
Age

<c:forEach var="row" items="${result.rows}">

<c:out value="${row.id}"/>
<c:out value="${row.first}"/>
<c:out value="${row.last}"/>
<c:out value="${row.age}"/>

</c:forEach>

<sql:update dataSource="${snapshot}" var="count">
   INSERT INTO Employees VALUES (104, 2, 'Nuha', 'Ali');
</sql:update>

Let me know how you get on...

A: used prepared statement for inserting... seems to solve the problem somehow :|


text:
Q: How to control only Application Brightness in iOs? I want to control and set brightness only my application not the whole device.
I think there may be two ways:

*

*Using [UIScreen mainscreen] control. But that take effect on whole device using [UIScreen mainscreen] I get the brightness and set into various application mode (states), But that's way also not feasible for my app because when I am doing IN/OUT (Active/Deactive) many times then actual brightness not get.

*Using view but that's also not feasible app into many view and I want change brightness like every minutes. All view into set and get value are not perfect way. I think it's also not feasible.
So, any another ways?
Thanks in advance,

A: I edited your question for legibility, but I think you are close with your first thought.
The UIScreen documentation describes what you are saying: (emphasis mine)

brightness
The brightness level of the screen.
Brightness changes made by an app remain in effect only while the app is active. The system restores the user-supplied brightness setting at appropriate times when your app is not in the foreground. So if you change the value of this property, you do not need to record the previous value and restore it when your app moves to the background.

From reading the above it looks like you just need to change the [UIScreen mainScreen].brightness value.