Q: What is the equivalent of Matlab/Octave single type cast function in Python I have received the data from a socket. In Matlab, this data is converted into single precision by the following function
data_cal_rx = typecast(data_tcp2, "single");

Now I would like to have the same function in Python. Searching from google and Stack overflow, I saw that the single precision in Python is numpy.float32. So I replace by the following function:
import numpy as np
data_cal_rx = np.float32(data_tcp2)

data_tcp2 in Matlab is an array interger numbers with:
class:     uint8
dimension: 1x70848
however, when I received data_tcp2 by socket in Python, it is displayed as:
...
\x00\x00C\x00 QE\x00 \x04E\x00 'E\x00BE\x00D\x00\x00LE\x00\x00\x10*E\x00`\x00@D\x00\x10+\x00\x00C\x000I\x00\x00A\x00\x16\x00\x13\x00
...
And I got this error from the terminal in python:
ValueError: could not convert string to float:

It could be a problem with socket in python? Any help or idea would be greatly appreciated.
Thank you very much

A: As an example, let's start with 32-bit float array:
orig = np.arange(5, dtype=np.float32)

We'll convert this to a buffer of bytes:
data = orig.tobytes()

This is shown as:
b'\x00\x00\x00\x00\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@'

Note the initial "b", which indicates this is a bytes object, not a string. If your data is actually a string, see at the bottom of this answer.
Now that we've got our buffer of bytes containing the data in the array, we can convert this back to an array of 32-bit floating-point values with:
out = np.frombuffer(data, dtype=np.float32)

(out is now identical to orig).

If data is a string, you need to first cast it to a bytes buffer, which you can do with
data = bytes(data, 'latin1')

The "latin1" part is the encoding. This encoding seems to not change any data when converting from string to bytes.


Q: Rotate an image by 90,180,270 and 360 degrees every time a button is clicked and retain the rotation degree in portrait and landscape mode? I am making an app in android where in an image has to be rotated whenever rotate button is clicked by 90,180,270 and 360 degrees. The rotation has to be the same in portrait and in landscape mode.
I am a beginner in Android Programming and I have basic knowledge of Java.
Kindly, help me soon.
The code that I have used is as below.I can only rotate it 90 degrees once. How do it continue with it?
btn_rotate = (ImageButton) findViewById(R.id.btn_rotate);
        btn_rotate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Bitmap bmap = BitmapFactory.decodeResource(getResources(), R.drawable.about_us_ipad_p);
            Display d = getWindowManager().getDefaultDisplay();
            @SuppressWarnings("deprecation")
            int x = d.getWidth();
            @SuppressWarnings("deprecation")
            int y = d.getHeight();
            ImageView imgView = (ImageView) findViewById(R.id.imgViewEdit_Pic);
            Bitmap scaledBmap = Bitmap.createScaledBitmap(bmap, y, x, true);
            Matrix matrix = new Matrix();
            matrix.postRotate(90, 180, 270);
            Bitmap rotatedBmap = Bitmap.createBitmap(scaledBmap,0,0,scaledBmap.getWidth(),scaledBmap.getHeight(),matrix,true);
            imgView.setImageBitmap(rotatedBmap);

        }
    });

A: this piece of code may help you and it is self explanatory...
public class TestActivity extends Activity {
    private int rotation;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (savedInstanceState != null) {
            rotation = savedInstanceState.getInt("ANGLE");
        }
        final ImageView imageView = (ImageView) findViewById(R.id.imageView);
        final Button button = (Button) findViewById(R.id.iv_icon);
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        final int width = metrics.widthPixels;
        final int height = metrics.heightPixels;
        final Bitmap imageBitmap = BitmapFactory.decodeResource(
                getResources(), R.drawable.image1);
        final Bitmap scaledBitmap = Bitmap.createScaledBitmap(imageBitmap, width, height, true);
        imageView.setImageBitmap(getRotatedBitmap(scaledBitmap));
        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                rotation += 90;
                rotation %= 360;
                Bitmap bitmap = getRotatedBitmap(scaledBitmap);
                imageView.setImageBitmap(bitmap);
            }
        });
    }

    private Bitmap getRotatedBitmap(Bitmap bitmap) {
        if (rotation % 360 == 0) {
            return bitmap;
        }
        Matrix matrix = new Matrix();
        matrix.postRotate(rotation, bitmap.getWidth() / 2,
                bitmap.getHeight() / 2);
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                bitmap.getHeight() / 2, matrix, true);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt("ANGLE", rotation);
        super.onSaveInstanceState(outState);
    }
}

A: yourimage.setRotation(yourimage.getRotation() + 90);

A: In manifest file, lock your screen orientation like this:
android:screenOrientation="portrait"

or
android:screenOrientation="landscape"


Q: Error using "Xlmns" in XML document I want to generate below code snippet into xml with c#:
<?xml version="1.0" encoding="utf-8" ?>
<PrincetonStorageRequest
         xmlns="http://munichre.com/eai/dss/pct/v1.0"
         requestId="RequestOut_MAG_Test_02"
         timestampUtc="2015-02-19T09:25:30.7138903Z">
  <StorageItems>

and my code is :
XmlWriter writer = XmlWriter.Create(fileName);
writer.WriteStartDocument(true);
writer.WriteStartElement("PrincetonStorageRequest");
writer.WriteAttributeString("xmlns","http://example.com/abc/dss/pct/v1.0");

writer.WriteAttributeString("requestId",name);
writer.WriteAttributeString("timestampUtc","2015-02-19T09:25:30.7138903Z");

writer.WriteStartElement("StorageItems");

But I am getting

"The prefix " cannot be redefined from " to  within the same start element tag.

A: From your XML and the error, I believe it's because you are adding a default namespace after adding an element with no namespace declaration, so you're effectively creating an element and then changing its namespace.
Try the following code - it stops the error when I test it locally just for the XML I think you're trying to get:
        XmlWriter writer = XmlWriter.Create(fileName);
        writer.WriteStartDocument(true);
        writer.WriteStartElement("PrincetonStorageRequest", "http://example.com/abc/dss/pct/v1.0");
        writer.WriteAttributeString("xmlns", "http://example.com/abc/dss/pct/v1.0");

        writer.WriteAttributeString("requestId", name);
        writer.WriteAttributeString("timestampUtc", "2015-02-19T09:25:30.7138903Z");

        writer.WriteStartElement("StorageItems");

So when I create the PrincetonStorageRequest element I am specifying a namespace URI.
Edit: Just to check, this is the XML that gets created but I did have to add the code to write the end elements:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<PrincetonStorageRequest xmlns="http://example.com/abc/dss/pct/v1.0" requestId="RequestOut_MAG_Test_02" timestampUtc="2015-02-19T09:25:30.7138903Z">
<StorageItems/>


Q: When is this group compact? Let $K=\begin{pmatrix}
I_a & 0\\
0 & -I_b
\end{pmatrix}$, where a+b=n, and $I_a$ is the $a\times a$ identity matrix and similar definition for $I_b$. Let G be the group consisting of all complex $n\times n$ matrices such that $A^*KA=K$. For what values of a and b is G compact?
If $a=0$ or $b=0$, this just reduces to the unitary group, which is compact. However, if $n=2$ and $a=b=1$, then $A=\begin{pmatrix}
c & \sqrt{c^2-1}\\
\sqrt{c^2-1} & c
\end{pmatrix}$ is not bounded and in G. Is there a way to generalize this?

A: This groups is known as the indefinite unitary group, and it is not compact unless $a=0$ or $b=0$. One can show this in the general case almost as easily as the $a=b=1$ case, using a subset of matrices such as the subgroup
$$
\begin{bmatrix}
\cosh(\psi) &  & &  & \sinh(\psi) \\
 & 1 & & &  \\
 & & \ddots & & \\
 & & & 1 & \\
\sinh(\psi) & & & & \cosh(\psi)
\end{bmatrix}\ \ \ \ \ \ \ \psi\in\mathbb{R}
$$
which are not bounded in $\mathbb{C}^{n^2}$.


