Compactness in $W^{1,p}_0(B_R)$

Question: I have a sequence of functions $\{u_k\}_k \in u + W^{1,p}_0(B_R, R^N)$, where $B_R \Subset \Omega $ is the ball of radius R and $\Omega \subset R^n$ open and bounded, $u \in W^{1,p}(B_R, R^N)$.
I want to understand why $\{ u_k - u\}_k$ admits a subsequence that converges weakly to a function $u_{\infty} - u.$
Maybe the set $ W^{1,p}_0(B_R, R^N) $ is weakly compact, but why?
Answer: The claim is false.
Let $u=0$ and let $v\in W_0^{1,p}(B_R,R^N)$ be a function with $\|v\|>0$.
Then define $u_k:=kv$.
Then it turns out that there is no weakly convergent subsequence of $\{u_k-u\}_k$
(this is because weakly convergent sequences must be bounded).
Comment: And if we suppose that $\{ u_k - u \}$ is bounded what happens?
Comment: @Fil Then we get a weakly convergent subsequence if the space is reflexive, which is the case for $p\in(1,\infty)$.
Comment: But  where does this result come from?
Comment: @Fil It is a consequence of the Banach-Alaoglu theorem, see here: https://en.wikipedia.org/wiki/Banach%E2%80%93Alaoglu_theorem#Consequences
Comment: Thank you so much!

Compactness in $W^{1,p}_0(B_R)$


Find div tag and replace with span

Question: I have React component that renders some HTML with
 tag. I want to use that component in
, but that occurs error
 cannot appear as a descendant of
.
Can I find that div and replace it with  tag?
What I need to find:

Comment: Can't you change the `` to a `` in the first place?
Comment: That component from big library, I couldn't find that code ((
Answer: You can't really replace an element type like that. Assuming you don't have direct access to this component, you could do some convoluted thing where you wrap the component in a div with a given ref, use that ref to select your element, save it's children, remove it, create a new element, etc, etc.
But you'll probably be much better off just not using a
 tag in this instance, or figuring out if you have any ability to modify those elements through whatever package youre using.

Find div tag and replace with span


If we know A is independent of B, why isn't P(A|B,C) = P(A|C) necessarily true?

Question: Let's say we know that A is independent of B, or mathematically:
$$P(A|B) = P(A)$$
Then how come we can't say the following is necessarily true:
$$P(A|B,C) = P(A|C)$$
If the outcome of B doesn't have an effect on the outcome of $A$, then why would the outcome of $B$ AND $C$ have an effect on $A$ that is different than the effect of the outcome of just $C$?
Is there perhaps a simple counterexample to illustrate this? For example, let's say $A$ and $B$ are the event of picking an ace of spades from a deck of cards (each has their own deck of cards).
Comment: In words: "For more than two events, pairwise independence does **not** imply mutual independence."
Answer: My favourite example is a chessboard: if you pick a point uniformly then the row, column, and colour are pairwise independent.
Suppose A is colour, B is row, and C is column. Then P(A="white"|B)=0.5 and P(A="white"|C)=0.5 for any value of B, but P(A="white"|B,C) is either 0 or 1 for any values of B and C.
Comment: In particular, applying this to a 2x2 chessboard results in the example where $A,B,C$ are all uniformly random bits, but correlated so that any pair is independent and the third is their XOR. (The example in guy's answer.)
Comment: Lovely example!
Answer: Imagine $A$ and $B$ are independent Bernoulli random variables with success probability 1/2, and let $C = AB + (1 - A)(1 - B)$ (if you like, $A$ is the event that a coin lands heads, $B$ is the event that another coin lands heads, and $C$ is the event that both coins land the same side up). Then $P(A = 1 \mid C = 1) = 1/2$ but $P(A = 1 \mid B = 1, C = 1) = 1$.
A bit more generally, a common situation where this is not true is when $(A, B, C)$ form a v-structure, i.e., where $A \rightarrow C \leftarrow B$, where $A$ and $B$ are marginally independent but where $B$ can provide information about $A$ if both cause $C$.
Answer: Let's continue your example with two decks of cards, supposing that one card is chosen randomly from each deck.
You have proposed that $A$ is the event that the ace of spades is chosen from the first deck and that $B$ is the event that the ace of spades is chosen from the second deck.
Now let $C$ be the event that the two cards from the two decks are of different colors. Then
$$P(A|C) = P(A) = 1/52$$
but
$$P(A|B,C) = 0$$
because $A$, $B$ and $C$ cannot simultaneously be true.
Note that any two of $A$, $B$ and $C$ are independent but the three events are dependent when taken together.
Comment: Hmm. The Ace of Spades is always a black card ...
Comment: That was witty. +1.
Answer: There are two situations how this can happen.
Collider bias
A common way how the situation can occur is collider bias.
An example is in the image below. In this example, intelligence and appearance are statistically unrelated (there's not even an effect in this case as with the coin example below). But conditional on the sum of intelligence and appearance the two become correlated.

Invariant effect
With collider bias both A and B have an effect on C. In some special cases, the situation may also appear when B has a causal effect on A, but it does not appear as a statistical dependency.
The underlying reason why this counterintuitive situation can happen is because: When we speak about statistical independence between A and B then it doesn't necessarily mean that A and B have no functional/causal relationship.
Let's say that we flip two fair coins $B$ and $C$, and assign values $-1$ and $1$ to the sides of the coins. Let's define $A := B \times C$.
<code> B   C   A := B*C
 1   1   1
 1  -1  -1
-1   1  -1
-1  -1   1
</code>
Now $B$ does influence the outcome $A$ but $A$ is not statistically dependent on $B$ alone. Namely we have that $P(A = 1) = P(A = -1) = 0.5$ independent of the value of $B$.
Variants of this case occur when $B$ is a variable that influences $A$ while leaving the distribution of $A$ unchanged. So this case happens when $B$ has an effect on $A$ that leaves the distribution of $A$ invariant. E.g. it happens when $B$ switches labels of a fair coin or dice.
This seems like a contrived case, but it is also a bit about a particular interpretation of probability. When we flip a coin, does it matter whether we start with heads up or tails up? Statistically speaking there might not be a relationship. But in the underlying physical process the starting position of the coin has (according to theory) an influence on the position of the coin after the flip. The situation may, after all, be considered deterministic; but we describe it as probabilistic because we have no complete knowledge about the begin state of the entire system and all the parameters that are involved in the outcome.
Comment: IIRC, there was another post where you mentioned about the collider bias, the first time I got acquainted with it. +1.
Comment: @User1865345 it might be the post from which I copied the image https://stats.stackexchange.com/a/579222/164061
Comment: Thanks for the answer! In the collider example, it would help to say with $A$, $B$, and $C$ are.
Comment: I like the idea of collider bias but I don't agree with your characterization of the second situation. I don't think it is correct to argue that "B does influence A" and "in some sense A is not independent of B" when in fact A and B are unambiguously mathematically independent. I don't accept the apparent implication that "statistical independence" is a flawed concept that misses some important type of dependence.
Comment: @GordonSmyth the second situation relates to the idea that 'dependence' can be an ambiguous term. On the one hand you have 'statistical dependence' on the other hand you have 'causal dependence'.  In the second example A := B*C is defined as a function of B and by definition dependent on B. All other things equal, B will change the value of A. I am not sure what there is to not accept. The example clearly shows a causal relationship, namely A := XOR(B,C), while A and B can be statistically independent if B and C are Bernoulli variables with p=0.5.
Comment: https://stats.stackexchange.com/questions/286741/is-there-an-example-of-two-causally-dependent-events-being-logically-probabilis
Comment: Discussing the possibility of a functional relationship between A and B that depends on an unobserved third variable is all to the good. In the relationship A = B*C, B is useful for predicting A if C is observed but useless if it is not. Great. Your answer would be improved if you could describe this situation in clear unambiguous terms without introducing new definitions for "dependence". Terms like "in some sense" or "clearly dependent" or "other things equal" or "causal dependence" confuse the issue IMO. There is only one definition of independence.
Comment: I really like this answer. This quote goes to the heart of the matter: "The underlying reason why this counterintuitive situation can happen is because: When we speak about statistical independence between A and B then it doesn't necessarily mean that A and B have no functional/causal relationship."
Answer: I quote Joseph Blitzstein's Introduction to Probability (2019 2 edn), p. 65.

Example 2.5.11 (Independence doesn't imply conditional independence).
My
friends Alice and Bob are the only two people who ever call me on the phone. Each
day, they decide independently whether to call me that day. Let A be the event
that Alice calls me next Friday and B be the event that Bob calls me next Friday.
Assume A and B are unconditionally independent with P(A) > 0 and P(B) > 0.
However, given that I receive exactly one call next Friday, A and B are no longer
independent: the call is from Alice if and only if it is not from Bob. In other words,
letting C be the event that I receive exactly one call next Friday, $P(B|C) > 0$ while
$P(B|A,C) = 0$, so A and B are not conditionally independent given C.
Answer: As @Sextus Empiricus (the ancient skeptic!) said, collider bias phenomenon in epidemiology is a great exemplar of why marginal independence of two random variables does not necessarily imply their conditional independence, given a third random variable.
Sackett (1978)'s example is a classic for the collider bias.  In his paper, $A =$ having locomotor disease, and $B = $ having respiratory disease. Let $C$ denote the event that a person is hospitalized (for whatever reason). He observed that among hospitalized patients, there was a strong association between $A$ and $B$, whereas there was no association between $A$ and $B$ in the overall population (mix of both $C$ and $\bar C$).  If $C$ denotes hospitalization, then we see that $P(A|B,C) \ne P(A|C)$ and $P(B|A,C) \ne P(B|C)$, even though $P(A|B) = P(B)$, this is because both $A$ and $B$ increase the probability of $C$.   Hospitalization, $C$, is the collider, being a common effect of $A$ and $B$.


Could not find a generator for route RouteSettings("todoscreen", Instance of 'ScreenArguments') in the _WidgetsAppState. FLUTTER

Question: Okay so the reason this error is weird is that it wasn't there till i added bluetooth functionality to my project. If i can't resolve this i might have to make my app from scratch an as a flutter beginner, it took me weeks to get this far. let me just describe my app: It is a health app paired with a wearable band. After login, the user is prompted to connect to a device and once they connect, HomeScreen() is returned which shows the temp and pulse data sent from arduino through bluetooth. For now,pulse is hardcoded but temp is sent from sensor to app, and updated to firestore then retrieved and displayed.
So the app has both a user and a caretaker interface.
here is main.dart
import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vitality/screens/btInitialize.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:vitality/screens/welcome.dart';
import 'package:vitality/components/route.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primaryColor: Color(0xff222831),
        accentColor: Color(0xff00adb5),
        textTheme: TextTheme(
          headline1: TextStyle(
              fontSize: 25.0, fontFamily: 'Montserrat', color: Colors.black),
          headline2: TextStyle(
              fontSize: 60.0, fontFamily: 'CrimsonText', color: Colors.black),
          headline3: TextStyle(
              fontSize: 30.0, fontFamily: 'Lora', color: Colors.white),
          headline4: TextStyle(
              fontSize: 30.0, fontFamily: 'Montserrat', color: Colors.white),
          headline5: TextStyle(
              fontSize: 85.0, fontFamily: 'Montserrat', color: Colors.black),
          headline6: TextStyle(
              fontSize: 20.0, fontFamily: 'Montserrat', color: Colors.white),
        ),
      ),
      initialRoute: Welcome.id,
      onGenerateRoute: RouteGen.generateRoute,
    );
  }
}