Q: Pass parameters in RestClient post request I want to send parameters with a POST request using the RestClient gem (but I don't want to pass the params as JSON).
In a GET request, I would have:
url = "http://example.com?param1=foo&param2=bar"
RestClient.get url

How can I pass the same params but in a POST request without passing a JSON ?

A: Read ReadMe file of Rest-client git, it has lots of examples showing different types of request.
For your answer, try :
url = "http://example.com"
RestClient.post url,:param1=>foo, :param2=>bar


Q: Preventing $-renaming of pattern names in lexically-scoped constructs When you use a lexically-scoped construct like With or Function to perform replacements in an expression, Mathematica might rename pattern names in that expression. It does so if the patterns appear on the lhs of a lexical scoping construct (such as Rule) whose rhs is altered by performing the replacement.
For example, we have
With[{s = c}, {t_ -> s, t_ -> 1}]

(* Out: {t$_ -> c, t_ -> 1} *)

Mathematica does this (I'm guessing) to prevent binding conflicts; if t_ lexically scopes the rhs of -> in t_ -> s, then we don't want to accidentally bind any t's that might occur in c once we substitute it in. For example, if we instead had s = f[t], we might accidentally create t_ -> f[t].
How do I prevent this? Since I'm trying to extract and manipulate pattern names from expressions, this is a bit of an issue for me! So far I've found two possibilities, but I don't know if I can trust them or why.
I'd be any sort of lexical replacement mechanism; but it would be cool to see a general-purpose way to prevent things from being renamed! :)
Work so far
1. The first possibility comes from noticing that Function only seems to rename variables when using a symbol as a formal parameter, and that e.g.
(t_ -> # &)[c]

(* Out: t_ -> c *)

might not ever rename anything. However, this makes replacements which require formal parameters (e.g. when having functions within functions and no other way to eliminate the ambiguity between which argument belongs to which function) difficult. So, I'd say this is only a partial solution without some other technique.
2. The second possibility comes from the sense that maybe we can "freeze" the expressions on the lhs's and prevent them from being touched by the renaming mechanism. Unfortunately, Hold (and all its evaluation-controlling variations, like Unevaluated and Inactivate) don't get in the way. However, Verbatim seems to, at least when surrounding (only) the scoping pattern:
With[{s = c}, {Verbatim[t_] -> s, Verbatim[t_ -> s]}]

(* Out: {Verbatim[t_] -> c, Verbatim[t$_ -> c]} *)

Is this robust? I couldn't see anything in the docs about it (but I could have missed it). This seems to work, but I have no guarantee that it does. So, that would also be useful as an answer, even if not the "holy grail" of turning off/reverting all $-renaming. :)
Further Background
In With[{s = c}, {t_ -> s, t_ -> 1}], since the rhs of t_ -> 1 is not touched by the replacement, there's no need to rename patterns on its lhs. In general, though, any touching of the rhs causes all variables that scope it on the lhs to be renamed:
With[{s = 1}, {a_, b_} -> s]

(* {a$_, b$_} -> 1 *)

At the top I said MMA renames "patterns which appear on the lhs of a lexical scoping construct...", but to be more precise I should have said something like "which are bound by a lexical scoping construct...", as being on the "lhs" is not always the criterion for being bound (and thus having a scope).
So, replacement happens provided the pattern names on the lhs actually do scope the part of the expression the replacement touched! If the scope of a given pattern name does not actually include the replacement, e.g. if the lhs is bound by some outer Rule instead, it is not renamed. Compare the two elements of the list output below:
With[{s = 1}, {(t_ -> s) -> 2, (t_ -> 2) -> s}]

(* Out: {(t_ -> 1) -> 2, (t$_ -> 2) -> 1} *)

The scope of t_ in (t_ -> s) -> 2 is 2, not s, as the outer -> binds it first (as far as I can tell).
There's also a discussion of this at this question, but it doesn't answer the question here. It's also discussed in the docs here.
Aside
If you try to "anticipate" the renaming by using e.g. t$ in your replacement expression, you can get away with inducing a binding:
With[{s = f[t$]}, t_ :> s]

(* Out: t$_ :> f[t$] *)

w /. With[{s = f[t$]}, t_ :> s]

(* Out: f[w] *)

This seems like an oversight—or maybe it's in the name of efficiency, and we just trust no one would ever feel ok ending a variable with $ in the first place?
If you're not careful, even two expressions where everything's the same, but you chose to write in the With constant explicitly, can wind up different:
3 /. {With[{d = 1}, With[{s = (e[t_] :> d)}, {t_ :> s}]],
      With[{d = 1}, With[{s = (e[t_] :> 1)}, {t_ :> s}]]}

(* Out: {e[Pattern[3, _]] :> 1, e[t_] :> 1} *)

Mathematica warns you something's weird with RuleDelayed::rhs, but still. Can anyone find any other exploits?


Q: Flutter : Can anybody help making custom TabController in flutter? I am making an app using flutter(dart). I need to make a tab controller with gradient background colour. I have used the DefaultTabController but couldn't get the way to add decoration or any gradient for App bar.Please find my code below:
import 'package:flutter/material.dart';
import 'package:vtech/CustomAppBar.dart';

class Policy extends StatefulWidget {
  @override
  _PolicyState createState() => _PolicyState();
}

class _PolicyState extends State<Policy> {
  @override
  Widget build(BuildContext context) {

    return MaterialApp(
      home: DefaultTabController(
        length: 3,
        child: Scaffold(

          appBar: AppBar(
            backgroundColor: Colors.pink,
            bottom: TabBar(
              tabs: [
                Tab(icon: Icon(Icons.directions_car)),
                Tab(icon: Icon(Icons.directions_transit)),
                Tab(icon: Icon(Icons.directions_bike)),
              ],
            ),
            title: Center(child:Text('POLICY')),
          ),
          body: TabBarView(
            children: [
              Icon(Icons.directions_car),
              Icon(Icons.directions_transit),
              Icon(Icons.directions_bike),
            ],
          ),
        ),
      ),
    );

  }
}

A: The AppBar and TabBar widgets do not allow to set a gradient, just a color.
To achieve what you need you can create a custom widget GradientAppBar or GradientTabBar built with a Stack that integrates a Container with a gradient and an AppBar or TabBar.
You create the GradientAppBar with parameters that would go to the Container and to the AppBar itself.
Here is a working example for Gradient AppBar. Below is a similar example just for the TabBar.
import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new Policy(),
    );
  }
}

class Policy extends StatefulWidget {
  @override
  _PolicyState createState() => _PolicyState();
}

class _PolicyState extends State<Policy> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DefaultTabController(
        length: 3,
        child: Scaffold(
          appBar: GradientAppBar(
            colors: [Colors.white, Colors.black],
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            elevation: 4.0,
            bottom: TabBar(
              indicatorColor: Colors.white,
              tabs: [
                Tab(icon: Icon(Icons.directions_car)),
                Tab(icon: Icon(Icons.directions_transit)),
                Tab(icon: Icon(Icons.directions_bike)),
              ],
            ),
            title: Center(child: Text('POLICY')),
          ),
          body: TabBarView(
            children: [
              Icon(Icons.directions_car),
              Icon(Icons.directions_transit),
              Icon(Icons.directions_bike),
            ],
          ),
        ),
      ),
    );
  }
}

class GradientAppBar extends StatefulWidget implements PreferredSizeWidget {
  // Gradiente properties
  final AlignmentGeometry begin;
  final AlignmentGeometry end;
  final List<Color> colors;

  // Material property
  final double elevation;

  // AppBar properties - Add all you need to change
  final Widget title;
  final PreferredSizeWidget bottom;

  @override
  final Size preferredSize;

  GradientAppBar({
    Key key,
    @required this.colors,
    this.begin = Alignment.centerLeft,
    this.end = Alignment.centerRight,
    this.elevation,
    this.title,
    this.bottom,
  })  : preferredSize = new Size.fromHeight(
            kToolbarHeight + (bottom?.preferredSize?.height ?? 0.0)),
        super(key: key); //appBar.preferredSize;

  @override
  _GradientAppBarState createState() => _GradientAppBarState();
}

class _GradientAppBarState extends State<GradientAppBar> {
  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Material(
          elevation: widget.elevation,
          child: Container(
            decoration: BoxDecoration(
                gradient: LinearGradient(
              begin: widget.begin,
              end: widget.end,
              colors: widget.colors,
            )),
          ),
        ),
        AppBar(
          backgroundColor: Colors.transparent,
          elevation: 0.0,
          bottom: widget.bottom,
          title: widget.title,
        ),
      ],
    );
  }
}

And here the example for the gradient TabBar.
import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new Policy(),
    );
  }
}

class Policy extends StatefulWidget {
  @override
  _PolicyState createState() => _PolicyState();
}

class _PolicyState extends State<Policy> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DefaultTabController(
        length: 3,
        child: Scaffold(
          appBar: AppBar(
            bottom: GradientTabBar(
              colors: [Theme.of(context).primaryColor, Colors.green],
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              tabBar: TabBar(
                //indicatorColor: Colors.white,
                tabs: [
                  Tab(icon: Icon(Icons.directions_car)),
                  Tab(icon: Icon(Icons.directions_transit)),
                  Tab(icon: Icon(Icons.directions_bike)),
                ],
              ),
            ),
            title: Center(child: Text('POLICY')),
          ),
          body: TabBarView(
            children: [
              Icon(Icons.directions_car),
              Icon(Icons.directions_transit),
              Icon(Icons.directions_bike),
            ],
          ),
        ),
      ),
    );
  }
}

class GradientTabBar extends StatefulWidget implements PreferredSizeWidget {
  // Gradiente properties
  final AlignmentGeometry begin;
  final AlignmentGeometry end;
  final List<Color> colors;

  final TabBar tabBar;

  GradientTabBar({
    Key key,
    @required this.colors,
    this.begin = Alignment.centerLeft,
    this.end = Alignment.centerRight,
    this.tabBar,
  }) : super(key: key);

  @override
  Size get preferredSize => tabBar.preferredSize;

  @override
  _GradientTabBarState createState() => _GradientTabBarState();
}

class _GradientTabBarState extends State<GradientTabBar> {
  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Container(
          height: widget.preferredSize.height,
          decoration: BoxDecoration(
              gradient: LinearGradient(
            begin: widget.begin,
            end: widget.end,
            colors: widget.colors,
          )),
        ),
        widget.tabBar,
      ],
    );
  }
}

A: you can try this
flexibleSpace: Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.centerLeft,
                end: Alignment.centerRight,
                colors: [
                  Colors.red,
                  Colors.blue
                ],
              ),
            ),
          ),

In Appbar
  appBar: AppBar(
  title: Center(child: Text("Add Student",),),
  flexibleSpace: Container(
    decoration: BoxDecoration(
      gradient: LinearGradient(
        begin: Alignment.centerLeft,
        end: Alignment.centerRight,
        colors: [
          darkblue,
          darkpurple
        ],
      ),
    ),
  ),
actions: <Widget>[
    IconButton(
    icon: Icon(Icons.account_circle,color: Colors.white,),),

],
),


Q: Wrong characters in some e-mail clients Have you seen an error like this? Using some email clients the characters appear to be different. I used the red squares to highlight the wrong words and the green squares for other words that are ok
The difference between them is that the words with special characters that are OK are written in the email template, whereas the wrong ones come from the database.
I tried sending this email to Hotmail and Gmail. In Hotmail they look different if they go to the Spam box. The special characters in the red squares are replaced by a '?', the others become a black a symbol

Do any of you know what is going on? Do you know how to fix it? Is it a problem in the client or the way the message is being encoded?
Thanks in advance

A: Try the steps below to see if that could help:
1)  From Outlook, click File from the top left > Options > Advanced
2) Scroll down until you see "International Options"
3) Check "Automatically Select Encoding for Outgoing..."
4) Select UTF-8 encoding from the drop down menu.

A: Try changing (or setting) the encoding in the html template. If it doesn't help, convert characters to html entities - that works in all email clients.


Q: crystal report is not printing online http://avas.hexaperkeducation.com/demo/Default.aspx
i built this application which print crystal report directly to printer.its working fine on my local system but when i upload it to online server page load keep running .
 con.Open();
 string sql = "select * from Student_Master";
 System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter(sql, con);
 DataSet ds = new DataSet();
 da.Fill(ds, "Student_Master");
 ReportDocument Report = new ReportDocument();
 Report.Load(Server.MapPath("CrystalReport.rpt"));
 Report.SetDataSource(ds);
 CrystalReportViewer1.ReportSource = Report;
 CrystalReportViewer1.DataBind();

 Report.PrintToPrinter(1, true, 1, 1);

A: Which version of crystal reports runtime you are using on server and on local system? Runtime should be 32bit.
You need to setup those two properties.
Report.PrintOptions.NoPrinter = false;
Report.PrintOptions.PrinterName = <printername>;

And printer should be available in network via this name.
If you are using IIS then application pool also need access to printer.
In app pool advanced settings you need to switch boolean prop "Enable 32-bit apps" to true. If this still does not help you can try change Identity to "LocalService" in those advanced settings.


Q: what is wrong in this main.xml? This is my main.xml
<com.example.parallax_sample xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res/com.example.parallax_sample"
    android:id="@+id/scrollView1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:overScrollMode="never">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="1000dp"
        tools:context=".MainActivity" >

        <RelativeLayout
            android:id="@+id/relativeLayout1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            tools:context=".MainActivity" >

            <ImageView
                android:id="@+id/imageView1"
                android:layout_width="match_parent"
                android:layout_height="100dp"
                android:src="@drawable/teste" />

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_alignParentLeft="true"
                android:text="Bottom"
                android:textColor="#ffffff"
                android:textSize="18sp" />

            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_alignParentTop="true"
                android:text="Top"
                android:textColor="#ffffff"
                android:textSize="18sp" />
        </RelativeLayout>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/relativeLayout1"
            android:text="@string/hello_world" />
    </RelativeLayout>

</com.example.parallax_sample>