here is route.dart
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:vitality/screens/login.dart';
import 'package:vitality/screens/homescreen.dart';
import 'package:vitality/screens/chatbot.dart';
import 'package:vitality/screens/todo.dart';
import 'package:vitality/screens/welcome.dart';
import 'package:vitality/screens/register.dart';
import 'package:vitality/components/ScreenArguments.dart';
import 'package:vitality/screens/btInitialize.dart';
import 'package:vitality/components/HomeArguments.dart';

class RouteGen {
  static Route<dynamic> generateRoute(RouteSettings settings) {
    final args = settings.arguments;
    switch (settings.name) {
      case btInit.id:
        return MaterialPageRoute(builder: (BuildContext context) {
          final argument = args as ScreenArguments;
          return btInit(
            docid: argument.docid,
            isCaretaker: argument.isCaretaker,
          );
        });
      case Welcome.id:
        return MaterialPageRoute(builder: (_) => Welcome());
      case HomeScreen.id:
        return MaterialPageRoute(builder: (BuildContext context) {
          final argument = args as HomeArgs;
          return HomeScreen(
              docid: argument.docid,
              isCaretaker: argument.isCaretaker,
              currentDevice: argument.currentDevice);
        });
      case LoginScreen.id:
        return MaterialPageRoute(builder: (_) => LoginScreen());
      case Register.id:
        return MaterialPageRoute(builder: (_) => Register());
      case ChatBot.id:
        return MaterialPageRoute(builder: (BuildContext context) {
          final argument = args as ScreenArguments;
          return ChatBot(
            docid: argument.docid,
            isCaretaker: argument.isCaretaker,
          );
        });
      case Todo.id:
        return MaterialPageRoute(builder: (BuildContext context) {
          final argument = args as ScreenArguments;
          return Todo(
            docid: argument.docid,
            isCaretaker: argument.isCaretaker,
          );
        });
    }
  }
}

since i have to pass multiple arguments i have a screenarguments class to pass docid, and isCaregiver (bool) between screens. and the first homescreen needs a device parameters passed so just for home i made a different class.
Here theyy are
class ScreenArguments {
  final String docid;
  final bool isCaretaker;

  ScreenArguments({this.docid, this.isCaretaker});
}

import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';

class HomeArgs {
  final String docid;
  final bool isCaretaker;
  final BluetoothDevice currentDevice;

  HomeArgs({this.docid, this.isCaretaker, this.currentDevice});
}

WHen login button is pressed, this is the screen it goes to
btinitialize.dart
import 'package:flutter/material.dart';
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';
import 'package:vitality/screens/connection.dart';
import 'package:vitality/screens/homescreen.dart';

class btInit extends StatelessWidget {
  final String docid;
  final bool isCaretaker;
  static const String id = 'btinit';
  btInit({@required this.docid, @required this.isCaretaker});
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: FutureBuilder(
        future: FlutterBluetoothSerial.instance.requestEnable(),
        builder: (context, future) {
          if (future.connectionState == ConnectionState.waiting) {
            return Scaffold(
              body: Container(
                height: double.infinity,
                child: Center(
                  child: Icon(
                    Icons.bluetooth_disabled,
                    size: 200.0,
                    color: Colors.blue,
                  ),
                ),
              ),
            );
          } else if (future.connectionState == ConnectionState.done) {
            print('bluetooth turned on');
            // return MyHomePage(title: 'Flutter Demo Home Page');
            return Home(docid: docid, isCaretaker: isCaretaker);
          } else {
            return Home(docid: docid, isCaretaker: isCaretaker);
          }
        },
        // child: MyHomePage(title: 'Flutter Demo Home Page'),
      ),
    );
  }
}

class Home extends StatelessWidget {
  final String docid;
  final bool isCaretaker;
  Home({this.docid, this.isCaretaker});
  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(
          backgroundColor: Colors.transparent,
          toolbarHeight: 50.0,
          centerTitle: true,
          title: Text(
            'HEALTH TRACKER',
            style: Theme.of(context).textTheme.headline4,
          )),
      body: Container(
        decoration: BoxDecoration(
            image: DecorationImage(
          image: NetworkImage(
              'https://www.setaswall.com/wp-content/uploads/2017/06/Blur-Phone-Wallpaper-1080x2340-011-340x550.jpg'),
          fit: BoxFit.cover,
          colorFilter: new ColorFilter.mode(
              Colors.black.withOpacity(.7), BlendMode.dstATop),
        )),
        child: SelectBondedDevicePage(
          Upload: (device1) {
            BluetoothDevice device = device1;
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) {
                  return HomeScreen(
                    docid: docid,
                    isCaretaker: isCaretaker,
                    currentDevice: device,
                  );
                },
              ),
            );
          },
        ),
      ),
    ));
  }
}

First it asks user to turn on bluetooth. then it returns the class SELECTBONDEDDEVICEPAGE Which is the device and a button that when pressed, take you to home screen.

connection.dart
This page is the code to discover devices. Theres not much UI stuff here.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';

enum _DeviceAvailability {
  maybe,
  yes,
}

class _DeviceWithAvailability extends BluetoothDevice {
  BluetoothDevice device;
  _DeviceAvailability availability;
  int rssi;

  _DeviceWithAvailability(this.device, this.availability, [this.rssi]);
}

class SelectBondedDevicePage extends StatefulWidget {
  final bool checkAvailability;
  final Function Upload;
  final String docid;
  final bool isCaretaker;
  static const String id = 'connect';
  const SelectBondedDevicePage(
      {this.checkAvailability = true,
      this.Upload,
      this.docid,
      this.isCaretaker});

  @override
  _SelectBondedDevicePage createState() => new _SelectBondedDevicePage();
}

class _SelectBondedDevicePage extends State<SelectBondedDevicePage> {
  List<_DeviceWithAvailability> devices = List<_DeviceWithAvailability>();

  // Availability
  StreamSubscription<BluetoothDiscoveryResult> _discoveryStreamSubscription;
  bool _isDiscovering;

  _SelectBondedDevicePage();

  @override
  void initState() {
    super.initState();

    _isDiscovering = widget.checkAvailability;

    if (_isDiscovering) {
      _startDiscovery();
    }

    // Setup a list of the bonded devices
    FlutterBluetoothSerial.instance
        .getBondedDevices()
        .then((List<BluetoothDevice> bondedDevices) {
      setState(() {
        devices = bondedDevices
            .map(
              (device) => _DeviceWithAvailability(
                device,
                widget.checkAvailability
                    ? _DeviceAvailability.maybe
                    : _DeviceAvailability.yes,
              ),
            )
            .toList();
      });
    });
  }

  void _startDiscovery() {
    _discoveryStreamSubscription =
        FlutterBluetoothSerial.instance.startDiscovery().listen((r) {
      setState(() {
        Iterator i = devices.iterator;
        while (i.moveNext()) {
          var _device = i.current;
          if (_device.device == r.device) {
            _device.availability = _DeviceAvailability.yes;
            _device.rssi = r.rssi;
          }
        }
      });
    });

    _discoveryStreamSubscription.onDone(() {
      setState(() {
        _isDiscovering = false;
      });
    });
  }

  @override
  void dispose() {
    // Avoid memory leak (`setState` after dispose) and cancel discovery
    _discoveryStreamSubscription?.cancel();

    super.dispose();
  }

//build returns list of bletooth devices entries (name, and connect button) with an on tap method Upload()
  @override
  Widget build(BuildContext context) {
    List<BluetoothDeviceListEntry> list = devices
        .map(
          (_device) => BluetoothDeviceListEntry(
            device: _device.device,
            onTap: () {
              widget.Upload(_device.device);
            },
          ),
        )
        .toList();
    return ListView(
      children: list,
    );
  }
}

class BluetoothDeviceListEntry extends StatelessWidget {
  final Function onTap;
  final BluetoothDevice device;

  BluetoothDeviceListEntry({this.onTap, @required this.device});

  @override
  Widget build(BuildContext context) {
    return ListTile(
      onTap: onTap,
      leading: Icon(Icons.devices),
      title: Text(device.name ?? "Unknown device"),
      subtitle: Text(device.address.toString()),
      trailing: FlatButton(
        child: Text('Connect'),
        onPressed: onTap,
        color: Colors.transparent,
      ),
    );
  }
}

And finally, when the button is pressed, it goes to homescreen with parameters docid, isCaretaker, and hte device.

homescreen.dart
import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:typed_data';
import 'package:vitality/components/bottomAppBar.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:vitality/components/biom.dart';
import 'package:flutter_phone_direct_caller/flutter_phone_direct_caller.dart';
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';

class HomeScreen extends StatefulWidget {
  static const String id = 'home_screen';
  final String docid;
  final bool isCaretaker;
  final BluetoothDevice currentDevice;
  HomeScreen(
      {@required this.docid,
      @required this.isCaretaker,
      @required this.currentDevice});
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

_callNumber() async {
  const number = '8606535166'; //set the number here
  bool res = await FlutterPhoneDirectCaller.callNumber(number);
}

class _HomeScreenState extends State<HomeScreen> {
  final auth = FirebaseAuth.instance;
  var pulse;
  var temp;
  static final clientID = 0;
  BluetoothConnection connection;
  String _messageBuffer = '';
  bool isConnecting = true;
  bool get isConnected => connection != null && connection.isConnected;
  bool isDisconnecting = false;
  @override
  void initState() {
    super.initState();
    BluetoothConnection.toAddress(widget.currentDevice.address)
        .then((_connection) {
      print('Connected to the device');
      print('device is ${widget.currentDevice}');
      connection = _connection;
      setState(() {
        isConnecting = false;
        isDisconnecting = false;
      });
      connection.input.listen(_onDataReceived).onDone(() {
        if (isDisconnecting) {
          print('Disconnecting locally!');
        } else {
          print('Disconnected remotely!');
        }
        if (this.mounted) {
          setState(() {});
        }
      });
    }).catchError((error) {
      print('Cannot connect, exception occurred');
      print(error);
    });
  }

  @override
  void dispose() {
    // Avoid memory leak (`setState` after dispose) and disconnect
    if (isConnected) {
      isDisconnecting = true;
      connection.dispose();
      connection = null;
    }
    super.dispose();
  }

  void _onDataReceived(Uint8List data) {
    // Allocate buffer for parsed data
    int backspacesCounter = 0;
    data.forEach((byte) {
      if (byte == 8 || byte == 127) {
        backspacesCounter++;
      }
    });
    Uint8List buffer = Uint8List(data.length - backspacesCounter);
    int bufferIndex = buffer.length;

    // Apply backspace control character
    backspacesCounter = 0;
    for (int i = data.length - 1; i >= 0; i--) {
      if (data[i] == 8 || data[i] == 127) {
        backspacesCounter++;
      } else {
        if (backspacesCounter > 0) {
          backspacesCounter--;
        } else {
          buffer[--bufferIndex] = data[i];
        }
      }
    }

    // Create message if there is new line character
    String dataString = String.fromCharCodes(buffer);
    print('$dataString');
    changePulse(int.parse(dataString));
    int index = buffer.indexOf(13);
    if (~index != 0) {
      setState(() {
        _messageBuffer = dataString.substring(index);
        //print('In message buffer is $_messageBuffer');
      });
    } else {
      _messageBuffer = (backspacesCounter > 0
          ? _messageBuffer.substring(
              0, _messageBuffer.length - backspacesCounter)
          : _messageBuffer + dataString);
    }
  }

  void _sendMessage(String text) async {
    text = text.trim();
    if (text.length > 0) {
      try {
        connection.output.add(utf8.encode(text + "\r\n"));
        await connection.output.allSent;
      } catch (e) {
        // Ignore error, but notify state
        setState(() {});
      }
    }
  }

  changePulse(int dataString) {
    main
        .doc(widget.docid)
        .update({'pulse': dataString})
        .then((value) => print("User Updated"))
        .catchError((error) => print("Failed to update user: $error"));
  }

  @override
  Widget build(BuildContext context) {
    print(
        'in homescreen each iis ${widget.docid}, ${widget.isCaretaker},${widget.currentDevice}');
    _sendMessage('1');
    print('got here');
    CollectionReference main = FirebaseFirestore.instance.collection('maindb');
    return Scaffold(
      extendBodyBehindAppBar: true,
      backgroundColor: Colors.white,
      appBar: AppBar(
          backgroundColor: Colors.transparent,
          toolbarHeight: 50.0,
          centerTitle: true,
          title: Text(
            'HEALTH TRACKER',
            style: Theme.of(context).textTheme.headline4,
          )),
      body: Container(
        decoration: BoxDecoration(
            image: DecorationImage(
          image: NetworkImage(
              'https://www.setaswall.com/wp-content/uploads/2017/06/Blur-Phone-Wallpaper-1080x2340-011-340x550.jpg'),
          fit: BoxFit.cover,
          colorFilter: new ColorFilter.mode(
              Colors.black.withOpacity(.7), BlendMode.dstATop),
        )),
        child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              SizedBox(height: 100.0),
              Text(widget.docid),
              Text({widget.isCaretaker}.toString()),
              biom(which: 'pulse', image: 'pulse', docid: widget.docid),
              RoundBorderText(text: 'PULSE'),
              biom(which: 'temperature', image: 'temper', docid: widget.docid),
              RoundBorderText(text: 'TEMPERATURE'),
              SizedBox(height: 30.0),
              FlatButton(
                  child: Text('test call'),
                  onPressed: () async {
                    _callNumber();
                  })
            ]),
      ),
      **bottomNavigationBar**: Container(
          decoration: BoxDecoration(
              image: DecorationImage(
            image: NetworkImage(
                'https://www.setaswall.com/wp-content/uploads/2017/06/Blur-Phone-Wallpaper-1080x2340-011-340x550.jpg'),
            fit: BoxFit.cover,
            colorFilter: new ColorFilter.mode(
                Colors.black.withOpacity(1), BlendMode.dstATop),
          )),
          child: bottomAppBar()),
    );
  }
}

class RoundBorderText extends StatelessWidget {
  final String text;
  RoundBorderText({this.text});
  @override
  Widget build(BuildContext context) {
    return Container(
        padding: const EdgeInsets.only(
            left: 40.0, right: 40.0, top: 8.0, bottom: 8.0),
        decoration: BoxDecoration(
            // ),
            borderRadius: BorderRadius.all(Radius.circular(20))),
        child: Text(text, style: Theme.of(context).textTheme.headline1));
  }
}

basically when it receives data from arduino it adds it to firestore nd displays it on screen also.
at the bottom is a bottomappbar which i extracted to a class.
THE PROBLEM IS HERE.
import 'package:flutter/material.dart';
import 'package:vitality/screens/login.dart';
import 'package:vitality/components/ScreenArguments.dart';
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';

class bottomAppBar extends StatefulWidget {
  final String id;
  bottomAppBar({this.id});
  @override
  _bottomAppBarState createState() => _bottomAppBarState();
}

class _bottomAppBarState extends State<bottomAppBar> {
  @override
  Widget build(BuildContext context) {
    print('id in bottom is ${widget.id}');
    return BottomAppBar(
      color: Colors.transparent,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          IconButton(
              icon: Icon(Icons.list),
              color: Colors.white,
              onPressed: () {
                print('to do pressed');
                print(docid);
                print(isCaretaker.toString());
                Navigator.of(context).pushNamed('todoscreen',
                    arguments: ScreenArguments(
                        docid: docid, isCaretaker: isCaretaker));
              }),
          IconButton(
              icon: Icon(Icons.data_usage),
              color: Colors.white,
              onPressed: () {
                Navigator.of(context).pushNamed('home_screen',
                    arguments: ScreenArguments(
                        docid: widget.id, isCaretaker: isCaretaker));
              }),
          IconButton(
              icon: Icon(Icons.chat),
              color: Colors.white,
              onPressed: () {
                Navigator.of(context).pushNamed('chat_screen',
                    arguments: ScreenArguments(
                        docid: widget.id, isCaretaker: isCaretaker));
              }),
        ],
      ),
    );
  }
}

The bottom bar consists of 3 icons, a reminder icon, homescreen one and chatbot one. We are currently in homescreen but when the todo icon is pressed, it should go to the screen for that. This worked before i put it the bluetooth code but now i get this error:
Could not find a generator for route RouteSettings("chat_screen", Instance of 'ScreenArguments') in the _WidgetsAppState.
for both the todo screen and chat screen.
here todo.dart code just so u can see it's initialized with necessary parameters
bool temp;
var todoid;
int number = 0;
final auth = FirebaseAuth.instance;
Stream collectionStream =
    FirebaseFirestore.instance.collection('todo').snapshots();
CollectionReference main = FirebaseFirestore.instance.collection('maindb');
CollectionReference todo = FirebaseFirestore.instance.collection('todo');
final myController = TextEditingController();

class Todo extends StatefulWidget {
  final String docid;
  final bool isCaretaker;
  Todo({this.docid, this.isCaretaker});
  @override
  _TodoState createState() => _TodoState();
  static const String id = 'todoscreen';
}

any help would be greatly appreciated as i am completely lost on what went wrong. (the bluetooth code is working)
Answer: While using Navigator.of(context), Flutter goes through the ancestors in the widget tree to find the nearest Navigator.
Now, you actually don't spcifically provide any Navigator widget in the tree, so where is your Navigator coming from ?
That's the MaterialApp.
Now, you have your main MaterialApp at the root.
But if you check your btInit widget, you have declared another MaterialApp in it. So when you call, pushNamed('todoscreen'), it is actually getting a hold of the Navigator from the MaterialApp of your btInit widget and not the main one.
Since, you only defined onGenerateRoute on the main MaterialApp, it is unable to resolve a request for the todoscreen route name.
Remove the MaterialApp inside your btInit widget and this should be resolved.
Comment: Wow, i can't believe i spent hours trying to solve this and all it took was me changing 2 words. Thank you so much!! I cannot express how indebted i am..i was going to remake this from scratch :)
Comment: Haha. Hey, it happens.


compute out an equation of complex integral of polynomial

Question: Let $f(z)=\sum_{k=0}^na_kz^k$ be a polynomial with coefficients in $\mathbb{C}$. Suppose $\deg f\geq 1$. Prove for any $R>0$,
\begin{equation*}
\frac{1}{2\pi i}\int_{|z|=R}z^{n-1}|f(z)|^2dz=a_0\bar{a_n}R^{2n}.
\end{equation*}
How to compute out this equation?
Comment: Note that $|z|=R$ can be parametrized as $z = R e^{i\theta}$ for $0\le\theta\le2\pi$
Answer: Here is how you advance
$$ \frac{1}{2\pi i}\int_{|z|=R}z^{n-1}|f(z)|^2dz = \frac{1}{2\pi i}\sum_{k=0}^n a_k\sum_{k=0}^n \overline a_k \int_{|z|=R}z^{n-1} z^k {(\overline z)}^k \,dz .$$
Now, let $z=Re^{i\theta}$ and try to finish the problem. See related technique.
Note: We used the fact

$$ |f(z)|^2 = f(z) \overline {f(z)}. $$


Condition of Convergence for the following Integral, evaluated using Gamma Function.

Question: Question:
Evaluate in terms of the Gamma function the integral $$\int_{0}^{\infty}\frac{x^k}{k^x}  dx$$
And state the condition on $k$ such that the integral converges.
Attempt
Let $$I = \int_{0}^{\infty}\frac{x^k}{k^x}dx = \int_{0}^{\infty}e^{-x\ln(k)}\cdot x^k dx$$
So $k>0$ and $k$ can not be negative.
Let $y = x\cdot\ln(k)$.
After simplification and using the gamma function:
$$I = \frac{1}{(\ln k)^{(k+1)}}\cdot\int_{0}^{\infty} e^{-y}\cdot y^k dy$$
$$ I = \frac{\Gamma(k+1)}{(\ln k)^{(k+1)}}$$
Now how to find the condition for the integral to converge, without graphing the function?
I thought it is $k>0$, but graphing the function shows that it diverges except when $k>1$
Comment: If $0<k<1$, then $1/k^x=(1/k)^x$ grows exponentially. Thus, the integral cannot converge. The case $k=1$ is also obvious. Your change of variables is incorrect if $0<k\le 1$ since then $\ln(k)\le 0$, which changes the range of integration (or for $k=1$ is useless).
Comment: Ohh I see. Thanks @Gary
Answer: $I=\int_0^\infty \frac{x^k}{k^x}dx=\int_0^\infty e^{-x\ln k}\cdot x^k dx$
$\pi(k) = \int_0^\infty x^ke^{-x}dx$
$I=\frac{1}{(\ln k)^{k+1}}\int_0^\infty (x \cdot \ln k)^k\cdot e^{-x\ln k}\cdot \ln k \cdot dx $
$u=x \ln k. du =dx \ln k$
$I=\frac{1}{(\ln k)^{k+1}}\int_0^\infty u^ke^{-u} du=\frac{\pi(k)}{(\ln k )^{k+1}}$
$\Gamma{(k+1)}=\pi(k)$

To prove divergence, you can use a comparison test.
$I=\int_0^\infty e^{-x\ln k}\cdot x^k dx$
$k$ must be greater than zero because of the domain of natural log. If $k\ge 1$, we have the case addressed above.
Consider $0<k<1. \implies\ln k <0$.
$I=\int_0^1 e^{-x\ln k}\cdot x^k dx+\int_1^\infty e^{-x\ln k}\cdot x^k dx>\int_0^1 e^{-x\ln k}\cdot x^k dx+\int_1^\infty e^{-x\ln k}dx=\int_0^1 e^{-x\ln k}\cdot x^k dx+\infty$
The first part of the integral is bounded, the second part, on the interval from 1 to $\infty$ diverges. Since I is greater than the unbounded part, it must diverge.


Transactions não funciona em criações/modificações de estruturas?