when I switch to graphical layout I see nothing (grey screen) ,with the exception stating.
Exception raised during rendering: com.android.layoutlib.bridge.MockView cannot be cast to android.view.ViewGroup.
I may be wrong but it must be a problem of main.xml only .
How can i resolve it.
Here is the StackTrace
 E/AndroidRuntime(15768): FATAL EXCEPTION: main
 E/AndroidRuntime(15768): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.parallax_sample/com.appkraft.parallax_sample.MainActivity}: android.view.InflateException: Binary XML file line #1: Error inflating class com.example.parallax_sample
 E/AndroidRuntime(15768):   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)
 E/AndroidRuntime(15768):   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
 E/AndroidRuntime(15768):   at android.app.ActivityThread.access$600(ActivityThread.java:162)
 E/AndroidRuntime(15768):   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
 E/AndroidRuntime(15768):   at android.os.Handler.dispatchMessage(Handler.java:107)
 E/AndroidRuntime(15768):   at android.os.Looper.loop(Looper.java:194)
 E/AndroidRuntime(15768):   at android.app.ActivityThread.main(ActivityThread.java:5371)
 E/AndroidRuntime(15768):   at java.lang.reflect.Method.invokeNative(Native Method)
 E/AndroidRuntime(15768):   at java.lang.reflect.Method.invoke(Method.java:525)
 E/AndroidRuntime(15768):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
 E/AndroidRuntime(15768):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
 E/AndroidRuntime(15768):   at dalvik.system.NativeStart.main(Native Method)
 E/AndroidRuntime(15768): Caused by: android.view.InflateException: Binary XML file line #1: Error inflating class com.example.parallax_sample
 E/AndroidRuntime(15768):   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:698)
 E/AndroidRuntime(15768):   at android.view.LayoutInflater.inflate(LayoutInflater.java:466)
 E/AndroidRuntime(15768):   at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
 E/AndroidRuntime(15768):   at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
 E/AndroidRuntime(15768):   at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:281)
 E/AndroidRuntime(15768):   at android.app.Activity.setContentView(Activity.java:1881)
 E/AndroidRuntime(15768):   at com.appkraft.parallax_sample.MainActivity.onCreate(MainActivity.java:18)
 E/AndroidRuntime(15768):   at android.app.Activity.performCreate(Activity.java:5122)
 E/AndroidRuntime(15768):   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
 E/AndroidRuntime(15768):   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)
 E/AndroidRuntime(15768): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.parallax_sample" on path: DexPathList[[zip file "/data/app/com.example.parallax_sample-1.apk"],nativeLibraryDirectories=[/data/app-lib/com.example.parallax_sample-1, /vendor/lib, /system/lib]]
 E/AndroidRuntime(15768):   at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:53)
 E/AndroidRuntime(15768):   at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
 E/AndroidRuntime(15768):   at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
 E/AndroidRuntime(15768):   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)

A: Your root element on the xml is a custom element. If the graphical layout cannot render that first element, it won't be able to render the rest of them either.

A: "com.example.parallax_sample" is the problem, previews for custom view can't be created, though possibly it will work fine when you run it.


Q: Integer roots of $x^2+y^2 = 25$ and $x^3+y^4=145$ I'm trying to find the solution of $x^2+y^2=25$ and $x^3+y^4=145$.
I tried doing substitution, which leads me to:
$y^2=25-x^2$ substituted to $x^3+y^4=145$
$x^3+(25-x^2)^2=145$
$x^3+x^4-50x^2+480=0$
But it led me nowhere and I'm stuck.
A very detailed step will be much appreciated. Thanks!

A: First you want $x^3+x^4-50x^2+480=0$ more conventionally written $x^4+x^3-50x^2+480=0$
Then you can apply the rational root theorem - any integer $x$ must divide $480$.
Then you can apply your knowledge of $x^2+y^2=25$ to reduce the number of integers you have to test.
Or alternatively you can spot a solution.

A: Go with this: there are only eight integer solutions to $u^3 + 145 = v^2,$
(u,v)

u^3 + 145 = v^2

E_+00145: r = 2   t = 1   #III =  1
          E(Q) = <(-4, 9)> x <(-1, 12)>
          R =   1.6626192366
           8 integral points
            1. (-4, 9) = 1 * (-4, 9)
            2. (-4, -9) = -(-4, 9)
            3. (54, 397) = 1 * (-4, 9) - 1 * (-1, 12)
            4. (54, -397) = -(54, 397)
            5. (-1, 12) = 1 * (-1, 12)
            6. (-1, -12) = -(-1, 12)
            7. (6, 19) = -1 * (-4, 9) - 1 * (-1, 12)
            8. (6, -19) = -(6, 19)

see http://en.wikipedia.org/wiki/Mordell_curve and http://tnt.math.se.tmu.ac.jp/simath/MORDELL/ and http://tnt.math.se.tmu.ac.jp/simath/MORDELL/MORDELL+
Out of these, the only solution with $v$ a square is $(-4,9),$ so the only integer answers to $q^3 + 145 = r^4$ are $(-4,3)$ and $(-4,-3).$ Write $x=-q, y=r,$ you get $x^3 + y^4 = 145$ only for $(x=4, y=3)$ and $(x=4, y=-3).$
In both cases, $x^2 + y^2 = 25.$


Q: Wrong vector calculus in lecture note 5 of cs224n, Stanford I am studying NLP via cs224n from Stanford.
I am reading this lecture note now.
When you refer to the 5th page, they want to derive the gradient with respect to W for RNN, to show the mathematical reasoning behind the vanishing gradient problem.
Here, I found something weird for me.
Here, I have $h_{j} = Wf(h_{j-1}) + W^{hx}x_{[t]}$ and I want to calculate $\frac{{\sigma}h_{j}}{{\sigma}h_{j-1}}$.
Because second term of right-hand side is independent to $h_{j-1}$, from my calculation, $\frac{{\sigma}h_{j}}{{\sigma}h_{j-1}} = W {\cdot}diag[f'(h_{j-1})].$
But they say $\frac{{\sigma}h_{j}}{{\sigma}h_{j-1}} = W^T {\cdot}diag[f'(h_{j-1})].$
Why do they transpose? Their definition of Jacobian is most widely used one and it doesn't match with their result.
Who is right?


Q: How do you determine whether a menu item is enabled? A menu item can be enabled or disabled using EnableMenuItem. How do you determine whether an existing item is enabled?

A: Whether a menu item is enabled is stored as part of a menu item's state information. The following function reports, whether a menu item (identified by ID) is enabled:
bool IsMenuItemEnabled( HMENU hMenu, UINT uId ) {
    UINT state = GetMenuState( hMenu, uId, MF_BYCOMMAND );
    return !( state & ( MF_DISABLED | MF_GRAYED ) );
}

A few notes on the implementation:

*

*A menu item can have both MF_DISABLED and MF_GRAYED states. A disabled item looks just like an enabled item, but is otherwise inactive. Neither disabled nor grayed items can be selected.1)

*The MF_ENABLED state equates to 0. As a consequence, it cannot be tested directly, but an expression must be used instead (see GetMenuState).

For completeness, here's an implementation using the newer API (GetMenuItemInfo). Both implementations are functionally identical:

bool IsMenuItemEnabled( HMENU hMenu, UINT uId ) {
    MENUITEMINFO mii = { 0 };
    mii.cbSize = sizeof( mii );
    mii.fMask = MIIM_STATE;
    GetMenuItemInfo( hMenu, uId, FALSE, &mii );
    return !( mii.fState & MFS_DISABLED );
}

1)The distinction between grayed and disabled items is documented under About Menus: Enabled, Grayed, and Disabled Menu Items. This distinction is no longer exposed in the newer APIs (see MENUITEMINFO), where both MFS_DISABLED and MFS_GRAYED have the same value.


Q: Why am I getting the error: "cannot read properties of null (reading "style") when I try to integrate Plaid link in JS? My relevant code is as follows
function useLink(token){
     const handler = Plaid.create({
         token: token,
         onSuccess: (public_token, metadata) => {},
         onLoad: () => {},
         onEvent: (eventName, metadata) => {},
         recievedRedirectUri: window.location.href,
     });
}

But everytime I try to use my link token to pull up link on the frontend, I get the following error from link-unitialize.js:
Uncaught TypeError: Cannot read properties of null (reading 'style')

I checked the Plaid website and couldn't find this listed as a common error, so I must be doing something very wrong. What is the most likely cause of this?


Q: Sort and update list of objects based on variable change I am working on a algorithm which will solve a problem I have, but I am finding myself a little stuck. Here is the scenario:
I have an object which contains a variable called order.
public class Item
{
     public int Order{get; set;};

     public int ID{get; set;}; // not incremented can be any value!
}

So I have a list of these:
List<Item> list = new List<Item>().OrderBy((o) => o.Order);

And at any time the order value can be changed.
So if I want to change the first an items order value all other order values should update accordingly so there are no duplicates.
for (int i = 0; i <= list .Count - 1; i++)
{
    if (list [i].ID == inputID)
    {
        list [i].Order = inputNewPosition;
    }
    else
    {
        if (list [i].Order < inputNewPosition)
        {
            list [i].Order --;
        }
        else
        {
             list [i].Order ++;
        }
    }
}

This fails if I change the last item order to be the first, as this would make the first item order be 0!
Can anyone help?
Thanks

A: Let us look at the four situations for an element in your list (as we iterate through them). If (for terseness) we take old to be the item that is moving's old position and new to be its new position we have the following cases for an item in your list (draw them out on paper to make this clear).

*

*the current item is the one to be moved: move it directly

*the current item's order is < new and < old: don't move it

*the current item's order is ≥ new and < old: move it right

*the current item's order is ≤ new and > old: move it left

*the current item's order is > new and > old: don't move it

When we start enumerating, we know the where the item to be moved will end up (at new) but we do not know where it has come from (old). However, as we start our enumeration at the beginning of the list, we know at each step that it must be further down in the list until we have actually seen it! So we can use a flag (seen) to say whether we have seen it yet. So seen of false means < old whilst true means >= old.
bool seen = false;
for (int i = 0; i < items.Length; i++)
{
    if (items[i].ID == inputID)
    {
        items[i].Order = inputNewPosition;
        seen = true;
    }
}

This flag tells us whether the current item is >= old. So now can start shunting stuff around based on this knowledge and the above rules. (So new in the above discussion is inputNewPosition and whether we are before or after old we represent with our seen variable.)
bool seen;
for (int i = 0; i < items.Count; i++)
{
    if (items[i].ID == inputID) // case 1
    {
        items[i].Order = inputNewPosition;
        seen = true;
    }
    else if (seen) // cases 4 & 5
    {
        if (items[i].Order <= inputNewPosition) // case 4
        {
           items[i].Order--; // move it left
        }
    }
    else // case 2 & 3
    {
        if (items[i].Order >= inputNewPosition) // case 3
        {
            items[i].Order++; // move it right
        }
    }
}

Having said all of that, it is probably simpler to sort the collection on each change. The default sorting algorithm should be quite nippy with a nearly sorted collection.

A: Your question isn't very clear, but for the requirements you'd likely be best off doing an event on the object that contains Order, and possibly having a container object which can monitor that.  However I'd suspect that you might want to rethink your algorithm if that's the case, as it seems a very awkward way to deal with the problem of displaying in order.
That said, what is the problem requirement?  If I switch the order of item #2 to #5, what should happen to #3?  Does it remain where it is, or should it be #6?