Question: Estava procurando na internet se havia alguma maneira de executar Transactions para operações do tipo ALTER TABLE ou CREATE TABLE no Mysql. Isso porque em um sistema nosso, usamos Migrations e queria que, se alguma coisa desse errado na criação da tabela, as alterações tivessem um rollback.
Acabei descobrindo que não é possível fazer isso em Mysql.
Vi isso nessa Resposta do SOEN.
(Se alguém puder traduzir, ficarem grato, mas deu pra entender mais ou menos).

Some statements cannot be rolled back. In general, these include data definition language (DDL) statements, such as those that create or drop databases, those that create, drop, or alter tables or stored routines.

Mas daí ficaram algumas dúvidas :

Sabendo que não são todos os Statments que suportam Rollback, quais são eles que sempre são aceitos?
Por que existe essa limitação quanto as alterações estruturais das tabelas?
Answer: Conforme a documentação do MySQL fala, no geral comandos de DDL(create, alter, drop, trucante) não são suportados dentro de transações, pois a sua execução causa um commit de forma implicita ou seja uma vez executada a instrução sua aplicação é feita no banco na hora em caso de sucesso.
Normalmente o conceito de transação é aplicado a manipulação(fazer/desfazer) dos dados, alguns bancos permitem algumas DDL em trasanções conforme essa resposta.


nice, ionice are not enough

Question: I have a script that starts big, CPU and memory consuming tree of processes. There is Python and executables down there, but everything starts with single bash script and python subprocesses.
During the execution, rest of system is completely chocked down. I attempted to do mitigate by
$ nice -n10 ionice -c2 ./Script.sh, however this is not sufficient - using computer is very laggy
(acutally this is development desktop, but the problem on designated server will be the same analogous).
I suspect, that the problem is with processes using to much memory - everything ends up swapped out and becomes sluggish.
Is there a way to lower priority of a process (and its recursive children)  in access to physial memory?
I prefer it to be done slower in background with limited influence on other tasks.
Comment: Once you're out of memory and start swapping, it's game over. Optimize your program or buy enough memory.
Comment: Yes, that's true. But I wish it could be game over for one process (process-tree), not for the rest of the system.
Comment: Memory is cheap these days
Answer: You cannot limit "pace" of consuming memory, but you can limit it's total memory usage via various different mechanisms.
1) security limits
Limit memory usage for user running the process via /etc/security/limits.conf. This may not work in your case if you are running this process as the same user working on different stuff.
Example:
username hard as 1000000

2) Control Groups
You can - with cgroups, create a group and also limit the memory usage. Just create cgroup, like this:
# cat >> /etc/cgconfig.conf << EOF
group memlimit {
    memory {
        memory.limit_in_bytes = 1073741824;
    }
}
EOF

# cat >> /etc/cgrules.conf <<EOF
username memory   memlimit/
EOF

Offcourse - in both cases, you have to develop your program so that it can recover from failing to allocate more memory.
In case it can't, you just need to add more memory to your system, so that you can avoid swapping. Once the swapping starts, its in the hands of kernel, and you can't - for example - lower the priority of kswapd, and even if you could - that doesn't guarantee some of the programs you use wouldn't still get swapped out, thus causing even more slower system response. Just don't go there.
Comment: Thanks. I searched more on cgroup rules and ended up with:
`nice -n 10 ionice -c2 -n7 cgexec -g memory:memlimit ./Script.sh`
Answer: While the next will not help you on memory swapping, it should help you on IO impact of your process.
It seems that you should explicit set the level as well.
ionice -c2 -n5 ./slowscript.sh

C2 alone might not be enough, depending on your kernel.
Qoute from the manpage (man ionice)
          Note that before kernel 2.6.26 a process that has not asked for an I/O priority formally uses "none" as scheduling class, but the I/O scheduler will  treat  such
          processes  as if it were in the best-effort class.  The priority within the best-effort class will be dynamically derived from the CPU nice level of the process:
          io_priority = (cpu_nice + 20) / 5.

          For kernels after 2.6.26 with the CFQ I/O scheduler, a process that has not asked for an I/O priority inherits its CPU scheduling class.   The  I/O  priority  is
          derived from the CPU nice level of the process (same as before kernel 2.6.26).

Basically: every newly started process will get C2 N4 , so when you want to have the IO reduced to as low as possible, either go on idle only (C3) or C2 N7.
Comment: I have recent kernel and usually combined ionice with nice -n10 or -n15, so io_priority by default was 6 or 7.
Thank You none the less.
Comment: @MateuszL If your system is memory constrained and bottle-necking on swap though, I have found that `ionice -c 3` is a lifesaver. Yeah, the process will just wait for everything else to finish, but assuming your swap partition and the used filesystem partition(s) are on the same physical device or just same bus to the CPU/RAM, you can really make a difference even in situations where swapping is the bottleneck.
Comment: @MateuszL In particular, I'm talking running full from-source compiles of large projects like GCC and node.js, on a single-core 600MHz ARMv7l chip with 256 MiB RAM. Swapping + IO happens over the same slow bus to the same eMMC chip, and it's _the_ bottleneck. Running builds with `ionice -c 3` (even before throwing in a `nice`) turned the builds from grinding the device into a basically unusable state (up to a worst-case of automatic reboot from watchdog not being pinged often enough), into the device basically remaining casually usable through-out the build.

nice, ionice are not enough


Angular io: Adding multiple lines in placeholder

Question: I am having trouble adding multi-lines within a placeholder in a textarea. I have already tried \r\n and \n.
Here is the input:
    <textarea #textAreaRef name="list" placeholder="[BE#] \n[OSuffix] \r\n [suggestedQuarter]" name="inputText"
 [className]="errorMessages.length>0 ? 'text-area in-valid' :'text-area valid'" [ngModel]="inputText" (ngModelChange)="onInputChange($event)"
 (scroll)="onScroll($event)"></textarea>

Answer: Try to add your placeholder value like this [placeholder] if you are getting data from your properties - this might understand the data has a string and reads your encoding, moves it to your next line i hope so - if not use html encoding for binding break - if that too doesn't work use attr binding for your placeholder
I think anyone of the above works - happy coding !!
[Can you have multiline HTML5 placeholder text in a <textarea>? check this for further update
Comment: Good !! Happy coding !


Como colocar vários números em uma var

Question: var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var lines = input.split('\n');

var i, p;

console.log(a);
p = 0;

{
    for(i = 1; i <= 6; i = i + 1);

    if(x > 0.0){
        p = p + 1;
    }
    console.log(p + ' valores positivos');
}

Tenho que usar este código para ler 6 números (lines[0] ate lines[5]) e mostrar quantos são positivos, porem não sei como criar uma var que leia todas as linhas como números, tentei usar var x = [lines[0], lines[1], ..., lines[5]]; Porem lê como string e não consigo usar x.split(","); Como eu devo fazer?
Input padrão:
7;
-5;
6;
-3.4;
4.6;
12;
Answer: Tente o seguinte script:
var p = 0;
var lines = input.split(";")

for(var i = 0; i < 6; i++){
    if(parseFloat(lines[i]) > 0.0){
         p = p + 1;
    }
}
 console.log(p + ' valores positivos');

Answer: Tenta usar o "filter" com "Math.sign"
var positivos = [7, -5, 6, -3.4, 4.6, 12].filter(x => Math.sign(x) == 0 || Math.sign(x) == 1);
    // positivos fica sendo [7, 6, 4.6, 12]

filter
Math.sign

Como colocar vários números em uma var


Using fseek() To Update a Binary File

Question: I have looked and looked online for help on using fseek() efficiently, but no matter what I do, I am still not receiving the right results. Basically I am reading from a file of animals that have an "age" parameter. If the age is -1, then upon adding to this binary file, I should use fseek() to find the first -1 in the file and overwriting that entire line with new information that the user inputs. I have an array that traverses and finds all of the holes at the beginning of the file, and it is working correctly. My issue is that it is updating the new animal and putting each one in the next empty slot with age -1, but when I go to refresh my file, all of the animals are appended to the end, even though their id's are the id's of the once empty slots. Here is my code:
void addingAnimal(FILE *file, struct animal ani, int * availableHoles) {
    int i;
    int offset = ((sizeof(int) + sizeof(ani)) * ani.id -1);
    if (availableHoles[0] != 0) {
        fseek(file, offset, SEEK_SET);
        ani.id = availableHoles[0];
        fwrite & ani, sizeof(ani), 1, file);
        for (i = 0; i < sizeof(availableHoles) -1; i++) {
            availableHoles[i] = avialablesHoles[i+1];
        }
}

The very beginning of the file has an integer that tells us the number of holes within the file, so the offset is removing that, so once I print it, it prints everything correctly. Then I check if there are holes in the helper array I created, if there are, then I want the animal's id to be that id and I am trying to seek to the line with the first -1 age to put my updated animal's information there, and then writing it to the file. The last for-loop is just me shifting up the available holes. Oh and as for opening the file, I am using r+b for reading and writing. Thank you in advance!
Comment: Should `ani.id -1` be in parentheses?
Comment: Okay then, could you make a [mcve]?
Comment: I'm sorry, I don't know what that is..
Comment: @user3376654 Click on the link to find out.
Comment: How did you open the file? What arguments did you pass to `fopen()`? It seems like the file was opened in append mode.
Comment: I stated in the next to last sentence I used "r+b" which I read is the most appropriate way to open when modifying the file the way I am intending.
Comment: That's a possibility that I am calculating my offset wrong.
Comment: that last for() loop in the posted code will shift the data to an earlier entry in the availableholes array, But is fails to 'clear' the last entry, so now there will be 2 duplicate entries, then 3 duplicate entries,  Only more duplicate entry for each time that posted code is called
Comment: I suspect this line: `int offset = ((sizeof(int) + sizeof(ani)) * ani.id -1);` should be: `int offset = ((sizeof(int) + sizeof(ani)) * (ani.id -1));`
Answer: You cannot use sizeof(availableHoles) to iterate on the array.  You are in a function that receives availableHoles as a pointer, its size is irrelevant to the number of holes.
Pass the number of elements of this array as a separate argument.
Using the FILE streams in read/write mode is tricky, do you call fseek() systematically between accesses in read mode and write mode?
Post the calling code, the function addingAnimal alone is not enough to investigate your problem.
Comment: @user3376654 No it's not working correctly. If you don't believe that then put a print statement inside the `for` loop. You should find it doesn't print out the number of times you intended the loop to run for. It may or may not be the root cause of your problem but it certainly is wrong and should be fixed to remove that possibility.
Comment: I believe you're referring to my for-loop at the very end, that is just to update the empty holes. That portion is working correctly to my understanding, it's me seeking to the right line of the file I am having trouble with.

Using fseek() To Update a Binary File


Forecast and STL are sensitive to last few data points

Question: I'm working on a time series containing hourly data for 8 days. Using the R forecast package, I'm trying to predict future data with stl. If I use only 7 days data, things work fine, but when I add the last day, the predicted values drop strongly. My questions:

Visually the 8 days data still show a clear periodic trend, why
forecast gives that result? Looking at the data, I see that the
value of the last hour of the day drops to 0 sooner than in previous
days. But why forecast are so sensitive with that?
Any advice for this situation? Any search keyword or reference that
I should know for further reading?

Thank you.
xnn <- c(0.11, 0.28, 0.26, 0.27, 0, 0, 0, 0, 0, 0.19, 0.19, 0.19, 0.25,
0.35, 0.42, 0.39, 0.17, 0.19, 0.36, 0.38, 0.41, 0.35, 0.33, 0.37,
0.36, 0.33, 0.06, 0, 0.17, 0, 0, 0, 0, 0.17, 0.31, 0.23, 0.4,
0.38, 0.33, 0.41, 0.34, 0.33, 0.41, 0.33, 0.34, 0.38, 0.41, 0.41,
0.4, 0.38, 0.27, 0.17, 0, 0, 0, 0, 0, 0, 0, 0, 0.44, 0.39, 0.4,
0.4, 0.38, 0.28, 0.36, 0.38, 0.43, 0.42, 0.44, 0.45, 0.41, 0.34,
0.2, 0, 0, 0, 0, 0, 0.15, 0.17, 0.17, 0.21, 0.42, 0.46, 0.42,
0.46, 0.38, 0.34, 0.35, 0.37, 0.38, 0.36, 0.36, 0.38, 0.35, 0.36,
0.39, 0.25, 0.15, 0.15, 0.15, 0.15, 0, 0, 0.28, 0.28, 0.42, 0.43,
0.44, 0.41, 0.41, 0.37, 0.37, 0.31, 0.33, 0.32, 0.34, 0.29, 0.3,
0.28, 0.22, 0.17, 0, 0, 0, 0, 0, 0, 0, 0.17, 0.32, 0.38, 0.39,
0.4, 0.37, 0.41, 0.45, 0.39, 0.35, 0.37, 0.33, 0.38, 0.37, 0.31,
0.15, 0, 0, 0, 0, 0.15, 0.1, 0.15, 0.19, 0.26, 0.38, 0.39, 0.39,
0.38, 0.38, 0.42, 0.41, 0.4, 0.43, 0.41, 0.33, 0.28, 0.35, 0.39,
0.26, 0.31, 0, 0, 0, 0, 0, 0, 0.23, 0.3, 0.4, 0.4, 0.4, 0.43,
0.41, 0.44, 0.43, 0.43, 0.41, 0.31, 0, 0)

require(forecast)
## hourly data
## 8 days (24*8 = 192 data points)
dput(xnn)

## using first 7 days, result is acceptable
x.ts <- ts(xnn[(1+24*0):(7*24)], frequency = 24)
fit <- stl(x.ts, s.window="periodic")
X11()
plot(fit)
X11()
plot(forecast(fit), type = "o")

## include one more day, unexpected result
x.ts <- ts(xnn[(1+24*0):(8*24)], frequency = 24)
fit <- stl(x.ts, s.window="periodic")
X11()
plot(fit)
X11()
plot(forecast(fit), type = "o")

Answer: Your last day drops to zero much sooner than earlier days. So the seasonally adjusted series has a big drop right at the end of your 8th day. The forecasts reflect this drop. It looks like you might be missing some observations in the last day.
Comment: Thank you very much for the answer and for your great package :) In situations like this, is there any parameter that I can tune to ease out the effect on the seasonally adjusted series? If I throw away the last 7 points (of 24 points of the last day), then the forecast comes back to normal. It does not make sense (in practice) when I have 50 days of regular data and the forecast for the whole next 5 days drop just because of the last few points. Or do you suggest any better model/approach for such kinds of data? Thanks.


Is log transforming square root transformed data a legitimate data transformation?

Question: Is it legitimate to do a "double transformation" on data? Specifically, log transforming data which has already been square root transformed, or conversely, square root transforming log transformed data? Does this even make sense?
Comment: It would help if you could say add something to your question about what you are trying to accomplish with the transformation. Note that taking the log of the square root of a value is just one-half the log of the original value.
Comment: You don't say what you want to do with these transformations...use them in a regression? Transformations of *any* kind do not violate any assumptions of multiple regression. In other words, you are free to do whatever you want to with your information. You may later be asked what they mean or how they "improved" the model. That would be a tougher challenge and, in some cases, sufficient cause not to use them.
Comment: I'm trying to normalize the distributions of my predictor variables (includes both count and proportion data), which are currently negatively skewed. I'm planning on doing a principal components analysis, and then using the factor scores in a GLM. Thanks for your comments.
Comment: Ah! Another option is to employ a factor analytic approach that accounts for extreme valued information. See this paper on *Cauchy PCA* from some guys at CMU. It describes four different types of data and the differing assumptions that go with each. Having done it, it's not that hard to code up in Python, SAS or any other software.   http://www.cs.cmu.edu/~pengtaox/papers/cpca.pdf
Answer: Specifically, no.
Using natural logarithms for concreteness, and a generic variable $x$, the transformation $\ln \sqrt{x}$ is defined easily for positive numbers, but also can be seen to be just $\ln x^{0.5} = 0.5 \ln x$. Hence it has exactly the same effect in terms of effect on nonlinearity, asymmetry, lack of Gaussianity -- or whatever the transformation is designed to cure or improve -- as $\ln x$.
The transformation $\sqrt{\ln x}$ is defined easily for $x > 1$, but that seems also to be an artificial constraint. I'd be happy to learn of a rationale but I can't think of one. If you want a transformation that is stronger than the logarithm, the reciprocal is a simpler transformation to consider first. Reciprocals can be applied usefully so long as all values are positive or all values are negative.
Generally, there certainly are useful transformations that can be regarded as two-step functions, e.g. the logit $\ln [p / (1 - p)]$ or the angular transformation $\arcsin \sqrt{p}$. Here the domain is now proportions or probabilities $p$ and $0 < p < 1$ for logit and $0 \le p \le 1$ for angular. If a transformation is useful and natural enough, we tend to regard it as a function directly defined and named, so that (e.g.) statistical software commonly supplies logit functions for immediate use.
Some might want to underline that in some contexts complex results, i.e. those with real and imaginary parts, might be interesting or useful.
Comment: Left-skewed variables will be made **worse** by taking roots or logarithms or reciprocals, even if the slgn of skewness is flipped (as reciprocals will do). Squares or cubes can help in principle; in practice I think you are likely to be overestimating the need for normal distributions. But I've a hard time imagining situations with left-skewed counts; there is likely to be some crucial context that you are not telling us about. How big is the dataset? Can you post it? Can you plot it?
Comment: Thank you for your answer and excellent information. My data set includes both count and proportion variables, which are currently negatively (left) skewed. I have tried the reciprocal transformation, but it seems to have too strong an effect on my data - the distributions become extremely positively skewed. I've been looking into the arcsin transformation, but I'm a bit confused about how it is calculated. I also have some reservations about using it after finding this article: http://onlinelibrary.wiley.com/doi/10.1890/10-0340.1/full. I will look into trying the logit. Thanks.
Comment: Sorry, I just realized I'm saying that backwards - It is right skewed! My count data are pesticide concentrations from water samples...many values are zero or very low, which is driving the skewness. I think you are probably right that I'm overestimating the need for normal distributions, particularly since I plan to do PCA (I've read normality is not required for this). However, since I then plan to use the factor/component scores in a GLM, I thought it would be best to normalize the original data first. Maybe this is unnecessary? Or perhaps just normalize the factor scores?
Comment: Concentrations can't be counts even if reported as integers by convention: the units are presumably ppm/ppb/ppt. . As before comment is difficult when you don't show or plot the data. What is crucial for  generalized linear models is how the response or outcome behaves and non-normal families can be not only allowed but also entirely natural. I'd omit the PCA and move straight towards GLM.
Comment: Data set is comprised of landscape variables (% various cover types), water quality variables (pesticides & nitrogen), and biological responses (aquatic invertebrates, and 2 biological measures of water quality) from 28 sites. Due to the large variable to sample size ratio, I though it would best to do a PCA on the predictors (many of which are correlated).
Comment: PCA has its good uses but doing your thinking about cause or process is not among them.
Comment: I could show some examples of some of the histograms - best to edit and post in the original questions? Good to know that concentrations are not counts - if not counts, what type of variable/family are they considered?
Comment: Concentrations are surely **measured** variables. If you care about nominal/interval/ordinal/ratio they are surely ratio scale. As said, if they have units of measurement, they can't be counts. I think you're morphing towards a different question. Comments are not a good medium for discussing good models for your data.
Answer: By the properties of logarithms, $$
y = \sqrt{x}
$$$$
\log(y)=0.5\log(x)
$$
So the net effect in something like a regression setting is to add a constant multiplier out front of the variable, i.e. to double the coefficient value of the log-square-root compared to simply taking the log.
But in other contexts, the effect won't matter at all! If you're using decision tree methods (e.g. random forest), and x > 0, then it won't even matter because these models are insensitive to monotonic transformations of the data.


transform:translateX vs transition on left property. Which has better performance? CSS

Question: I'm making a slide out menu with HTML and CSS3 - especially transitions.
I would like to know what is best practice / best performance to slide a relatively positioned div horizontally. When i click a button it adds a class to my div. Which class is better? (Note I can add all the browser prefixes later and this site only targets modern browsers).
//option 1
.animate{
    -webkit-transition:all ease 0.3s;
    -webkit-transform:translateZ(200px);
}

//option 2
.animate{
    -webkit-transition:all ease 0.3s;
    left:200px;
}

Thanks
Comment: http://blog.alexmaccaw.com/css-transitions
Answer: Transitions via translate performs MUCH better on mobile devices!
Edit:
Here are a live demo. Transitions with translateX and translateY are much smoother than top, bottom, left and right.
jsFiddle Demo for mobile devices
Comment: I'm building a webapp for the iPad at the moment. And the performance with translateX and translateY is MUCH better than with left, right, top and bottom. But If you build it only for desktop browsers you will see no difference.

And there is another difference. if you animate to left: 100% the element will be animated to 100% of the parents width. And if you animate translateX(100%) the element will be animated to 100% of the own width.

I haven't any tests or articles at the moment - just my experience ;) but i will prepare a jsFiddle today...
Comment: Any tests or articles for this?
Comment: Here look at this. just hover (or click on mobile) on the left an right side. the translateY transitions are much smoother on my iPad 3. http://jsfiddle.net/philippkuehn/wLm87/
Comment: just add a case now. transform is way better than transition for performance on the iphone
Comment: The fiddle in this answer just made me realize that my translateX wasn't working because I had `position: absolute;` on.
Answer: translateX and translateY is much smoother than left, right, top, bottom and jQuery animate versions.
See this for much deeper details with demo:
http://www.paulirish.com/2012/why-moving-elements-with-translate-is-better-than-posabs-topleft/


Need help deriving the Schwartz inequality.

Question: I am trying to prove the Schwartz Inequality (through an exercise) in the form of
$$
\sum_{i=1}^{n}x_iy_i \le \sqrt{\sum_{i=1}^{n}x_i^2}\sqrt{\sum_{i=1}^{n}y_{i}^2}
\tag{1}
$$
through a method of knowing that there is no $\lambda$ for $x_1 =\lambda y_1$ & $x_2 =\lambda y_2$  through which we can easily make out that
$$
 0 < \sum_{i=1}^{n}(\lambda y_i -x)^2
\tag{2}
$$
or
$$
0< \lambda^2 (\sum_{i=1}^{n}y_i^2) - 2\lambda (\sum_{i=1}^{n}x_iy_i) + (\sum_{i=1}^{n}x_i^2)
\tag{3}
$$
No problem there. For the next couple of steps, I am going to denote $(\sum_{i=1}^{n}y_i^2)$ by $a$, $(\sum_{i=1}^{n}x_iy_i)$ by $b$ and $(\sum_{i=1}^{n}x_i^2)$ by $c$ (to reduce time writing this),
for example, $(3)$ is written as
$$
0 < \lambda ^2(a)-2\lambda(b) +c
\tag{4}
$$
which we can proceed to make into
$$
0<\lambda ^2-2\lambda(ba^{-1})+ca^{-1}
\tag{5}
$$
Now, since from $(3)$, we can see that $0=\lambda ^2(a)-2\lambda(b)+c$ has no solution for $\lambda$ as I already stated that there is no $\lambda$ for $x_1 =\lambda y_1$ & $x_2 =\lambda y_2$ , so we can say that for $(5)$,
$$
 (ba^{-1})^2-4(ca^{-1}) < 0
\tag{6}
$$
$(6)$ is derived from $b^2-4c<0$ (here is where I made my mistake, I don't know why I didn't use $b^2-4ac$ sorry for this stupid mistake, from here I go on to try to make $a = 1$) for cases where we don't have a solution. Bringing back the summations, we get
$$
(-2(\sum_{i=1}^{n}x_iy_i)(\sum_{i=1}^{n}y_i^2)^{-1})^2-4(\sum_{i=1}^{n}x_i^2)(\sum_{i=1}^{n}y_i^2)^{-1} < 0
\tag{7}
$$
which is as far as I got. I tried doing
$$
4(\sum_{i=1}^{n}x_iy_i)^2(\sum_{i=1}^{n}y_i^2)-4(\sum_{i=1}^{n}x_i^2)(\sum_{i=1}^{n}y_i^2)^{-1} < 0
\tag{8}
$$
but I don't know how to get to $(1)$. So, did I do something wrong? Can someone elaborate on what I am meant to do? I am so sorry for the stupid question, I am really tired and (even though that's not an excuse,) I feel like I made a mistake somewhere and I really want to know the answer by the end of today. Thank you so much.