A: This is how I solved the problem but I think there might be a more clever way out there..
The object that I need to update are policy workload items.  Each one of these has a priority associated.  There cannot be a policy workload item with the same priority.  So when a user updates the priority the other priorities need to shift up or down accordingly.
This handler takes a request object. The request has an id and a priority.
 public class UpdatePriorityCommand
 {
     public int PolicyWorkloadItemId { get; set; }
     public int Priority { get; set; }
 }

This class represents the request object in the following code.
//Get the item to change priority
PolicyWorkloadItem policyItem = await _ctx.PolicyWorkloadItems
                                          .FindAsync(request.PolicyWorkloadItemId);

//Get that item's priority and assign it to oldPriority variable
int oldPriority = policyItem.Priority.Value;

//Get the direction of change.
//-1 == moving the item up in list
//+1 == moving the item down in list
int direction = oldPriority < request.Priority ? -1 : 1;

//Get list of items to update...
List<PolicyWorkloadItem> policyItems = await _ctx.PolicyWorkloadItems
                                                 .Where(x => x.PolicyWorkloadItemId != request.PolicyWorkloadItemId)
                                                 .ToListAsync();

//Loop through and update values
foreach(var p in policyItems)
{
    //if moving item down in list (I.E. 3 to 1) then only update
    //items that are less than the old priority. (I.E. 1 to 2 and 2 to 3)
    //items greater than the new priority need not change (i.E. 4,5,6... etc.)

    //if moving item up in list (I.E. 1 to 3)
    //items less than or equal to the new value get moved down. (I.E. 2 to 1 and 3 to 2)
    //items greater than the new priority need not change (i.E. 4,5,6... etc.)
    if(
           (direction > 0 && p.Priority < oldPriority)
        || (direction < 0 && p.Priority > oldPriority && p.Priority <= request.Priority)
      )
    {
        p.Priority += direction;
        _ctx.PolicyWorkloadItems.Update(p);
    }
}

//finally update the priority of the target item directly
policyItem.Priority = request.Priority;

//track changes with EF Core
_ctx.PolicyWorkloadItems.Update(policyItem);

//Persist changes to database
await _ctx.SaveChangesAsync(cancellationToken);


Q: React - Google Maps component not rendering after componentDidMount I'm just having trouble with my Google Maps rendering when a search (with a postcode) happens. It seems like the map is rendering the null map centre, and then not re-rendering after setState in componentDidMount(), as the map is rendered blank/grey but with a hard refresh the map will load with the postcode. I've tried using componentWillMount() without any luck, anyone have any suggestions?
This is the code for my search page:
class SearchContainer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      map_centre: null
    };
  }

  componentDidMount() {
    const values = queryString.parse(this.props.location.search);
    axios
      .get("api/v1/search?postcode=" + values.postcode)
      .then(response => {
        var mapCentre = response.data.map_centre;
        this.setState({
          map_centre: mapCentre
        });
      })
      .catch(error => console.log(error));
  }

  render() {
    return (

        <GoogleMapComponent
          townCenters={this.state.townCenters}
          schools={this.state.schools}
          supermarkets={this.state.supermarkets}
          hotels={this.state.hotels}
          airports={this.state.airports}
          trainStations={this.state.trainStations}
          map_centre={this.state.map_centre}
          onMapMounted={this.handleMapMounted}
          onDragEnd={this.handleMapChange}
          onZoomChanged={this.handleMapChange}
          onMarkerClick={this.handleAdspaceShow}
          googleMapURL={url}
          loadingElement={<div style={{ height: `100vh`, width: `100%` }} />}
          containerElement={<div style={{ height: `100vh`, width: `100%` }} />}
          mapElement={<div style={{ height: `100vh`, width: `100%` }} />}
        />

        <input
          id="map-search-input"
          className="form-control d-none"
          type="search"
          placeholder="Enter new location"
          aria-label="Search"
          onChange={this.handlePostcodeChange}
          onKeyPress={this.handleNewSearch}
        />

    );
  }
}

This is the code for my Google Maps component:
const GoogleMapComponent = withScriptjs(
  withGoogleMap(props => (
    <GoogleMap
      defaultZoom={13}
      defaultCenter={props.map_centre}
      onDragEnd={props.onDragEnd}
      onZoomChanged={props.onZoomChanged}
      ref={props.onMapMounted}
    />
  ))
);

A: defaultCenter will only be used by the map for the initial render, so it will not have any effect if you change this value later.
If you use the center prop instead it will work as expected.
const GoogleMapComponent = withScriptjs(
  withGoogleMap(props => (
    <GoogleMap
      defaultZoom={13}
      center={props.map_centre}
      onDragEnd={props.onDragEnd}
      onZoomChanged={props.onZoomChanged}
      ref={props.onMapMounted}
    />
  ))
);

A: Be more specific with the library you are using...you have added the tags "google-maps-react" and "react-google-map" and both are different libraries...
google-maps-react = https://github.com/fullstackreact/google-maps-react
react-google-map = https://tomchentw.github.io/react-google-maps/
Anyway, I can see 2 options:
solution 1:
Add a conditional that renders  GoogleMapComponent only if map_centre is not null.
  render() {
    if(this.state.map_centre){
      return (

          <GoogleMapComponent
            townCenters={this.state.townCenters}
            schools={this.state.schools}
            supermarkets={this.state.supermarkets}
            hotels={this.state.hotels}
            airports={this.state.airports}
            trainStations={this.state.trainStations}
            map_centre={this.state.map_centre}
            onMapMounted={this.handleMapMounted}
            onDragEnd={this.handleMapChange}
            onZoomChanged={this.handleMapChange}
            onMarkerClick={this.handleAdspaceShow}
            googleMapURL={url}
            loadingElement={<div style={{ height: `100vh`, width: `100%` }} />}
            containerElement={<div style={{ height: `100vh`, width: `100%` }} />}
            mapElement={<div style={{ height: `100vh`, width: `100%` }} />}
           />

          <input
          id="map-search-input"
          className="form-control d-none"
          type="search"
          placeholder="Enter new location"
          aria-label="Search"
          onChange={this.handlePostcodeChange}
          onKeyPress={this.handleNewSearch}
          />

);
     }
     return
 Loading..
;
  }

solution 2:
Set a default lat/lng (not null) before you get the response.
constructor(props) {
    super(props);
    this.state = {
      map_centre: { lat: -34.397, lng: 150.644 }
    };
  }


Q: Why cant I pass a type to a generic method Ok a brief background.  I'm trying out various ways to test an API and I'm trying to allow a user to provide a simple CSV file of a API calls that my test framework can iterate over using a generic test method.  I'm having trouble passing the type  to my generic API call method.  Allow me to demonstrate.
Given I have a method with the following basic structure
public T GetData<T>(Uri uri, HttpStatusCode expectedStatusCode)
{
        var myHttpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
        myHttpWebRequest.Accept = "application/json";
        var response = (HttpWebResponse)myHttpWebRequest.GetResponse();

        if (response.StatusCode != expectedStatusCode)
            Report.Log(ReportLevel.Failure, "ExpectedResponseCode:" + expectedStatusCode.ToString() + " ActualResponseCode:" + response.StatusCode.ToString());

        string responseString = "";

        using (var stream = response.GetResponseStream())
        {
            var reader = new StreamReader(stream, Encoding.UTF8);
            responseString = reader.ReadToEnd();
        }

        return JsonConvert.DeserializeObject<T>(responseString);
    }

I can call the above as follows without issue
Person person = _apiHelper.GetData<Person>(uri, HttpStatusCode.Ok);

However assume I now have a Type that I have acquired as follows
Type returnType = Type.GetType(typeString, true, true);

why can I not call the GetData method as follows
var result = _apiHelper.GetData<returnType>(uri, HttpStatusCode.Ok);

Visual studio simply says it cant resolve the symbol

A: Just use the JsonConvert.DeserializeType overload that accepts a type parameter instead of the generic one:
public object GetData(Type t,Uri uri, HttpStatusCode expectedStatusCode)
{
    ....
    return JsonConvert.DeserializeObject(responseString,t);
}

This is a case of the XY problem. You want to deserialize arbitrary types (problem X) and think that somehow, you need pass a generic type at runtime (problem Y), so when you get stuck ,you ask about Y.


Q: going from one subject in PhD to another in Postdoc. Hi, my question is:
Is it acceptable to do a PhD in mathematics in a topic such as Number Theory and or Analysis and change subjects in postdoc to something different than these topics such as Geometry/Topology or something else?
I've looked on some pages of researchers in mathematics and most of them just continued their topic of dissertation after their graduation.
Thanks in advance.


Q: Connectivity via a Field Gateway with IoT Central I am building an IoT Solution based on non programmable devices. I can just configure a host where they can connect to send data and receive commands.
Now, supposed that I know the messaging protocol of the device, I would like to build a field gateway to apply protocol and identity translation with the IoT Hub behind IoT Central.
Is that doable ? If yes, may you drive me to the solution please ?

A: AFAIk, this scenario is not implemented yet. Please provide your feedback on the UserVoice.
All the feedback you share in these forums will be monitored and reviewed by the Microsoft engineering teams responsible for building Azure.
Reference: How to create IoT edge device on IoT central?


Q: React - Why this function in onClick doesn't work? If I write like this, click button works
<Menu.Item
    key={book.uid}
    onClick={() => this.changeColor(book)}
    >

But if I write like this:
onClick={this.changeName(book)}

the click doesn't work.
So if the function has arguments, I should use "() => xxx(argument); otherwise, I can just use "this.xxx", right?

A: Because doing this.changeName(book) will instantly call the function when rendering. And what your function returns is.. not a function, so when you click, nothing will happen.
And () => this.changeColor(book) is an arrow function, it has a similar (but not really) behavior as this syntax :
() => { this.changeColor(book) }

To avoid this, you could use your first code example or transform your function into a curried one and keep the second syntax in the render :
changeName = bookInfo => event => {
    /* Your code here */
}

When called once in the render, this function will return another function receiving the event and set the bookInfo first.


Q: Python GDAL does not install on Mac OSX El Capitan I am having several issues when installing pygdal in my Mac OSX El capitan. The procedure is the folowing:

*

*Install GDAL Libraries from http://www.kyngchaos.com/software/frameworks#gdal_complete

*pip install gdal
The output is the following:
.
.
.
    extensions/gdal_wrap.cpp:3085:10: fatal error: 'cpl_port.h' file not found

    #include "cpl_port.h"
         ^
2 warnings and 1 error generated.
error: command 'cc' failed with exit status 1

Looks like the installer cannot find the GDAL libraries, or headers (libgdal or gdal-devel in ubuntu).
Where are they placed in OSX?
FYI, the following /Library/Frameworks/GDAL.framework/Programs is into the $PATH variable.

A: I finally (with a little help from Cam_Aust) solved the problem !!!
Here is what I did:

*

*Find the cp_port.h file in your system: sudo find / -name cpl_port.h, My output was:

/Library/Frameworks/GDAL.framework/Versions/1.11/Headers/cpl_port.h      /opt/local/include/cpl_port.h