I am sorry if I am making any stupid mistakes, I am tired but I can't sleep without knowing how to do this.
Comment: Note that it is "Schwarz", not "Schwartz", named after [Karl Hermann Amandus Schwarz](https://en.wikipedia.org/wiki/Hermann_Schwarz).
Comment: @Sdavid552 From the corrected $(8)$ and multiply both sides by $\frac{a^2}{4}$, you get $b^2-ac < 0$. Sure it's a longer route with some extra division and multiplication of $a^2$, but it's too harsh to say everything was a mess.
Comment: I wasn't sure about the tags, if they are misleading or lacking, please feel free to change them. I didn't really know if this fit into "Calculus", sorry about that.
Comment: I edited wording, nothing big.
Comment: Line $(8)$ should be $4b^2a^{\color{red}{-2}}-4ca^{-1}< 0$, i.e. $a^{-2}(4b^2-4ac)<0$.
Comment: @peterwhy You're right, but regardless, I messed up this whole proof, I wouldn't really know where to go from $(8)$, even with your correction, maybe there someway, but I am not going to bother then, it would've been much easier if I just used $b^2-4ac < 0$ (something noted in the answer below) instead of trying to make $a=1$, this whole question was a mess, regardless, thank you for pointing that out.
Answer: Go back to
$0 < \lambda ^2(a)-2\lambda(b) +c$.
Using the original quadratic formula,
the discriminant is
$d = (2b)^2-4ac
=4(b^2-ac)
$.
For the quadratic
to have no real roots,
$d < 0$
so
$b^2-ac < 0$
so
$b^2 < ac$.
Comment: Now that I am in a much better mood, I am going to comment for the last time. Thank you very much for the answer, originally I placed "<" the wrong way around; I already fixed it. What I was saying is that $0=\lambda ^2(a)−2\lambda (b)+c$ had no solution hence $b^2−ac$ had to be $<0$. I am sorry for wasting your time but I thank you for taking your time to answer me. I ended up getting my answer by taking the much simpler route mentioned in the comments. P.S. I wasn't happy with my comment I made yesterday in a rush.


Pull data into a list for custom content type?

Question: Hopefully this is a quick question!  I'm working on a custom content type for users to create something similar to blog posts.  We'll have different authors who will be credited, so I need a drop down list so when a user writes the post, they can select the author.
The trouble is, I need to list to be auto populated from the data that is stored in a different field.  We have a content type called (you guessed it) authors.  It allows us to fill out name, field of expertise, etc.
So, how can I add an AUTHOR NAME list to my BLOG custom content type?
Thanks!
-JB
Answer: You can use the Entity Reference module to create your 'author name' field, which will reference your authors content type.


Update com Codeigniter

Question: Estou tentando fazer um update em meu banco de dados usando codeigniter, porém o update não esta sendo executado.
HTML:
<?php echo form_open('Texto/alterarTexto', 'class="form-horizontal"'); ?>
  <fieldset>
    <legend>Novo texto</legend>

      Titulo

        <input id="titulo" name="titulo" type="text" placeholder="" class="form-control input-md" value="<?php echo $dados[0]->titulo; ?>" required disabled>

      Data

      <input id="data" name="data" type="hidden" placeholder="" class="form-control input-md" required value="<?php echo $dados[0]->id; ?>">
        <input id="data" name="data" type="text" placeholder="" class="form-control input-md" required value="<?php echo $dados[0]->data; ?>">

      Texto
 Evite grandes textos

        <textarea rows="10" id="area1" cols="120" name="texto"><?php echo $dados[0]->texto; ?></textarea>

        <button id="salvar" class="btn btn-primary btn-lg" type="submit">Salvar</button>

  </fieldset>

Controller:
public function alterarTexto() {

    $data = array(  'id' => $this->input->post('id'),
                    'data' => $this->input->post('data'),
                    'texto' => $this->input->post('texto')
                    );
    if ($this->Texto_model->alterarTexto($data)) {
        echo "Sucesso!";
    } else {
        echo "Erro!";
    }

}

Model:
    function alterarTexto($data) {
    $this->db->where('id', $data['id']);
    $this->db->set($data);
    return $this->db->update('texto', $data);
}

No controller eu coloquei echo só para saber em que parte do  if estava caindo, e o que aparece é a mensagem sucesso, porém nada muda.
Comment: Dá um print_r($data), dentro do controller, pra ver se estão chegando os dados corretamente.
Comment: if ($this->Texto_model->alterarTexto($data)) { print_r($data); die();
Answer: No seu HTML, adicione:
<input type="hidden" value="<?php echo dados[0]->id; ?>" name="id">

Dentro do seu model, desabilite:
$this->db->set($data);

Answer: Creio que o "$this->db->set", deverá ser campo por campo da tabela em questão, pois, se tu largar todo o array $data dentro do set dará erro de syntax sql.
Dentro da array tem a propriedade id também, e tu não pode atualizar ela...
function alterarTexto($data) {
    $this->db->where('id', $data['id']);
    $this->db->set('Titulo', $data['Titulo']);
    $this->db->set('Data', $data['Data']);
    $this->db->set('Texto', $data['Texto']);
    $this->db->update('texto');
    if($this->db->trans_status() === true){
        $this->db->trans_commit();
        return true;
    }else{
        $this->db->trans_rollback();
        return false;
    }
}

Acho que assim resolve...
Espero ter ajudado...
Oss!

Update com Codeigniter


Temporary vocal bass range extension

Question: I need a quick fix on how to very temporarily extend my lower voice range.
The note(s) I need to reach, for a short performance in a couple of days, are notes that I can reach fairly easily and sing reasonably strong during times when I'm actively singing in choirs (with 2-3 semitones to spare until my absolute range limit)1. However I'm currently out of shape and the desired note(s) - although I currently in general can "sing" them - are very weak and at the very limit of my lower range. That is I'm lacking the 2-3 semitones of "buffer" that would make for the desired note(s) to come out strong enough. Also, since the performance is in the evening I afraid of tensioning up during the day so I can't reach the notes at all.
Since (a) this is a one time thing, (b) the total performance time for me will be less than a minute, (c) my voice quality for the performance is pretty much irrelevant, and (d) I'm not dependent on my singing voice for a living, I am open to suggestions that are possibly (but hopefully temporarily) destructive for the voice. Such as Drinking special fluids? Or screaming? Or making the vocal chords swollen some (other) way?
I've read this (and others) Q&A, but it's not aimed at a temporary quick fix and don't allow for having a possible bad voice:
How to extend and strengthen low end of vocal range? (I need about a whole tone extra.)
When singing in a choir I normally sing bass 2.
Mornings after a good party I can reach up to a fifth lower than my current low end limit and the desired notes then come out at full strength.
1These notes are very rarely found in choir music, but the active singing makes my range encompass them for easy reach.
Comment: Oof.  I hope you find something safe!
Comment: Catch a cold... give yourself a hangover... ;)
Answer: For longer-term development, there's vocal fry and false-cord vibration.
But probably the best thing you can do short-term is lots of rest. If you can manage to take a 2-hour nap before singing, it should make the low tones easier to achieve because the muscles are relaxed. The "two hour" part is to try to get one full 90 minute sleep cycle. The deep-sleep portion of the cycle is where the muscles are greatly affected. Any less than a full cycle may provide no benefit, or may even be counterproductive. Practicing may be counterproductive because it will increase the muscle tension.
And of course, breath-support. The deep tones need more support.
Edit:
A few more ideas. [I realize the localized event has passed. Hope it went well, @Ulf! So this is for posterity.]
In-line with the breath-support, one should try to rise up from beneath the note rather than reaching down toward it. This almost forces you to summon the note with enough breath behind it. Then the fully-relaxed larynx won't interfere with your deepest resonance. You get the air going then scoop up to tone. With really deep notes, you're never going to get much attack and you'll strain if you try. But if it's breathy, you can add volume and tone by adding more breath without any real need to tense-up.
If you can move just a little closer to the microphone, that should reduce your need for volume and make the breathy tone less inadequate (hopefully reducing your need to push it).
Answer: To hit the low notes, you will need to train your high notes. You will need as much support and muscle training for the lowest notes as the highest notes.
Source: my experience: I am a bass and have always trained the high notes more than the low notes. Both ends of my tessitura have strengthened over the years and my vocal range has grown. It is common for basses to practice the low notes only, which leads to them have no high notes and breathy, non-metallic low notes.
I am afraid I cannot provide you a quick fix but it is worth remembering that singing both high and low notes requires muscle training and low notes should not be overlooked as easier to sing than the high notes, or sung with just power, but they should be treated equally and sung with the right (and similar!) technique.
Answer: Add sulfur hexafluoride to the air you breathe while singing the part.  Find a concentration that lets you nail your lowest note, then fill a balloon or bag with that mix.
Comment: As far as I know, sulfur hexafluoride does not lower the pitch your voice, just as helium does not raise the pitch of your voice.  In the video you linked, he actually talks with a *higher* pitch when demonstrating the deep voice.
Comment: @Edward True, gases with different densities can only affect the timbre of the voice, not the fundamental frequencies. Still, one might wonder whether sulfur hexafluoride could possibly help a bass singer get a solid deep tone of voice on an extreme low note that otherwise might sound very weak...

Temporary vocal bass range extension


How do I call a function in a JavaScript file?

Question: I have included a javascript in the module "myid" I've been developing in drupal by using this code:
function myid_init() {
    drupal_add_js(drupal_get_path("module", "myid") . "js/myid.js");
}

This is my Javascript file "myid.js":
function myid_js_start(){
    alert("hello world");
}

Below is the code that creates a button that invokes an alert function:
$form['add_button'] = array(
    '#type' => 'button',
    '#value' => 'Take a picture',
    '#attributes' => array('onclick' => 'myid_js_start()'),
);

I dont know where did I go wrong. The button shows up but doesn't fire any alert function. Can anyone help me with this?
Comment: Sadly there are too many who post here that do not know to do that, therefore it is helpful to include that fact in your question =)
Comment: Standard question: have you cleared your cache? Have you tried specifying that the function is javascript as per http://stackoverflow.com/questions/21032365/add-an-onclick-attribute-to-login-submit-button-in-drupal-7
Comment: I always clear the cache, everytime I make changes.
Answer: Try to write JS in drupal way like this:
(function($) {

    Drupal.behaviors.xyzModule = {
        attach: function(context, settings) {

//            $('.test', context).click(function() {
//                $(this).next('ul').toggle('show');
//            });

//myid_js_start();
            function myid_js_start() {
                alert("hello world");
                //console.log(' Hello');
            }

        }
    };

})(jQuery);