*Add the resulting folders to your $PATH in your bash init script (~/.bash_login or ~/.zshrc). This worked for me: export PATH=/Library/Frameworks/GDAL.framework/Headers:$PATH

*Open a new terminal session or source ~/.zshrc
After this, you can now pip install gdal:
Collecting gdal
Using cached GDAL-2.1.0.tar.gz
Installing collected packages: gdal
Running setup.py install for gdal ... done
Successfully installed gdal-2.1.0

A: After installing the GDAL Libraries from kyngchaos (as mentioned in the question) you should be able to find the python package ready to go.
I cheated and used that:
export PYTHONPATH=$PYTHONPATH:/Library/Frameworks/GDAL.framework/Versions/2.1/Python/2.7/site-packages


Q: why does an iOS universal app need to have two different xib files? I'm a newbie of iOS development and I'm confused regarding universal app.
We can use the same code, same xib file for iPhone 4(retina) and previous iPhones, but why we should write two different xibs for iPhone and iPad? What's the difference?
For iPhone and retina iPhone, we use "point" instead of pixel for the coordinate. Why we can't use the similar method for iPhone and iPad?

A: For some simple apps, it is possible to design your iPhone UI and reuse the same xib file for the iPad.  Just select your Target in XCode and copy the Main Interface text from iPhone / iPod Deployment Info to iPad Deployment Info.  If you're using a Main Storyboard, copy that too.  However, the iPad does not simply scale everything up from the 320*480 / 640*960 iPhone screen to the 768*1024 / 1536*2048 iPad screen.  @elgarva correctly says that this would look terrible.  Instead, the iPad version makes use of your autosizing masks to resize or reposition each view.
If all of your views can be considered to be left-middle-right or top-middle-bottom, this may work.  If you have anything more complicated, you'll need to design a separate iPad interface.
Duplicating your iPhone UI is not just discouraged for aesthetic reasons - iPhones often end up containing a deep and confusing navigation tree for tasks that the iPad can fit on a single screen.

A: The main reason, is that if you just scale the elements on the UI to fit the larger screen, it wouldn't look nice... and you don't need to do anything for it to work, it automatically does it for you if your app is iPhone only and installed on an iPad (if the user chooses to).
Having a different XIB lets you rearrange your app, and think it so that you can take advantage of the larger screen. You can probably show more information on one iPad view than on 3 different screens on the iPhone... so, your iPhone app could show basic info and expand it when the user taps on it, while your iPad version could show all the information on load, plus extra graphics that look nice but aren't needed, and wouldn't make sense on the iPhone screen.
PS: If you're starting a new app, I strongly suggest you using the storyboard if your app won't have a lot of views... it's really easy to get started and it lets you see your app flow at a glance.

A: The ratina display just doubles the resolution of original iPhone. If you don't provide separate graphics for retina display, then system just doubles the resolution of resources.
The points are related to physical size of screen, which is similar in old and new iPhones.
For iPads, the screen size changes. This means that its dimension in points will be different from that of iPhone.

A: duplicating the xib file and renaming that as filename~ipad.xib is working great for me in ios6.1


Q: How do I remove lambda expressions/method handles that are used as listeners? Java 8 has introduced lambda expressions, which is a great thing. But now consider rewriting this code:
class B implements PropertyChangeListener {
    void listenToA(A a) {
        a.addPropertyChangeListener(this);
    }

    void propertyChange(PropertyChangeEvent evt) {
        switch(evt.getPropertyName()) {
            case "Property1":
                doSomething();
                break;
            case "Property2":
                doSomethingElse();                case "Property1":
                doSomething;
                break;

                break;
    }

    void doSomething() { }
    void doSomethingElse() { }
}

class A {
    final PropertyChangeSupport pcs = new PropertyChangeSupport(this);

    void addPropertyChangeListener(PropertyChangeListener listener) {
        pcs.addPropertyChangeListener(listener);
    }

    void removePropertyChangeListener(PropertyChangeListener listener) {
        pcs.removePropertyChangeListener(listener);
    }
}

With lambda expressions and method references, it is no more necessary to have B implement PropertyChangeListner as we can write
class B {
    void listenToA(A a) {
        // using method reference
        a.addPropertyChangeListener("Property1", this::doSomething);
        // using lambda expression
        a.addPropertyChangeListener("Property2", e -> doSomethingElse());
    }

    void doSomething(PropertyChangeEvent evt) { }
    void doSomethingElse() { }
}

class A {
    final PropertyChangeSupport pcs = new PropertyChangeSupport(this);

    void addPropertyChangeListener(String name, PropertyChangeListener listener) {
        pcs.addPropertyChangeListener(name, listener);
    }

    void removePropertyChangeListener(String name, PropertyChangeListener listener) {
        pcs.removePropertyChangeListener(name, listener);
    }
}

I think the new code is not only shorter but also cleaner and easier to understand. But after reading the answers given here (duplicate of this one, but I think question and answer are more crisp), I can see no way to implement a method called stopListening() which would remove the listeners again.
I am sure that I am not the first one to stumble on this. So has anyone found a nice solution on how to use method handles as shown in this example and still being able to remove the listeners again later?
UPDATE
That was fast. Building on the answers by Mike Naklis and Hovercraft Full Of Eels, I ended up with this:
class B {
    void listenToA(A a) {
        a.addPropertyChangeListener("Property1", doSomething);
        a.addPropertyChangeListener("Property2", doSomethingElse);
    }

    final PropertyChangeListener doSomething = evt -> {};
    final PropertyChangeListener doSomethingElse = evt -> {};
}

A: You can use lambdas and still use variables. For example, if you had:
class B {
    private PropertyChangeListener listener1 = this::doSomething;
    private PropertyChangeListener listener2 = e -> doSomethingElse();

    void listenToA(A a) {
        // using method reference
        a.addPropertyChangeListener("Property1", listener1);
        // using lambda expression
        a.addPropertyChangeListener("Property2", listener2);
    }

Then it would be easy to remove listener1 or listener2 when and where needed.
Also there are other ways, since the PropertyChangeSupport object has a getPropertyChangeListeners() that would allow removal of all listeners in a for loop if need be.
class A {
    final PropertyChangeSupport pcs = new PropertyChangeSupport(this);

    void addPropertyChangeListener(String name, PropertyChangeListener listener) {
        pcs.addPropertyChangeListener(name, listener);
    }

    void removePropertyChangeListener(String name, PropertyChangeListener listener) {
        pcs.removePropertyChangeListener(name, listener);
    }

    public void removeAllListeners() {
        for (PropertyChangeListener l : pcs.getPropertyChangeListeners()) {
            pcs.removePropertyChangeListener(l);
        }
    }
}

A: You can declare your listeners as follows:
private final PropertyChangeListener myProperty1Listener = this::doSomething;
private final PropertyChangeListener myProperty2Listener = e -> doSomethingElse());

then, you can add your listeners:
// using method reference
a.addPropertyChangeListener( "Property1", myProperty1Listener );
// using lambda expression
a.addPropertyChangeListener( "Property2", myProperty2Listener );

and you can remove them:
a.removePropertyChangeListener( "Property1", myProperty1Listener );
a.removePropertyChangeListener( "Property2", myProperty2Listener );


Q: Can a form be invoked on a click event in AngularJS ? I am creating a project to put into practice what I have learned about AngularJS. I created a form, which uses a controller. In the form, I have a button to save the information filled in by the user. After the information is save into the database I would like to call a second form to continue, (this form has its own controller) etc. How can I do that ?

A: You can use ng-submit for this:
<form ng-submit="goToNextForm()">
    <input type="text" ng-model="email">
    <button type="submit" value="submit">
</form>

And in controller:
$scope.goToNextForm = function(){

   //code to save data and move to next controller/form here

}

A: If you're not navigating to a different view, you probably dont need another controller. You can show and hide forms conditionally with ng-if. Ie. say first form is done, you've posted it to the database. You can do something like this
$scope.form = 1

<form id="form1" ng-if="form === 1">
//your form html
</form>

<form id="form2" ng-if="form === 2">
//your form html
</form>

then when form1 is submitted, you can do
$scope.form = 2

in your controller to hide the first form and render the second one
If you're set on the different forms having different controllers, you can do something like this
<div controller="mainCtrl">

<form controller="form1Ctrl" id="form1" ng-if="form === 1">
    //your form html
    </form>

    <form controller="form2Ctrl" id="form2" ng-if="form === 2">
    //your form html
    </form>
</div>

You would set the form variable from the mainCtrl's scope


Q: How to make Start-Process with Run as administrator should wait till finish i am having a code shown below. When i execute this code i want start-Process should wait. Once it is executed i will be accessing th exit code through $process. But here it is not working properly.
$process=Start-Process  powershell -Verb runAs "$exePath ${args} "  #Run as administrator
 Write-Output "hello world"
 Write-Output $process.exitCode


Q: How do I dynamically label my ggplot within a for loop? I want the title of each of my plots to be labeled by the contents of my list: "namesvector" instead of just "Scatterplot"
Also bonus question, par(mfrow = c(2,2)) isnt printing all 4 plots side by side, but individually.
 par(mfrow = c(2, 2))
namesvector <- list("Start", "Week_1", "Week_3", "Week_5")
for (i in 4:ncol(data_3)) {
  print(
    ggplot(data_3, aes(
      y = data_3[, i], x = Biomass, color = Tissue
    )) +
      geom_point() + geom_smooth(method = "lm") +
      labs(title = "Scatterplot", x = "Biomass", y = "Isotopic Signature")
  )
}

A: For printing a variable into your title, you need to use paste(), as explained here:
Inserting function variable into graph title in R
Does this help you?


Q: Spring Session JDBC - How to catch when the session is destroyed? Since Spring Session JDBC implementation does not support publishing of session events, how can I catch when the session is destroyed? I need to perform some additional logic when user's session has ended, but I couldn't find any other workaround. In the Spring Session docs there isn't any other solution presented.


Q: How to prevent saving Excel workbook unless a command button is clicked? I have a command button to save an Excel workbook in a particular format.
I want that the users are unable to save the workbook unless they click that command button.
To prevent the use of traditional saving options I used the code below:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    MsgBox "You can't save this workbook!"
    Cancel = True
End Sub

How do I prevent traditional saving options but allow saving if the command button is clicked?

A: You can have a boolean flag to indicate whether or not saving is allowed and only set it to true when you call the macro that contains your logic for saving the workbook.
Add the following code under ThisWorkbook:
Public AllowSave As Boolean

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    If Not AllowSave Then
        MsgBox "You can't save this workbook!"
        Cancel = True
    End If
End Sub

Public Sub CustomSave()
    ThisWorkbook.AllowSave = True

    ' TODO: Add the custom save logic
    ThisWorkbook.SaveAs '....