For More info visit here
Answer: This:
drupal_add_js(drupal_get_path("module", "myid") . "js/myid.js");

Needs to be:
drupal_add_js(drupal_get_path("module", "myid") . "/js/myid.js");

Note the forward slash before the path to the js file


Derivation of linear boundary conditions of BVP for second-order Linear ODEs

Question: I am having some trouble understanding where some linear boundary conditions are derived from
The following is an extract from my lecture notes on boundary value problems for second-order Linear ODE's

In this section we are going to consider the different situation when some conditions are specified at the endpoints, or boundaries, of an interval of the independent variable, that is, at $x = x_1$ and $x=x_2$ with $x_1 < x_2$. This problem is known as a $ \textbf{Boundary Value Problem} $ and the conditions are called boundary conditions. We are then interested in finding the solution $y(x)$ to the ODE (which we consider to be Linear) inside the interval $x_1 \le x \le x_2$. we will consider only linear boundary conditions, where the left-hand sides of the conditions are linear combinations of the function and its derivatives at the same point and the right hand sides are given by constants, for example
$$ y(x_1) = b_1, \ y(x_2)=b_2 \ \ or \ \  y'(x_1)=b_1, \  y'(x_2) = b_2$$
or more generally
$$ \tag{1}  \alpha y'(x_1) + \beta y(x_1)=b_1, \gamma y'(x_2)+\delta y(x_2) =b_2,$$
where $\alpha , \beta , \gamma , \delta$ are given real constants such that $|\alpha |+ | \beta | > 0, | \gamma | + | \delta|>0. $