    MsgBox "The workbook has been saved successfully.", , "Workbook saved"
    ThisWorkbook.AllowSave = False
End Sub

Note that you'll need to assign the CustomSave macro to the button that will be initiating the custom save.
Demo:


Q: TP4056 module parallel output this is my first time asked on stack exchange, please bear bare with me.
Anyway, I created portable monitor using multiple TP4056 as battery charger & protection circuit. But I'm not sure it's safe or not.
this is the wiring diagram :

why I wired this way? Apparently the monitor needs more than 5 Watt, and using 1 TP4056 can't give enough power. (the monitor needs 12 volt). So far my solution works, but I worried about the safety.
what I'm asking is this solution safe?
Thank you
edit 2:
To power up 12 volt monitor, I stepped up the output from TP 4056 (from around 3-4 volt) using XL6009 module to 12 volt. As you can see, the module located under the batteries.

A: The cutoff voltage is a trade-off between maximum current capability and battery under-voltage protection, at high currents (which is your case)  the battery voltage can drop down to 2.5V even the battery is not over-discharged but this wasn't your question
There is nothing that forbids you to use this configuration, I actually used-it for a two batteries / two  TP4056 configuration.


Q: "Automatic is not a valid StreamPoints specification" If I run
StreamPlot[{a, b}, {a, 0, 10}, {b, 0, a}]

the kernel hangs, and I have to restart it. I also get the error message

StreamPlot::strmpts: Automatic is not a valid StreamPoints specification.

If I try to manually specify StreamPoints, the kernel still hangs, and the error message changes: e.g., with StreamPoints -> 10, I get

StreamPlot::strmpts: 10 is not a valid StreamPoints specification.

(For the record, I'm using 10.4.1 for Microsoft Windows (64-bit)).
What's going on here? What does this message mean, and how can I fix it?

A: No idea why it doesn't work as in Plot3D[ a b , {a, 0, 10}, {b, 0, a}]...
Try RegionFunction
StreamPlot[{a, b}, {a, 0, 10}, {b, 0, 10},RegionFunction -> Function[{a, b}, b < a]]

A: StreamPlot is not designed to work with such domain specs.  It ought to give a better message though.  Actually it doesn't seem to validate the domain before sending it to the internal routines.  (Probably, it used a standard plot validation, but the internal routines assume the limits are numeric, i.e., that it's a rectangle.)
tr = Trace[
   StreamPlot[{a, b}, {a, 0, 10}, {b, 0, a}],
   _Visualization`VectorFields`VectorFieldsDump`StreamPointsParse,
   TraceInternal -> True];

StreamPlot::strmpts: Automatic is not a valid StreamPoints specification.

Cases[
 Flatten@tr,
 HoldForm[parse_Visualization`VectorFields`VectorFieldsDump`StreamPointsParse] :>
  parse]

StreamPlot::strmpts: Automatic is not a valid StreamPoints specification.

(*  {None}  *)