My question is this, where do the conditions $(1)$ derive from?
Answer: There is no derivation. Those are the three types of boundary conditions generally seen.
$$ y(x_{1}) = b_{1}, y(x_{2}) = b_{2} $$
is known as a Dirichlet Boundary Condition
$$ y^{'}(x_{1}) = b_{1}, y^{'}(x_{2}) = b_{2} $$
is known as a Neumann Boundary Condition.
$$  \alpha y'(x_1) + \beta y(x_1)=b_1, \gamma y'(x_2)+\delta y(x_2) =b_2,$$
The last type is called Robin Boundary Conditions.
There is an interpretation.
Dirichlet Conditions mean you are holding the boundaries at a specific temperature.
Neumann Conditions means that the boundaries are being given energy at a specific rate.
Robin is a linear combination of the above.
Comment: thanks! your interpretation also helped a lot!
Comment: It was no problem.
Comment: Just to be sure, the last type is called both Neumann B.C and Robin B.C ?, can you please clarify
Comment: @BAYMAX I edited it. I believe it can be called both Mixed and Robin conditions but somewhere I've seen people say there is a slight difference between Mixed and Robin.
Comment: cool! [here](https://en.wikipedia.org/wiki/Mixed_boundary_condition), it mentions the difference between the mixed and Robin Boundary Conditions. Mixed BC essentially on disjoint parts of the domain and Robin on the whole of the domain.
Comment: @BAYMAX ahh, cool thanks
Answer: The boundary conditions are found by the physical condition of the problem at the end points.
For  example if the end points are moving according to certain rule involving velocity or if the temperature at end points are controlled according to some rules dictated by the problem.


Does removing unused imports have an impact on bundle size and build time in Reactjs

Question: I have a Reactjs application created using Create React app which while starting and building gives a lot of warnings which states that I have unused vars or imports in my Components.
./src/components/home/Header.js
    Line 10:   'Switch' is defined but never used  no-unused-vars
    Line 10:   'Route' is defined but never used   no-unused-vars

Does having no-unused-vars have a considerable impact on final bundle size and build time of the application. Can I reduce build time and bundle size by removing all these warnings?
Comment: Thanks for your response @ShubhamBatra. I think Create React app comes with uglify out of box. I was looking for ways to optimize build size and time.
Comment: Yes, removing these will reduce size but not much. You need to do uglify, if you really want to reduce size.
Comment: Yes, uglify is out of box but it reduce my app size from 11.1 mb to 1.89 mb. you should see this answer https://stackoverflow.com/questions/34239731/how-to-minimize-the-size-of-webpacks-bundle/34241128#34241128
Answer: Checkout this package https://www.npmjs.com/package/source-map-explorer. And run
source-map-explorer bundle.js

It will give you detailed screenshot of your bundle file like which package is taking too much file size and all. Change the way you are importing packages mentioned in How to minimize the size of webpack's bundle? and also if some particular package is causing a size issue then switch to alternative packages.


Qual a melhor maneira de representar um Loop em matemática?

Question: Precisava representar e documentar um algoritmo aritmético em uma notação matemática, o problema é que não encontro a melhor maneira de representar um loop composto para isso.
Suponhamos que temos o simples algoritmo E:
public int E () {
    return n / (m + 200);
}

A representação matemática seria:

E estou com dúvida em como representar uma função um pouco mais composta, como:
public int E () {
     int e = 0;
     for(int i = 0; i < 5; i++) {
        e += i;
        e *= i + 2;
     }
     return e;
}

E representando num somatório:

Na fórmula acima, não há nenhuma implementação de até onde o loop, começa, pula e deve ir (sendo que no código, é definido que o loop percorrerá até que i < 5, sendo inicialmente i = 0 e por loop, i += 1).
Está certa esta representação científica? Ou existe outra maneira matemática de representar um loop do gênero?
Answer: Da maneira que está:
public int E () {
     int e = 0;
     for(int i = 0; i < 5; i++) {
        e += i;
        e *= i + 2;
     }
     return e;
}

A função E sempre retornará o valor 714, então a representação matemática seria:

Mas se generalizarmos considerando uma entrada n:
public int E (int n) {
     int e = 0;
     for(int i = 0; i < n; i++) {
        e += i;
        e *= i + 2;
     }
     return e;
}

Então teremos uma função recursiva disfarçada. Recursiva porque o valor de cada iteração dependerá do valor passado; a única diferença é que este valor é armazenado em uma variável local e é calculado iterativamente do 0 até n, enquanto que na versão recursiva a chamada é feita de n até 0, sendo n = 0 nossa condição de parada, uma vez que o laço não executaria e seria retornado o valor zero.
public int E (int n) {
    if (n == 0) {
        return 0;
    }

    return (n+2) * (E(n-1) + n)
}

Para efeitos de comparação com a versão original, ao calcular E(5) teremos o mesmo resultado, 714. Desta forma, podemos representar nossa função E(n) como:
Comment: @CypherPotato, matematicamente não há distinção entre loop e recursão. É tanto que o paradigma funcional, aquele que deriva da matemática diretamente (cálculo lambda, sendo mais específico), não prevê iterações, apenas recursões.
Comment: @CypherPotato Na recursividade
Comment: Isso não responde a pergunta. Onde foi aplicado o Loop na expressão?
Comment: Onde posso especificar o ínicio, passo e fim da recursividade no exemplo citado?
Comment: @CypherPotato O que você entende por passo e fim?
Comment: `for inicio = 0; inicio < fim; inicio += passo`
Comment: @CypherPotato Hum, esse nível de detalhamento deveria estar na pergunta já
Comment: Mas está, logo abaixo da última equação. Vou editar para deixar mais claro.
Answer:
Especificamente sobre operações de somatório e produtório, não de modo geral e não consegue representar o seu caso específico porque a ordem da operação é importante.

Existem operações que são feitas em coleções. Elas são funções unárias baseadas em operações binárias (vide operação binária), contanto que a operação binária em si defina, com a coleção dos elementos, um grupo abeliano (não confundir grupo e conjunto, são objetos matemáticos distintos). E somatório e produtório são exemplos dessas operações.

Não tenho a garantia da necessidade de que o grupo necessite ser abeliano, porém, como por si só um grupo não tem ordenação, me parece intuitivo que op(a,b) = op(b,a) precise ser verdadeiro

A definição de um operador de coleção é recursiva. Seja uma coleção S (vide bag) um elemento de C* (vide estrela de Kleene), e C um conjunto pertencente ao grupo G = {C, op, e}, onde op define uma operação comutativa em C e e é o elemento neutro de op. Podemos criar um operador de conjunto opX que recebe uma coleção e retorna um elmento de C. Sua assinatura é assim (em LaTeX fica mais elegante, mas fica para um próximo momento, foquemos em ASCII):
opX: C* -> C

Isso significa que opX recebe uma quantidade variável de elemento de C (portanto, uma coleção com repetições, vulgo bag) e devolve um elemento de C. Seu retorno é escalar em C.
Essa é a assinatura de opX, que identifica quais os tipos de entradas e qual a sua saída. A definição de opX, entretanto, é assim:
opX(S) = e, se S = {}
opX(S) = op(a, opX(S\{a})), a em S, S != {}

O somatório é definido desse jeito:
Σ(S) = 0, se S = {}
Σ(S) = +(a, Σ(S\{a})), se a em S, S != {}

E a de produtório:
Π(S) = 1, se S = {}
Π(S) = *(a, Π(S\{a})), se a em S, S != {}

Acontece que muitas vezes não interessa descrever todos os elementos em S para essas operações. Então se faz uma inferência de conjunto. Para fazer essa inferência, você deve passar uma função unária em X para mapeamento (se o domínio passado for distinto do domínio da operação básica). Ou seja, você precisa descrever uma função da seguinte assinatura:
map: X -> C

Então você define uma coleção S' baseada em S aplicando a função de maepamento map:
S' = {map(s), s em S}

Então, por convenção, foi definido o seguinte:
Σ(S, map) = Σ(S'), S' = {map(s), s em S}

Porém, como na maior parte das vezes o intervalo de inteiros consiste de números consecutivos, bastaria informar o início e o fim desse intervalo. Também se convencionou que é elegante mostrar qual a variável de iteração, por isso que se coloca i = 0 debaixo do símbolo do sigma (ou do pi, no produtório) e apenas um número arbitrário acima. Exemplo dessa notação: aqui.
Em notação ASCII, seria equivalente a isso:
Σ(ini, fim, map) = Σ(S, map) = Σ(S')
S = [ini, fim], S' = {map(s), s em S}

Onde [ini, fim] é o intervalo fechado dos números inteiros entre ini e fim.
Eu particularmente as vezes escrevo apenas que a variável de iteração está contida em um conjunto. Vide os produtórios.

O algoritmo definido no seu laço em pseudo-código, entretanto, não consigo fazer com que ele se torne uma operação em algum conjunto numérico relevante (naturais/inteiros/racionais/reais/complexos).
Answer: Isso aí me parece uma relação de recorrência.
A representação matemática poderia ser
E₀ = 0
Eₙ₊₁ = (Eₙ + n) * (n + 2) (para n > 0)

Na Wikipedia.
Obs. estou colocando a Wikipedia como referência porque faz muito tempo já que estudei matemática.
Comment: Isso não é a resposta do @AndersonCarlosWoss de maneira bem sumarizada?
Comment: **acho** que esta notação mais resumida é a mais usada quando me trabalha com relações de recorrência...a notação que ele utilizou me parece ser uma notação mais genérica para denotar funções, não só funções definidas de maneira recursiva, mas também, por exemplo, funções descontínuas que a gente vê quando aprende cálculo diferencial


C# dynamically added property messes with datagridview order

Question: So I have need to dynamically add data to a class that will populated a datagridview.  Below is the test code.  I created a form with a datagridview and manually added the columns in the order I wanted with the datapropertynames that correspond to each property in the dataset. but the datagridview reorders them and I cant figure out why.  I set the datagridview to have the order of data2,data1,CustomerName but customername keeps moving between data2 and data1.  I know this may look weird with what Im trying to do but this was just a test of the concept.  The implementation is that I have columns that are calculated based off data in the other columns but those columns arent sortable because they are not bound to the data.  So I need this to work or a way to bind the data in the calculated columns so that its sortable.  Thanks
<code>public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    public static Type BuildDynamicTypeWithProperties()
    {
        AppDomain myDomain = Thread.GetDomain();
        AssemblyName myAsmName = new AssemblyName();
        myAsmName.Name = "MyDynamicAssembly";

        // To generate a persistable assembly, specify AssemblyBuilderAccess.RunAndSave.
        AssemblyBuilder myAsmBuilder = myDomain.DefineDynamicAssembly(myAsmName,
                                                        AssemblyBuilderAccess.RunAndSave);
        // Generate a persistable single-module assembly.
        ModuleBuilder myModBuilder =
            myAsmBuilder.DefineDynamicModule(myAsmName.Name, myAsmName.Name + ".dll");

        TypeBuilder myTypeBuilder = myModBuilder.DefineType("CustomerData",
                                                        TypeAttributes.Public);
        myTypeBuilder.SetParent(typeof(TestData));

        FieldBuilder customerNameBldr = myTypeBuilder.DefineField("customerName",
                                                        typeof(string),
                                                        FieldAttributes.Private);

        // The last argument of DefineProperty is null, because the
        // property has no parameters. (If you don't specify null, you must
        // specify an array of Type objects. For a parameterless property,
        // use an array with no elements: new Type[] {})
        PropertyBuilder custNamePropBldr = myTypeBuilder.DefineProperty("CustomerName",
                                                         System.Reflection.PropertyAttributes.HasDefault,
                                                         typeof(string),
                                                         null);

        // The property set and property get methods require a special
        // set of attributes.
        MethodAttributes getSetAttr =
            MethodAttributes.Public | MethodAttributes.SpecialName |
                MethodAttributes.HideBySig;

        // Define the "get" accessor method for CustomerName.
        MethodBuilder custNameGetPropMthdBldr =
            myTypeBuilder.DefineMethod("get_CustomerName",
                                       getSetAttr,
                                       typeof(string),
                                       Type.EmptyTypes);

        ILGenerator custNameGetIL = custNameGetPropMthdBldr.GetILGenerator();

        custNameGetIL.Emit(OpCodes.Ldarg_0);
        custNameGetIL.Emit(OpCodes.Ldfld, customerNameBldr);
        custNameGetIL.Emit(OpCodes.Ret);

        // Define the "set" accessor method for CustomerName.
        MethodBuilder custNameSetPropMthdBldr =
            myTypeBuilder.DefineMethod("set_CustomerName",
                                       getSetAttr,
                                       null,
                                       new Type[] { typeof(string) });

        ILGenerator custNameSetIL = custNameSetPropMthdBldr.GetILGenerator();

        custNameSetIL.Emit(OpCodes.Ldarg_0);
        custNameSetIL.Emit(OpCodes.Ldarg_1);
        custNameSetIL.Emit(OpCodes.Stfld, customerNameBldr);
        custNameSetIL.Emit(OpCodes.Ret);

        // Last, we must map the two methods created above to our PropertyBuilder to
        // their corresponding behaviors, "get" and "set" respectively.
        custNamePropBldr.SetGetMethod(custNameGetPropMthdBldr);
        custNamePropBldr.SetSetMethod(custNameSetPropMthdBldr);

        Type retval = myTypeBuilder.CreateType();

        // Save the assembly so it can be examined with Ildasm.exe,
        // or referenced by a test program.
        myAsmBuilder.Save(myAsmName.Name + ".dll");
        return retval;
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        Type custDataType = BuildDynamicTypeWithProperties();

        PropertyInfo[] custDataPropInfo = custDataType.GetProperties();
        foreach (PropertyInfo pInfo in custDataPropInfo)
        {
            Console.WriteLine("Property '{0}' created!", pInfo.ToString());
        }

        Console.WriteLine("---");
        // Note that when invoking a property, you need to use the proper BindingFlags -
        // BindingFlags.SetProperty when you invoke the "set" behavior, and
        // BindingFlags.GetProperty when you invoke the "get" behavior. Also note that
        // we invoke them based on the name we gave the property, as expected, and not
        // the name of the methods we bound to the specific property behaviors.

        object custData = Activator.CreateInstance(custDataType);

        ((TestData)custData).data1 = "This Works";
        ((TestData)custData).data2 = "This Works 2";
        custDataType.InvokeMember("CustomerName", BindingFlags.SetProperty,
                                      null, custData, new object[] { "Joe User" });
        var list = new List<object>();

        /* var1.data1 = "Hello";
         var1.data2 = "World";
         list.Add(var1);*/
        list.Add(custData);
        dataGridView1.DataSource = list;

    }

    private void button1_Click(object sender, EventArgs e)
    {
        var test = dataGridView1.Rows[0].DataBoundItem;
    }
}

public class TestData
{
    public string data1 { get; set; }
    public string data2 { get; set; }
}
</code>
Comment: Can you not use `dynamic`? See https://stackoverflow.com/questions/5573856/binding-a-gridview-to-a-dynamic-or-expandoobject-object/6298704#6298704
Comment: That may work in some instances however the data relies heavily on the object and methods in that object so there is no way for me to convert it to a datatable without a major code change (couple thousand lines)  so I need to derive the base class and add the properties programmatically.
Answer: Turns out by disabling autogeneratecolumns fixed it.  It seems the datagridview was clearing my created columns and generating new ones from the datasource.


How to run a Symfony command from Heroku's Scheduler

Question: I've configured Heroku's Scheduler to run a Symfony 2 command:
bash app/console myapp:send:confirmations --verbose

And set it to be run each 10 minutes.
But, in the logs I see those messages:
2015-09-10T13:01:25.313711+00:00 heroku[api]: Starting process with command `bash app/console myapp:send:confirmations` by email@example.com
2015-09-10T13:01:44.151426+00:00 heroku[scheduler.7629]: Starting process with command `bash app/console myapp:send:confirmations --verbose`
2015-09-10T13:01:44.811500+00:00 heroku[scheduler.7629]: State changed from starting to up
2015-09-10T13:01:45.565021+00:00 app[scheduler.7629]: app/console: line 2: ?php: No such file or directory
2015-09-10T13:01:45.565093+00:00 app[scheduler.7629]: app/console: line 19: unexpected EOF while looking for matching `''
2015-09-10T13:01:45.565096+00:00 app[scheduler.7629]: app/console: line 28: syntax error: unexpected end of file
2015-09-10T13:01:46.291606+00:00 heroku[scheduler.7629]: State changed from up to complete
2015-09-10T13:01:46.278800+00:00 heroku[scheduler.7629]: Process exited with status 2

Those are the three relevant that are confusing me:
2015-09-10T13:01:45.565021+00:00 app[scheduler.7629]: app/console: line 2: ?php: No such file or directory
2015-09-10T13:01:45.565093+00:00 app[scheduler.7629]: app/console: line 19: unexpected EOF while looking for matching `''
2015-09-10T13:01:45.565096+00:00 app[scheduler.7629]: app/console: line 28: syntax error: unexpected end of file

I'm a bit confused: the file app/console seems not exist, but then the script encounters an unexpected EOF (but the file doesn't exist o.O) and then an unexpected end of file (isn't this the same thing as the message immediatley before?
What am I doing wrong?
Answer: Use php instead of bash to launch the console:
php app/console myapp:send:confirmations --verbose

I have the same behaviour (crash) on Ubuntu 15.04:
$ bash app/console
app/console: line 2: ?php: No such file or directory
app/console: line 18: unexpected EOF while looking for matching `''
app/console: line 23: syntax error: unexpected end of file
$ php app/console -v
Symfony version 2.7.4 - app/prod
...

It seems that the shebang from the start of app/console is ignored and the PHP interpreter is not called:
#!/usr/bin/env php
<?php
....

Here are explanations from Aaron Copley:

It's not executable
Run the binary with absolute or relative path

So if you mark the file as executable and launch the script with relative path, the PHP interpreter will be called:
$ chmod +x app/console
$ ./app/console -v
Symfony version 2.7.4 - app/prod


On Matlab while running this code I am getting this error, Z must be a matrix, not a scalar or vector

Question: I am unable to generate mesh or surf while using this code
 z must be a matrix, not a scalar or vector
r= 5;
theta= 60 ;
ro=5;
w1=200;
w2=300;
t=0:1:60;
dt=diff(t);
x=ro*cos(w1.*t)+r.*cos(theta+(w1+w2).*t)
dx=diff(x);
y=ro*sin(w1.*t)+r.*sin(theta+(w1+w2).*t)
dy=diff(y);
a=(dx./dt).^2;
b=(dy./dt).^2;
v=sqrt(a+b);
[x,y]=meshgrid(x,y);
surf(x,y,v)

Answer: v is a vector. from Matlab's documentation:

The function plots the values in matrix Z as heights above a grid in the x-y plane defined by X and Y

I.e v should be a matrix (in the size of length(x) * length(y)).
Usually, the meshgrid output itself could be passed for the calculations on each of the 2D locations :

[X,Y] = meshgrid(1:0.5:10,1:20);
Z = sin(X) + cos(Y);
surf(X,Y,Z)

see: surf docs