One can inspect StreamPointsParse and its subroutines with GeneralUtilities`PrintDefinitions, if one's curious.  It's fairly short code and easy to follow.


Q: why there is no element in the list even after populating the list? package collectionwaliclass;

import java.util.ArrayList;
import java.util.List;

public class ArraylistWaliClass {

    public static List<String> list= new ArrayList<>() ;
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //list= ;
    ArraylistWaliClass arraylistWaliClass= new ArraylistWaliClass();
                //adding the element to the existing list
                int counter=0;
                /*while(counter++<10)
                {
                    arraylistWaliClass.addElement("new element"+counter, list);
                }*/
                //traversing the list in the arryaList
                list.forEach((x)->
                {
                    System.out.println(x);

                System.out.println("uff");
                });

                //deleting the list from the arraylist

    }
    public void addElement(String string, List<String> list)
    {
        list.add(string);
    }

}

A: because of scope definition, you are just adding elements to the parameter
List<String> list

in
  public void addElement(String string, List<String> list)
    {
        list.add(string);
    }

A: It's working fine if you just un-comment the while loop:
Output:
new element1
new element2
new element3
new element4
new element5
new element6
new element7
new element8
new element9
new element10

Code:
package collectionwaliclass;

import java.util.ArrayList;
import java.util.List;

public class ArraylistWaliClass  {

    public static List<String> list= new ArrayList<>() ;
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //list= ;
        ArraylistWaliClass arraylistWaliClass= new ArraylistWaliClass();
        //adding the element to the existing list
        int counter=0;
        while(counter++<10)
        {
            arraylistWaliClass.addElement("new element"+counter, list);
        }
        //traversing the list in the arryaList
        list.forEach((x)->
        {
            System.out.println(x);
        });

        //deleting the list from the arraylist
    }

    public void addElement(String string, List<String> list)
    {
        list.add(string);
    }

}


Q: What are possible causes of systemd error "Failed to enqueue OnFailure= job: Resource deadlock avoided"? My systemd onFailure tasks failed to run, and I see this in the system journal:

: Failed to enqueue OnFailure= job: Resource deadlock avoided

What are possible causes that could trigger this message and prevent from my OnFailure= task from running?
I'm using systemd v229

A: What exactly happens here is: You trigger shutdown.target, systemd uses job mode 'replace-irreversibly' for it. The unit fails because this target conflicts with every other unit, and triggers a stop for them. Meanwhile, your unit must have failed, so it triggers OnFailure= unit. Now, by default, this too Conflicts= with shutdown.target, hence will trigger a stop for it. But, since job mode was replace-irreversibly, it cannot cancel that job and replace it, and systemd considers this is a conflicting transaction, hence it is aborted. manager_add_job fails, and this bus error is mapped to EDEADLK errno, so you see Resource deadlock avoided string.

A: This can case be triggered in a system configuration that is designed to boot up a system, run a single task and then shut off. The systemd service that also contains the failing OnFailure= task might also contain:
ExecStopPost=/usr/bin/sudo /sbin/poweroff

There is a deadlock in that to finish shutting down the unit the poweroff commands needs to run. But for the poweroff command to finish running, it needs to stop the unit.
Meanwhile, the OnFailure= job is trying run while this deadlock is occurring.
Ultimately, it seems the poweroff action soon "wins" the deadlock, also pre-empting the OnFailure= task from running.
An alternate solution on AWS is to set a CloudWatch alarm on the instance. The alarm will have the option to "Take Action: Shutdown" if the Max CPU on the instance is less than 1% CPU for 15 minutes.


Q: Mysql function adding unwanted decimals on addition I am creating a simple MySQL function for addition, the function works well for numbers with up to 10 decimal places, but when I pass A as 17.565714285714 and B as 22.8 I got 40.365714285714006 the function append 006 to the result, what could be a reason and how can I solve it.
Mysql version is 8.0.18
DELIMITER $$
CREATE DEFINER=`root`@`localhost`
FUNCTION `addition`(`A` DOUBLE, `B` DOUBLE)
RETURNS DOUBLE
NO SQL
BEGIN
 RETURN A + B;
END$$
DELIMITER ;


Q: Setting root and passing parameter using the same function in angular 2 I am building an Ionic2 app. On click, I am sending parameter and setting a new rootPage in the same function so I can display a different set of tabs on the destination page.
   viewProjects(item){
    this.navCtrl.push(ItemPage,{
       item: item
     });
    this.navCtrl.setRoot(Tabs2Page);
  }

Template:
<button  ion-item (click)="viewItem(item)"> Item </button></div>

If I don't send parameter on click, I can successfully go to the target page and new rootPage is set.
   viewProjects(item){
    this.navCtrl.push(ItemPage);
    this.navCtrl.setRoot(Tabs2Page);
  }

If I only send Parameter and not setRoot, It works I have access to the parameters that I need but new rootPage is not set so I don't have tabs on the page.
   viewProjects(item){
    this.navCtrl.push(ItemPage,{
       item: item
     });
  }

I'm getting the following error
Runtime Error
Error in ./ItemPage class ItemPage - caused by: Cannot read property 'name' of undefined

I need to be able to setRoot and be able to send parameters on click, any idea how I might be able to do that? Thanks a lot !


Q: Openstack Instances don't have access to internet I used landscape installer with MAAS. When I SSH into the Neutron node, I can ping out to the internet, but instances cannot.
ubuntu@nvcg:~$ ping google.com
PING google.com (216.58.223.14) 56(84) bytes of data.
From 10.10.0.1 icmp_seq=1 Destination Net Unreachable
From 10.10.0.1 icmp_seq=2 Destination Net Unreachable
From 10.10.0.1 icmp_seq=3 Destination Net Unreachable

/etc/network/interfaces in Instance:
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).
# The loopback network interface
auto lo
iface lo inet loopback

# Source interfaces
# Please check /etc/network/interfaces.d before changing this file
# as interfaces may have been defined in /etc/network/interfaces.d
# NOTE: the primary ethernet device is defined in
# /etc/network/interfaces.d/eth0
# See LP: #1262951
source /etc/network/interfaces.d/*.cfg
/etc/network/interfaces.d/eth0.cfg in Instance:

# The primary network interface
auto eth0
iface eth0 inet dhcp

IP route on Neutron node shows that default gateway is via my MAAS controller node:
ubuntu@blue-drop:~$ ip route
default via 10.1.1.100 dev juju-br0
10.0.3.0/24 dev lxcbr0  proto kernel  scope link  src 10.0.3.1
10.1.1.0/24 dev juju-br0  proto kernel  scope link  src 10.1.1.152

juju status neutron from the landscape LXC:
landscape@juju-machine-0-lxc-1:~$ juju status neutron-gateway
environment: "1"
machines:
  "0":
    agent-state: started
    agent-version: 1.25.6
    dns-name: blue-drop.maas
    instance-id: /MAAS/api/1.0/nodes/node-b76c3dca-5a50-11e6-8378-0cc47a2275d4/
    series: trusty
    hardware: arch=amd64 cpu-cores=24 mem=131072M tags=node-b76c3dca-5a50-11e6-8378-0cc47a2275d4
      availability-zone=default
    state-server-member-status: has-vote
services:
  landscape-client:
    charm: cs:trusty/landscape-client-14
    exposed: false
    service-status: {}
    relations:
      ceph-client:
      - ceph-mon
      container:
      - base-machine
      - ceilometer
      - ceph-mon
      - ceph-osd
      - ceph-radosgw
      - cinder
      - glance
      - glance-simplestreams-sync
      - keystone
      - mongodb
      - mysql
      - neutron-api
      - neutron-gateway
      - nova-cloud-controller
      - nova-compute-kvm
      - ntpmaster
      - openstack-dashboard
      - rabbitmq-server
    subordinate-to:
    - base-machine
    - ceilometer
    - ceph-mon
    - ceph-osd
    - ceph-radosgw
    - cinder
    - glance
    - glance-simplestreams-sync
    - keystone
    - mongodb
    - mysql
    - neutron-api
    - neutron-gateway
    - nova-cloud-controller
    - nova-compute-kvm
    - ntpmaster
    - openstack-dashboard
    - rabbitmq-server
  neutron-gateway:
    charm: cs:trusty/neutron-gateway-229
    can-upgrade-to: cs:trusty/neutron-gateway-230
    exposed: false
    service-status:
      current: active
      message: Unit is ready
      since: 21 Sep 2016 07:36:41Z
    relations:
      amqp:
      - rabbitmq-server
      cluster:
      - neutron-gateway
      juju-info:
      - landscape-client
      neutron-plugin-api:
      - neutron-api
      quantum-network-service:
      - nova-cloud-controller
    units:
      neutron-gateway/0:
        workload-status:
          current: active
          message: Unit is ready
          since: 21 Sep 2016 07:36:41Z
        agent-status:
          current: idle
          since: 21 Sep 2016 07:36:43Z
          version: 1.25.6
        agent-state: started
        agent-version: 1.25.6
        machine: "0"
        public-address: blue-drop.maas
        subordinates:
          landscape-client/3:
            workload-status:
              current: active
              message: System successfully registered
              since: 20 Sep 2016 07:25:58Z
            agent-status:
              current: idle
              since: 21 Sep 2016 07:36:45Z
              version: 1.25.6
            agent-state: started
            agent-version: 1.25.6
            upgrading-from: cs:trusty/landscape-client-14
            public-address: blue-drop.maas
networks:
  subnet-1:
    provider-id: subnet-1
    cidr: 172.26.0.0/22
  subnet-2:
    provider-id: subnet-2
    cidr: 10.1.1.0/24
  subnet-3:
    provider-id: subnet-3
    cidr: 192.168.122.0/24

ifconfig on the neutron node:
ubuntu@blue-drop:~$ ifconfig
eth0      Link encap:Ethernet  HWaddr 0c:c4:7a:22:89:9c
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:4940677 errors:0 dropped:0 overruns:0 frame:0
          TX packets:5279006 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:1477383852 (1.4 GB)  TX bytes:2890096642 (2.8 GB)
          Memory:c7120000-c7140000

eth1      Link encap:Ethernet  HWaddr 0c:c4:7a:22:89:9d
          inet6 addr: fe80::ec4:7aff:fe22:899d/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:56379 errors:0 dropped:0 overruns:0 frame:0
          TX packets:372 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:5587444 (5.5 MB)  TX bytes:45875 (45.8 KB)
          Memory:c7100000-c7120000

juju-br0  Link encap:Ethernet  HWaddr 0c:c4:7a:22:89:9c
          inet addr:10.1.1.152  Bcast:10.1.1.255  Mask:255.255.255.0
          inet6 addr: fe80::ec4:7aff:fe22:899c/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:1739573 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1605712 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:550485072 (550.4 MB)  TX bytes:1694052911 (1.6 GB)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:11853058 errors:0 dropped:0 overruns:0 frame:0
          TX packets:11853058 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:6184581194 (6.1 GB)  TX bytes:6184581194 (6.1 GB)

lxcbr0    Link encap:Ethernet  HWaddr 16:3e:90:08:e6:6e
          inet addr:10.0.3.1  Bcast:10.0.3.255  Mask:255.255.255.0
          inet6 addr: fe80::143e:90ff:fe08:e66e/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:8 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:0 (0.0 B)  TX bytes:648 (648.0 B)

tap17f944be-8c Link encap:Ethernet  HWaddr 06:15:a8:c7:72:43
          UP BROADCAST RUNNING MULTICAST  MTU:1458  Metric:1
          RX packets:8 errors:0 dropped:0 overruns:0 frame:0
          TX packets:3 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:648 (648.0 B)  TX bytes:262 (262.0 B)

tap2a05341c-57 Link encap:Ethernet  HWaddr da:ad:d8:d0:d5:32
          UP BROADCAST RUNNING MULTICAST  MTU:1458  Metric:1
          RX packets:485 errors:0 dropped:0 overruns:0 frame:0
          TX packets:568 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:61839 (61.8 KB)  TX bytes:65210 (65.2 KB)

tap9799d51d-3f Link encap:Ethernet  HWaddr ba:ee:51:bb:19:51
          UP BROADCAST RUNNING MULTICAST  MTU:1458  Metric:1
          RX packets:10 errors:0 dropped:0 overruns:0 frame:0
          TX packets:2 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:864 (864.0 B)  TX bytes:140 (140.0 B)

tapaf2b94ee-1b Link encap:Ethernet  HWaddr 1a:f7:3c:a1:57:a7
          UP BROADCAST RUNNING MULTICAST  MTU:1458  Metric:1
          RX packets:335 errors:0 dropped:0 overruns:0 frame:0
          TX packets:53150 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:43105 (43.1 KB)  TX bytes:5254767 (5.2 MB)

tapf4edb36f-89 Link encap:Ethernet  HWaddr 26:18:93:ef:8a:4c
          UP BROADCAST RUNNING MULTICAST  MTU:1458  Metric:1
          RX packets:13 errors:0 dropped:0 overruns:0 frame:0
          TX packets:47 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:1874 (1.8 KB)  TX bytes:7328 (7.3 KB)

tapf97a3cfd-7f Link encap:Ethernet  HWaddr 16:62:97:43:da:26
          UP BROADCAST RUNNING MULTICAST  MTU:1458  Metric:1
          RX packets:21 errors:0 dropped:0 overruns:0 frame:0
          TX packets:52862 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:1474 (1.4 KB)  TX bytes:5219352 (5.2 MB)

veth9GOBB0 Link encap:Ethernet  HWaddr fe:08:5b:e8:1e:2b
          inet6 addr: fe80::fc08:5bff:fee8:1e2b/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:469961 errors:0 dropped:0 overruns:0 frame:0
          TX packets:562703 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:95499097 (95.4 MB)  TX bytes:179705526 (179.7 MB)

vethQELJ2E Link encap:Ethernet  HWaddr fe:59:b7:41:18:3a
          inet6 addr: fe80::fc59:b7ff:fe41:183a/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:2349669 errors:0 dropped:0 overruns:0 frame:0
          TX packets:2490007 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:1100476551 (1.1 GB)  TX bytes:747480935 (747.4 MB)

Neutron Node's /etc/network/interfaces:
auto lo
iface lo inet loopback
    dns-nameservers 10.1.1.100
    dns-search maas
iface eth0 inet manual
auto juju-br0
iface juju-br0 inet static
    gateway 10.1.1.100
    address 10.1.1.152/24
    mtu 1500
    bridge_ports eth0
auto eth1
iface eth1 inet manual
    mtu 1500
source /etc/network/interfaces.d/*.cfg

A: This was found to be a gateway and CIDR misconfiguration at the OVS configuration step of the install.
Network was set as 172.26.0.0/24 when it should have been 172.26.1.0/22 and was therefore colliding with existing network.
Obtained admin credentials and did a subnet update and also noticed that the gateway for external network subnet was not set. Once this was set, instances received network connectivity.


Q: Should I lock a variable in one thread if I only need it's value in other threads, and why does it work if I don't? I am aware of this question, but I believe my concerns are very different.
I recently created an SDL application, using threading and OpenGL.  I have one thread running in a loop, which continually updates the state of the objects I draw to the screen.  The states are very simple, it is just a boolean array (when the array value is true, I draw it, when it is false, I don't).
Currently, I have no mutex lock on any of my variables and everything is working just fine.  Even if only half of the state array was updated between a draw, the framerate is much higher (or at least equal to) the update rate, so it would be acceptable to have a half-updated state.
Now, I initially started working on a similar idea to this on an embedded system using interrupts.  Every once in a while, an interrupt would trigger, update the state array, and the execution would continue.  Now that I'm on a multi-core desktop, and updating the array simultaneously, I'm wondering why nothing bad is happening, since I am technically reading and writing to the same memory location at the same time.

*

*Is it just by chance, or is there a reason there's no memory access violations happening?

*If it is acceptable for the state of the variable to change just before, during, or just after the value is used, should I bother using a mutex lock?

Thank you for your help.

Edit: Additional information - the array is created dynamically, but when it is created/deleted, I do use a mutex (I figured accessing deleted memory wouldn't be looked kindly upon :P).

A: In theory, it's completely invalid (undefined behavior) to access memory like this without some synchronization.
In practice, it's moderately safe as long as:

*

*Only one thread is writing and the others are all reading.

*You don't care if the readers don't see some of the changes made until sometime later (possibly much later than the actual time they're written.

*You don't care if the readers see out-of-order changes, i.e. they see some changes that were made later without seeing other changes that were made earlier.

Issues 2 and 3 are a non-issue on x86, but can occur on nearly every other real-world multi-core/SMP machine. You could mitigate them with some machine-specific asm (or compiler intrinsics) to insert memory barriers at appropriate points.

A: The boolean array elements are can be set/read with an atomic operation, there is not need for a mutex.  You need a mutex to protect a structure to make sure that it stays consistent.  Since your booleans are independent there is no problem.


Q: Authenticating passwords against an LDAP I am a bit confused as to where passwords are stored within an LDAP. Many applications, eg. AD, seem to store passwords to allow users to log onto apps or computers. However, AD is open and can usually be viewed by anyone. So, where is the password? Can I pull passwords out of an LDAP?

A: AD stroes the password in an attribute called unicodepwd. This is a one way hash. Even if you can view it,you can not retrieve the password. Also this attribute can not be viewed with regular ldap searches. You have to use ldapi interface to retrieve it. Which means you have to be on the local machine.


Q: predicate from js to objective C I had a .js file for my screenshot automation with Instruments.app where I was looking up a cell with the following predicate:
var classScheduleCell = classScheduleTableView.cells().firstWithPredicate("isEnabled == 1 && NONE staticTexts.value BEGINSWITH 'No classes'").withValueForKey(1, "isVisible");

I want to translate that predicate to an objective C UI test, as the ruby scripts I was using for the screenshots now uses UI testing instead of Instruments. Using the same predicate fails
XCUIElement *firstCell = [classScheduleTableView.cells elementMatchingPredicate:[NSPredicate predicateWithFormat:@"isEnabled == 1 && NONE staticTexts.value BEGINSWITH 'No classes'"]];

Looks like I can make the first part of the predicate work changing
isEnabled == 1

for
enabled == true

Any ideas on how to make the other part work?

A: I found a solution for this, though is not the most elegant. I couldn't find a way to make a predicate to work as the one I had in UI Automation, so I used a couple of for loops to check the value of the cell labels.
NSPredicate *enabledCellsPredicate = [NSPredicate predicateWithFormat:@"enabled == true "];
XCUIElementQuery *enabledCellsQuery = [classScheduleTableView.cells matchingPredicate:enabledCellsPredicate];
int cellCount = enabledCellsQuery.count;
for (int i = 0; i < cellCount; i++) {
    XCUIElement *cellElement = [enabledCellsQuery elementBoundByIndex:i];
    XCUIElementQuery *cellStaticTextsQuery = cellElement.staticTexts;
    int textCount = cellStaticTextsQuery.count;
    BOOL foundNoClasses = NO;
    for (int j = 0; j < textCount; j++) {
        XCUIElement *textElement = [cellStaticTextsQuery elementBoundByIndex:j];
        if (textElement.value && [textElement.value rangeOfString:NSLocalizedString(@"No classes", nil) options:NSCaseInsensitiveSearch].location != NSNotFound) {
            foundNoClasses = YES;
            break;
        }
    }
    if (foundNoClasses == NO) {
        [cellElement tap];
        break;
    }
}

Thanks @joe-masilotti for your help anyway.

A: I don't believe your exact predicate is possible with UI Testing.
UI Testings vs UI Automation
Matching predicates with UI Testing (UIT) behaves a little differently than UI Automation (UIA) did. UIA had more access to the actual UIKit elements. UIT is a more black-box approach, only being able to interact with elements via the accessibility APIs.
NOT Predicate
Breaking down your query I'm assuming the second part is trying to find the first cell not titled 'No classes'. First, let's just match staticTexts.
let predicate = NSPredicate(format: "NOT label BEGINSWITH 'No classes'")
let firstCell = app.staticTexts.elementMatchingPredicate(predicate)
XCTAssert(firstCell.exists)
firstCell.tap() // UI Testing Failure: Multiple matches found

As noted in the comment, trying to tap the "first" cell raises an exception. This is because there is more than one match for a text label that starts with "No classes".
NONE Predicate
Using the NONE operator of NSPredicate leads us down a different path.
let predicate = NSPredicate(format: "NONE label BEGINSWITH 'No classes'")
let firstCell = app.staticTexts.elementMatchingPredicate(predicate)
XCTAssert(firstCell.exists)// XCTAssertTrue failed: throwing "The left hand side for an ALL or ANY operator must be either an NSArray or an NSSet." -

This approach can't even find the cell. This is because the elementMatchingPredicate() expects the predict to return a single instance, not an array or set. I couldn't figure out how to make the query select the first element. And once you get an XCUIElement there are no ways to farther restrict it.
Different Approach
That said I suggest you take a slightly different approach for your test. If your tests are deterministic, and they should be, just tap the first known cell. This means you don't have to worry about ambiguous matchers nor chaining predicates.
let firstCell = app.staticTexts["Biology"]
XCTAssert(firstCell.exists)
firstCell.tap()


Q: Android TextView multiline has extra space Multiline TextViews with android:layout_width="wrap_content" automatically take up maximum space as if they become match_parent. Is there any way keep the true wrap_content behavior?
Example xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/rounded_bg"
        android:backgroundTint="@color/colorAccent"
        android:text="Example text"
        android:textAlignment="center"
        android:textColor="#fff"
        android:textSize="28sp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:background="@drawable/rounded_bg"
        android:backgroundTint="@color/colorAccent"
        android:text="Example text ================"
        android:textAlignment="center"
        android:textColor="#fff"
        android:textSize="28sp" />

    <TextView
        android:layout_width="270dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:background="@drawable/rounded_bg"
        android:backgroundTint="@color/colorAccent"
        android:text="Example text ================"
        android:textAlignment="center"
        android:textColor="#fff"
        android:textSize="28sp" />

</LinearLayout>

*

*Single line

*Multiline

*How I want it to look

I want to remove the extra space at the left and right ends of the multiline text. The effect can be done if I manually set the layout_width to some specific value like 270dp, but then it becomes arbitrary. I prefer to keep it as wrap_content.
EDIT:
The purpose of this is that I want to use a custom background, rounded bg that fits onto the text. I've edited the example xml and the images.

A: Try it programmatically in .java file without changing xml file
SpannableString s = new SpannableString("your content");
s.setSpan(new BackgroundColorSpan(getResources().getColor(R.color.colorAccent)), 0, s.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
text.setText(s);


Q: Time complexity analysis of search problem I was introduced to an example interview question, where given a 2D array of characters and a word, find the word in the array, where the next character of the word is either to the right or below the previous character, and return a list of the co-ordinates of each character found.
I wrote the following code to solve this:
co_ords = []

def init_recursion(word, grid):
    co_ords.clear()
    return find_word(word, grid, 0, 0, True, 0)

def find_word(word, grid, x, y, explore, pos):
    word_len = len(word) - pos
    if word_len == 0:
        return True

    x_size = len(grid[0])
    y_size = len(grid)

    if word_len > (x_size - x) + (y_size - y):
        return False

    try:
        char_on = grid[y][x]

        if word[pos] == char_on:
            co_ords.append((y, x))
            if find_word(word, grid, x + 1, y, False, pos + 1):
                return True
            elif find_word(word, grid, x, y + 1, False, pos + 1):
                return True
            else:
                co_ords.pop()
        if word_len - 1 > (x_size - x) + (y_size - y):
            return False
        if explore and find_word(word, grid, x + 1, y, True, 0):
            return True
        else:
            return explore and find_word(word, grid, x, y + 1, True, 0)
    except IndexError:
        return False

# Valid grid and word combinations:
grid1 = [
    ['c', 'c', 'x', 't', 'i', 'b'],
    ['c', 'c', 'a', 't', 'n', 'i'],
    ['a', 'c', 'n', 'n', 't', 't'],
    ['t', 'c', 's', 'i', 'p', 't'],
    ['a', 'o', 'o', 'o', 'a', 'o'],
    ['o', 'a', 'a', 'a', 'o', 'o'],
    ['k', 'a', 'i', 'c', 'k', 'i']
]
word1 = 'catnip' >>> [(1, 1), (1, 2), (1, 3), (2, 3), (3, 3), (3, 4)]
word2 = 'cccc' >>> [(0, 0), (0, 1), (1, 1), (2, 1)] (one choice of many)
word3 = 's' >>> [(3, 2)]
word4 = 'bit' >>> [(0, 5), (1, 5), (2, 5)]

My complexity analysis for this is as follows:
Where:

*

*R = number of rows

*C = number of columns

*W = characters in word

The find_word function will loop through the entire 2D grid RC - W2 times, and for each exploration call, could recuse up to Wlog(W) times attempting to find a match. There would therefore be a total of Wlog(W)(RC - W2) recursive calls at the worst case.
Hence my questions:

*

*One, have I got the complexity analysis of the above correct?

*Two, in big O notation (worst case time complexity), how would this be represented?
I think that it could be one of the following:

*

*O(RCW(log(W)) - W3)

*O(RCW(log(W)))
But I'm not sure which - normally the smaller term would be ignored in big O, however I'm not sure, as W is present in both the n3 and n3log(n) terms.

A: I disagree with your search depth being O(Wlog(W)). In the worst case, where every intermediate letter (except the last) matches the word, your recursion will have a branching factor of 2, and will explore 2^W paths. Take, as an example, an extremely large grid, filled entirely with As, and a sole B in the lower right corner, and a search word AAA...AB. You can see how that would explode exponentially (with respect to W).
You are correct too, in that you'd ignore the smaller term, so overall I think the time complexity should be O(RC*2^W).


Q: Show that S_n is a martingale. Let $\{X_n:n \geq 1\}$ be a sequence of random variables. Let $S_n = \sum_{i=1}^{n} (X_i-E(X_i|X_1,...,X_{i-1})).$ Show that {S_n} is a martingale.
This is what I have so far:
To show it's martingale then : $E(S_{n+1}|F_n)$
=$E(S_{n+1}|S_1,S_2,..,S_n) \rightarrow E(S_{n+1}|X_1,X_2,..,X_n) =$
$E(X_i -E(X_i|X_1,....,X_{i-1}))|X_1,X_2,...,X_n)$ =
$X_i-E(X_i|X_1,...,X_{i-1})|X_1,X_2,...,X_n)$.
Am I going in the right path?
So with the feedback of angryavian, something like this?
$X_i -X_{n+1}-E[X_{n+1}|X_1,...,X_n]$.?

A: You want to show $E[S_{n+1} \mid X_1,\ldots,X_n] = S_n$, or equivalently $E[S_{n+1} - S_n \mid X_1,\ldots,X_n]=0$.
Note that $S_{n+1} - S_n = X_{n+1} - E[X_{n+1} \mid X_1,\ldots,X_n]$ and plug this into the above expectation.


Q: Can't convert int pointer array to double pointer array in a function I have a function that is supposed to convert an int pointer array to a double pointer array. It looks like this:
double* intToDouble(int len , int*x){

    double* y;
    y =(double*)malloc(len*sizeof(double));
    for (int i=0; i<len ; i++){
        y[i]=(double)x[i];
    }
    return y;
}

However, when trying to use it, I get an array full of float 0's . I will also leave here my print array function in case it is relevant.
void printDoubleSignal(int len, double* x) {
    printf("%d: [", len);
    if (len > 0) {
        printf("%lf", x[0]);
        for (int i = 1; i < len; i++) printf(",%lf", x[i]);
    }
    printf("]\n");
}

This is the result that I get after trying to convert from int to float the array 10: [1,2,3,4,5,0,0,0,0,0]
10: [0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000]

EDIT
As requested, here is the rest of the code:
#include <stdio.h>
#include <stdlib.h>
#include <complex.h>
#include <math.h>

int* readSignal(int* len) {
    int* x;
    char c;
    scanf("%d:", len);
    x = calloc(*len, sizeof(int));
    do c = getchar(); while (c != '[');
    if (*len > 0) {
        scanf("%d", &x[0]);
        for (int i = 1; i < *len; i++) scanf(",%d", &x[i]);
    }
    do c = getchar(); while (c != ']');
    return x;
}

void printSignal(int len, int* x) {
    printf("%d: [", len);
    if (len > 0) {
        printf("%d", x[0]);
        for (int i = 1; i < len; i++) printf(",%d", x[i]);
    }
    printf("]\n");
}

void printDoubleSignal(int len, double* x) {
    printf("%d: [", len);
    if (len > 0) {
        printf("%lf", x[0]);
        for (int i = 1; i < len; i++) printf(",%lf", x[i]);
    }
    printf("]\n");
}

int* zeroPad(int len, int* x, int n){

    int i;
    x = (int*)realloc(x, sizeof(int) * n);
    for (i=len; i<n ; i++){
        x[i]=0;
    }
    return x;
}

double* intToDouble(int len , int* x){

    double *y;
    y =(double*)malloc(len*sizeof(double));
    for (int i=0; i<len ; i++){
        printf("x[%d]=%lf\n",i, x[i]);
        y[i]=x[i];
        printf("y[%d]=%lf\n",i, y[i]);
    }
    return y;
}

int main()
{
    int *x , len=5;
    double *y;
    x = readSignal(&len);
    printSignal(len,x);
    x = zeroPad(&len,x,10);
    printSignal(len,x);
    y = intToDouble(len,x);
    printDoubleSignal(len ,y);

    return 0;
}

EDIT 2
This is the exact text of the input/output (first line is input, the rest is output):
5:[1,2,3,4,5]
5: [1,2,3,4,5]
10: [1,2,3,4,5,0,0,0,0,0]
x[0]=-0.000000
y[0]=-0.000000
x[1]=-0.000000
y[1]=-0.000000
x[2]=-0.000000
y[2]=-0.000000
x[3]=-0.000000
y[3]=-0.000000
x[4]=-0.000000
y[4]=-0.000000
x[5]=-0.000000
y[5]=-0.000000
x[6]=-0.000000
y[6]=-0.000000
x[7]=-0.000000
y[7]=-0.000000
x[8]=-0.000000
y[8]=-0.000000
x[9]=-0.000000
y[9]=-0.000000
10: [0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000]

A: You forgot to receive the result of zeroPad. The function uses realloc(), so the passed pointer may be invalidated. The function returns the new pointer, so you have to assign that to x.
This means that the line in the main() function
    zeroPad(5,x,10);

should be
    x = zeroPad(5,x,10);