Preimage set of complex polynomial is connected.

Question: Let $f(z) \in \mathbb{C}[z]$ with deg$(f) \geq 1$. Then $\{z \in \mathbb{C} : |f(z)| > 1\}$ is connected.
I know that $f(z)$ is holomorphic, so continuous on $\mathbb{C}.$ I dont think that preimage of connected set under continuous map is always connected.
Right now I just know that $\{z \in \mathbb{C} : |f(z)| > 1\}$ is open since it is exactly the set $|f|^{-1}((1,\infty)).$
Answer: Since the given set contains the exterior of a large circle $C$, there is certainly a connected component that contains $\infty$, which also contains the exterior of $C$.
Suppose the statement is not true. Then there will be another connected component $D$, which is inside $C$. Since $\lvert f\rvert$ is continuous $D$ is a compact domain. Apply the maximum modulus principle to $f$ in $D$: $\lvert f\rvert$ takes on its maximum on the boundary of $D$, but $\lvert f\rvert \geq 1$ on the interior of $D$ by the definition of $D$, so $D$ must be constant, which is a contradiction.
Comment: Exterior ? Do you mean it is the complement of interior points of $C$ ? It is in topology sense ? (I dont know the definition of exterior points, but I guess you mean outside of the interior ?)
Comment: When you speak of $\infty$, do you mean the extended complex plane ? (I think this problem is proved in $\mathbb{C}$, not in $\mathbb{C} \cup \{\infty\}$)
Comment: I mean a set of the form $\{ z : z>R \}$. This is because $\lim_{z \to \infty} \lvert f(z) \rvert = \infty$ for polynomials.
Comment: why $|f| \geq 1$ on the interios of $D$ ?
Comment: $D$ is a connected component of the set on which $|f| > 1$, so *a fortiori* $|f|>1$ on the $\text{int }{D} \subseteq D$.


Consumer not rebuilding UI using riverpod ChangeNotifier

Question: I was able to narrow this down to the UI not updating, the consumer is not updating with changing data. How can I get this to work properly?
The goal is for the app bar text widget to reload when the models start and end date variables change.
I checked this similar post but he is using stateNotifier. This looks more complex and I'm just trying to learn riverpod with a simple demo...
Nothing I have tried has worked yet. I tried creating a new global provider in the screen file and that did nothing. Tried changing the way I was initializing the watch in the consumer and nothing. I have verified and it seems I'm doing everything as the documentation says here. I do not understand why this won't work. Any help and pointers is appreciated!
screen:
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:intl/intl.dart';
import 'package:linechart/date_range_widget.dart';
import 'package:linechart/linechart.dart';

class LineChartScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          title: Consumer(builder: (context, watch, child) {
            final startDate = watch(dateController);
            final endDate = watch(dateController);

            final formStart = DateFormat.yMMMd().format(startDate.startDate);
            final formEnd = DateFormat.yMMMd().format(endDate.endDate);

            print(context.read(dateController).startDate);
            print(context.read(dateController).endDate);

            return Text('INCOME GRAPH --- $formStart - $formEnd');
          }),
          backgroundColor: Colors.lightBlue,
          actions: [DateRangeWidget()]),
      body: Column(
        children: [
          SafeArea(
            child: Center(
                child: Padding(
              padding: const EdgeInsets.all(10.0),
              child: LineChart(),
            )),
          ),
        ],
      ),
    );
  }
}

widget
import 'package:flutter/material.dart';
import 'package:date_range_picker/date_range_picker.dart' as DateRangePicker;
import 'package:flutter_riverpod/flutter_riverpod.dart';

final dateController = Provider((ref) => DatePickModel());

class DateRangeWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return IconButton(
        color: Colors.white,
        icon: Icon(Icons.calendar_today),
        onPressed: () async {
          final List<DateTime> picked = await DateRangePicker.showDatePicker(
              context: context,
              initialFirstDate: context.read(dateController).startDate,
              initialLastDate: context.read(dateController).endDate,
              firstDate: DateTime(2015),
              lastDate: DateTime(DateTime.now().year + 2));
          if (picked != null && picked.length == 2) {
            context.read(dateController).setDates(picked.first, picked.last);
          }
        });
  }
}

class DatePickModel extends ChangeNotifier {
  DateTime _startDate = DateTime.now().subtract(Duration(seconds: 7));
  DateTime _endDate = DateTime.now();

  DateTime get startDate => _startDate;
  DateTime get endDate => _endDate;

  void setDates(DateTime startDate, DateTime endDate) {
    _startDate = startDate;
    _endDate = endDate;
    notifyListeners();
  }

  void resetDates() {
    _startDate = DateTime.now().subtract(Duration(seconds: 7));
    _endDate = DateTime.now();
    notifyListeners();
  }
}

EDIT: Also tried putting widget into a separate ConsumerWidget and no go...
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:linechart/date_range_widget.dart';
import 'package:linechart/linechart.dart';

class LineChartScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          title: AppBarTitle(),
          backgroundColor: Colors.lightBlue,
          actions: [DateRangeWidget()]),
      body: Column(
        children: [
          SafeArea(
            child: Center(
                child: Padding(
              padding: const EdgeInsets.all(10.0),
              child: LineChart(),
            )),
          ),
        ],
      ),
    );
  }
}

class AppBarTitle extends ConsumerWidget {
  @override
  Widget build(BuildContext context, ScopedReader watch) {
    context.read(dateController).formatDates();
    final formStart = watch(dateController).startFormatted;
    final formEnd = watch(dateController).endFormatted;
    return Text('INCOME GRAPH --- $formStart - $formEnd');
  }
}

Answer: You need to change the type of your Provider to ChangeNotifierProvider.
A regular provider doesn't know to update when notifyListeners is called as it doesn't subscribe to the provided value.
final dateController = ChangeNotifierProvider((ref) => DatePickModel());

Comment: Hey Alex, when I do this I get the error: type `'Provider' is not a subtype of type 'ChangeNotifierProvider' of 'function result'` As well as the text showing up red because the consumer does not work. Is there something else I'm doing wrong here? Thought this package should be pretty simple even for a greenie.
Comment: Also I should mention that with the Provider version as in my original code, this works i.e. the widget rebuilds to the correct last input date when I hot reload. So everything else works except the Consumer is not rebuilding when the date picker updates the values... ??
Comment: @RobbB Did you restart your app after updating your code?
Comment: I didn't think that would be necessary but it did the trick! I am now getting  an exception `The following assertion was thrown while dispatching notifications for DatePickModel:
setState() or markNeedsBuild() called during build.` Any idea, do i need to create a constructor or initialize the two variables?
Comment: @RobbB It's probably because you are calling `formatDates` in your build method. If you open a new question I could help you there.
Comment: That would be very much appreciated! Thank you for the help so far. Here is the new Q: https://stackoverflow.com/questions/67578010/exception-setstate-or-markneedsbuild-called-during-build


How to use a swing timer to wait 1 second before continuing to execute code?

Question: I literally just want to do the following:
System.out.println("First line");
// wait 1 second
button.setText("newText");

I tried using thread sleep but it doesn't work. I'm trying to understand swing timers but its so needlessly confusing. I just want the code to delay a second.
Further clarification:
public void actionPerformed(ActionEvent e) {

JButton clicked = (JButton) e.getSource();
clicked.setText("you clicked this button");
//timer here for 1 second,like a delay
clicked.setText("");

Comment: *The problem is that i need this timer to execute which is already in the actionListener's code* - and that is your design problem. The code in your ActionListener needs to be split into two. You execute the code up to the first "setText()" statement. Then you start the Timer. When the Timer executes, you invoke the remaining code. So you need the code broken up into two ActionListeners. Post a proper [mre] demonstrating the problem if you need more help.
Comment: does this help? https://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html
Comment: A Swing `Timer` uses a `ActionListener` as callback/observer which is notified when the timer ticks.  Use the `ActionListener`'s `actionPerformed` method to update the state of the UI
Comment: The problem is that i need this timer to execute which is already in the actionListener's code,at a specific spot
Comment: When a button is clicked,a bunch of stuff happens, then the timer should wait 1 second, then update the text of the button.
Comment: First, the problem with your void situation is that your probably tried to assign the Timer instance to a variable `timer` which is not what I did.  The `start()` returns void which was the problem.  But based on your edits. you have a fundamental problem.  You can not run two processes currently in the EDT.  So while you are in the `actionPerformed` method, you won't receive the event from the timer.
Answer: Try it like this.  The first argument is the initial delay of 1000 ms.  Then the ActionEvent object is used to get the creator of the event (the timer) and stop it.
System.out.println("First line");
new Timer(1000, (ae)->{
               button.setText("newText");
               ((Timer)ae.getSource()).stop();
}).start();

Comment: I'm getting a type mismatch: cannot convert from void to timer
Comment: I can't explain it it works for me just fine.  First check your syntax.  Then if that is correct can you edit your question and show the context of how you are using it?  And make certain you don't assign the Timer to anything.  It runs standalone.  That is don't do this `Timer timer =  new Timer(....`


Can anyone here explain Ext.ComponentQuery.query('what here comes?')[0] briefly?

Question: Hello friends I am stuck at a point in sencha touch 2.0.I am creating a screen in my app in which i need to get the checkbox values(checked or unchecked). i am referring this example from sencha documentation,but i am unable to understand how to use Ext.ComponentQuery.query('what here comes?')[0].
EDIT
here's my code:-
Ext.define('MyApp.view.groupList',{
    extend : 'Ext.navigation.View',
    requires: ['Ext.field.Search', 'Ext.TitleBar'],
    alias: "widget.groupList",
    itemId: "gList",
    initialize: function(){
        this.callParent(arguments),
        var checkBox = {
            xtype: 'checkboxfield',
              name : 'all',
            //  label: 'All',
              value: 'all',
              lableWidth: "0",
              width: 1,
              padding: '0 0 15 30',
              checked: false
        };

        var sendBtn = {
                itemId: 'sendBtn',
                xtype: 'button',
                text: 'Send',
                ui: 'action',
                handler: function() {
                    var check = Ext.ComponentQuery.query('navigationview')[0],
                        values = check.getValues();

                    Ext.Msg.alert(null,
                        "Selected All: " + ((values.all) ? "yes" : "no")

                    );
                }
        };

        var topToolbar = {
            xtype : "toolbar",
            title : "Groups",
            docked : "top",
            items: [
                    checkBox,
                    {xtype: 'spacer'},
                  //  searchBtn,
                    sendBtn
            ],
        };
        var list = {
                xtype: "grlist",
                store: Ext.getStore("grStore")
        };

        this.add([list,topToolbar]);
    },

    config: {
        navigationBar: {
            hidden: true,
        },
    }
});

I am getting the following error:-
TypeError: Result of expression 'check.getValues' [undefined] is not a function. at
 file:///android_asset/www/app/view/group_list.js

So please make me understand how Ext.ComponentQuery works with some sample code or tutorial.
Thanx in advance.
Comment: Show us your code, preferably an [SSCCE](http://sscce.org).
Comment: i added code snippet go through it.
Answer: Ext.ComponentQuery accepts 3 types of parameters:

xtype, eg: Ext.ComponentQuery.query('navigationview')
id, eg: Ext.ComponentQuery.query('my-nav-view-id')
attributes, eg: Ext.ComponentQuery.query('navigationview[name="my nav view"]')

No matter which type the param is of, Ext.ComponentQuery.query() always returns an array of matched components. In the example, they add [0] because it's assured that the result array contains only 1 item.
In your code, it seems that you tried to query a component of xtype navigationview, this kind of component does NOT have getValues methods (which is only available to Ext.form.Panel and derived classes). So if you want to retrieve the values, you have to use queries like this:
Ext.ComponentQuery.query('checkboxfield')[0]
Hope it helps.
Comment: ok buddy i made it working with ur help.i put var check = Ext.ComponentQuery.query('#all')[0] and it worked perfectly('all' is the itemId of checkbox).Thanx.
Comment: if getValues() method is not there in navigatiobview how can i get the value of the checkbox?
Comment: i have understand what you have told but the thing is i dont understand how to proceed after Ext.ComponentQuery.query('checkboxfield')[0].Please provide me some code.
Comment: `var check = Ext.ComponentQuery.query('checkboxfield')[0],
                        value = check.getValue();` - does it work?
Comment: ok its working but one thing is happening here that weather i check the checkbox or not it only showing in dialog box is "Selected all:no"
Comment: `console.log(value)`, what did you get?
Comment: hey buddy is there any possibility to get the value of checkbox added in itemTpl.I have the following itemTpl.How can i get its values?                                                        itemTpl: 'checked="checked" /> {groupName}',
Comment: use `Ext.get()` to access your element
Comment: Hey buddy i have no idea how to use Ext.get(),can show me some code snippet?
Answer: Ext.ComponentQuery documentation is here...
It should not be used in this example.
This code would be more resilent and ridiculously faster as wouldn't use a global search method.
var sendBtn = {
            itemId: 'sendBtn',
            xtype: 'button',
            text: 'Send',
            ui: 'action',
            scope: this,
            handler: function() {
                var check = this.down('#checkboxfield'),
                values = check.getValue();
                Ext.Msg.alert(null,
                    "Selected All: " + ((values.all) ? "yes" : "no")
                );
            }
    };

Also I've corrected the code example, the method is getValue()
Note:
I know that this answer is so out of date it's not relevent, however the accepted method is encouraging the use of Ext.ComponentQuery where it's not needed which is simply awful code and has logical code presuming that ui will remain in the same set format.


PHP Notice: Undefined index: step in C:\xampp\htdocs\try1.php on line 30

Question: I am currently learning php for fun. When i was googling aorund, i found this code and wanted to try it. When i typed it, this error came out. I want to know why this error happens and how can i fix it. Thank you in advanced.
Notice: Undefined index: step in C:\xampp\htdocs\try1.php on line 30
<?php
/*
  Description: Body Mass Index Calculator

  Author: Murray Moffatt for A Web 4 U Designs

  Notes: Originally written for use on CarolynGibson.com

  History:
    2003-04-?? : Initial coding.
    2005-02-13 : Remove extra CarolynGibson.com HTML and make
      stand-alone for publishing on WeberDev.com.
    2005-02-16 : Get $step variable from $_POST and add a
      "Go Back" option at the end.
*/
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Body Mass Index</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="author" content="A Web 4 U Designs - www.aweb4u.co.nz">

Body Mass Index (BMI)

<?php
$step = $_POST["step"];
if ($step == "") {
?>

The Body Mass Index (BMI) is a formula used to estimate the proportion
  of your body that consists of fat. It is currently the best guide for
  calculating a healthy weight range for people aged between 20 and 65.

Do you want to work in metric (centimetres and kilograms) or imperial
  (inches and pounds)?

<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" name="unitsForm" id="unitsForm">

      <input name="units" type="radio" value="metric" checked>
        Metric

      <input type="radio" name="units" value="imperial">
        Imperial

      <input type="submit" name="Submit" value="Next ->">
        <input name="step" type="hidden" id="step" value="1">

</form>
<?php
}
if ($step == "1") {
  $units = $_POST["units"];
?>

Type your weight and height measurements into the boxes below:

<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" name="inputForm" id="inputForm">

      Your weight:
      <input name="weight" type="text" id="weight" size="6" maxlength="6">
        <?php if ($units == "metric") echo " kilos"; else echo "pounds"; ?>

      Your height:
      <input name="height" type="text" id="height" size="6" maxlength="6">
        <?php if ($units == "metric") echo " cm (i.e. 177 is 1.77 meters)"; else echo " inches (i.e. 67 is 5 feet 7 inches)"; ?>

      <input name="step" type="hidden" id="step" value="2">
        <input name="units" type="hidden" id="units" value="<?php echo $units; ?>">

      <input type="submit" name="Submit" value="Next ->">

</form>
<?php
}
if ($step == "2") {
  $units = $_POST["units"];
  $weight = $_POST["weight"];
  $height = $_POST["height"];

  if (!IsValidNumber($weight, ".", 2, 1, 999)) {
    echo "
The weight measurement you entered, \"$weight\", is invalid.
";
    echo "Please enter a number between 1 and 999, optionally with up to two decimal places.
";
    echo "For example 90.5 is 90 and a half, 105.25 is 105 and a quarter.
";
    echo "
Please press Back on your browser and try again.
";
    die("");
  }

  if (!IsValidNumber($height, ".", 2, 1, 999)) {
    echo "
The height measurement you entered, \"$height\", is invalid.
";
    echo "Please enter a number between 1 and 999, optionally with up to two decimal places.
";
    echo "For example 90.5 is 90 and a half, 105.25 is 105 and a quarter.
";
    echo "
Please press Back on your browser and try again.
";
    die("");
  }

  if ($units == "metric") {
    $height = $height / 100; // Convert from centimeters to meters
    $bmi = round($weight / ($height * $height), 1);
    $height = $height * 100; // Convert back to centimeters
  } else {
    $heightcm = ($height * 2.54) / 100; // Convert from inches to meters
    $weightkilo = $weight * 0.4536; // Convert from pounds to kilos
    $bmi = round($weightkilo / ($heightcm * $heightcm), 1);
  }
?>

According to your height of <?php echo $height; ?>
  <?php if ($units == "metric") echo "cm"; else echo "inches"; ?>
  and weight of <?php echo $weight; ?>
  <?php if ($units == "metric") echo "kilograms"; else echo "pounds"; ?>
  your Body Mass Index is <?php echo $bmi; ?>.

The answer that you get with this equation is NOT your weight but is
  the factor that is used to establish your healthy weight range.

A Body Mass Index of <?php echo $bmi; ?> indicates that
<?php
  if ($bmi < 20) {
    echo " you are underweight.";
  }
  if ($bmi >= 20 and $bmi <= 24.9) {
    echo " your weight is within the ideal range.";
  }
  if ($bmi >= 25 and $bmi <= 26.9) {
    echo " you are slightly overweight.";
  }
  if ($bmi > 27) {
    echo " you are overweight and at risk of weight-related problems.";
  }
?>

<a href="<?php echo $_SERVER["PHP_SELF"];?>">Go Back

<?php
}

function IsValidNumber($number, $decimal = null, $dec_prec = null, $min = null, $max = null) {
  if (is_array($number)) {
    extract($number);
  }
  $dec_prec   = $dec_prec ? "{1,$dec_prec}" : '+';
  $dec_regex  = $decimal  ? "[$decimal][0-9]$dec_prec" : '';
  if (!preg_match("|^[-+]?\s*[0-9]+($dec_regex)?\$|", $number)) {
    return false;
  }
  if ($decimal != '.') {
    $number = strtr($number, $decimal, '.');
  }
  $number = (float)$number;
  if ($min !== null && $min > $number) {
    return false;
  }
  if ($max !== null && $max < $number) {
    return false; `enter code here`
  }
  return true;
}
?>

Comment: Possible duplicate of [PHP: "Notice: Undefined variable" and "Notice: Undefined index"](http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-and-notice-undefined-index)
Answer: You have to check if the post is having that index.
$step = $_POST["step"];

to
if(isset($_POST["step"]){
    $step = $_POST['step'];
} else {
   $step = "";
}

One liner for above
$step = isset($_POST["step"]) ? $_POST['step'] : "";

Make sure you change in all places where ever you are using the post directly.
Comment: With 7k rep you should know that this is an off-topic question @NiranjanNRaju...why answer this?
Comment: Some refinment: `$step = isset($_POST["step"]) ? $_POST["step"] : "";`
Answer: I don't know why it occurs, but you can hide this notice using
error_reporting(0);

int the starting of your php file.
I've passed 0 in the parameter, since i don't want any error or notice to see in the webpage.
Comment: Wrong! Wrong! And wrong!! If you have an error you shuld resolve the issue, not hide it!!!
Comment: @Cliff, But he asked about fix and i've mentioned just alternative. I also stated that i'm not writing the solution in the starting of my answer
Comment: Sorry but I can't see where you stated this sentence...but again, hiding an error, even if it is only a notice, without a solution to _prevent_ it is not a good practice.


Traçar um gráfico do carregamento e da descarga de um capacitor no MATLAB

Question: Preciso criar um programa que mostra através do plot a carga e a descarga de um capacitor conforme imagens abaixo:

São 3 constantes onde o usuário precisa informar os valores:
C = capacitância;
R = resistência
E = tensão da fonte (exemplo; uma fonte de 20v);
Consegui fazer o gráfico de carga através desse código:
Comment: O que já tentastes?
Comment: Ainda não comecei Renan.
Answer: Caso pretenda fazer o gráfico teórico basta continuar da mesma forma que começou, pedindo os valores e mostrando a figura para um e outro caso. Pode mostrar o resultado na mesma figura ou figuras separadas.
Recomendo usar um tempo t dependente do valor de Tau. Um condensador carrega/descarrega totalmente em 5*Tau, por isso o codigo seguinte mostra figuras sempre ajustadas ao valor de Tau.
<code>C = input ('Digite o valor do condensador (em uF): ')
R = input ('Digite o valor da resistencia (em Ohms): ')
E = input ('Digite o valor da fonte de tensao (em V): ')

C = 10^-6
Tau = R * C;

t = linspace (0,5*Tau,100); %100 amostras de 0 a 5*Tau segundos

figure (1)
hold on
% carga do capacitor
plot (t,E*(1-exp(-t/(R*C))),'b-')

% descarga do capacitor
%figure (2)  %para graficos separados descomente essa linha
plot (t,E*(exp(-t/(R*C))),'r-')
</code>


flutter:: Is there a way to play only one audio file using the audioplayer package?

Question: I saved the audio files in list 'file'. I want to play this audio file using the audioplayers package. I have listed audio files using listview, but I want to play only one selected audio file among multiple audio files. Currently, the entire audio file in the records is played at the same time and an error has occurred.
How can I solve this?
This is part of my code.
class AudioViewer extends StatefulWidget {
  @override
  _AudioViewerState createState() => _AudioViewerState();
}

class _AudioViewerState extends State<AudioViewer> {
  List file = [];
  var audioPath;
  var directory;
  AudioPlayer? audioPlayer;
  bool _isplaying = false;
  var _icon = Icons.play_arrow;
  var _deleteicon = Icons.delete;
  Color _color = Colors.deepOrangeAccent;
  Duration position = Duration();
  Duration duration = Duration(seconds: 1);

  int indexindex = 0;

  @override
  void initState() {
    super.initState();
    getFiles();
    _setupAudioPlayer();
  }

  void getFiles() async {
    directory = (await getExternalStorageDirectory())!.path;
    setState(() {
      file = Directory("$directory").listSync();
    });
    print(file.toString());
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        title: Text(
          "Audio List",
        ),
      ),
      body: Container(
          child: ListView.builder(
            reverse: true,
            itemCount: widget.records.length,
            shrinkWrap: true,
            itemBuilder: (BuildContext context, int index) {
            return Card(
                elevation: 5,
                child: ExpansionTile(
                    title: Text(
                      widget.records[index].path.split('/').last.split(".").first,
                      style: TextStyle(color: Colors.black),
                    ),
                    onExpansionChanged: ((newState) {
                      if (newState) {
                        indexindex = index;
                        setState(() {

                        });
                      }
                    }),
                    children: [
                      Container(
                        height: 100,
                        padding: EdgeInsets.fromLTRB(10,0,10,0),
                        child: Column(
                          children: <Widget>[
                                Row(
                                    children: <Widget>[
                                      Container(
                                        child: IconButton(
                                          iconSize: 40,
                                        onPressed: () {
                                            if (!_isplaying) {
                                              audioPlayer!.resume();
                         setState(() {
                                                _isplaying = true;
                                                _icon = Icons.pause;
                                                _color = Colors.blueGrey;

                                              });
                                            } else {
                                              audioPlayer!.release();
                                              setState(() {
                                                position = new Duration();
                                                _isplaying = false;
                                                _icon = Icons.play_arrow;
                                                _color = Colors.deepOrangeAccent;

                                              });
                                            }
                                          },
                                          icon: Icon(_icon),
                                          color: _color,
                                        ),
                                      ),
                                      Container(
                                        child: IconButton(
                                          iconSize: 30,
                                          onPressed: () {
                                            widget.records[index].delete(recursive: true);
                                            setState(() {
                                              widget.records.removeAt(index);
                                              position = new Duration();
                                            });
                                          },
                                          icon: Icon(_deleteicon),
                                        ),
                                      ),
                                    ]
                                ),

Answer: It seems you have your state variables like _isplaying only once for the whole page/list. You need them per song. This doesn't seem to be a complete example (widget.records seems to be missing) so I cannot really help a lot here.
What you could do, if widget.records contains the songs, is to have a currentlyPlaying variable that is the record that is currently playing, instead of just a generic _isplaying. This way, you could figure out if the currectly build list entry is actually playing or not. But then maybe I'm misunderstanding something, since your audioplayer is not actually playing that song, it just resumes whatever it was playing before.
Maybe start out with easy steps and first make the icon work. That should be possible with the method I mentioned above: keep track of which record was selected.
Answer: You need to create a globals.dart file like that:
AudioPlayer? _player;

Future<void> playAudio(AudioPlayer player, AudioSource source) async {
    if (_player != null && _player!.playing) {
      await _player!.stop();
    }
    _player = player;
    player.setAudioSource(source);
    player.play();

}
And use it in somewhere:
playAudio(currentAudio, audioSource);


Centralização perfeita de elementos usando o transform:translate

Question: Em uma outra pergunta que fiz antes, um usuário me deu um exemplo de como eu poderia deixar perfeitamente centralizado um botão html na tela.
Foi nesta pergunta: Como posicionar um button em qualquer lugar da tela, em html
Ele simplesmente fez:
#centralizar{
    position:absolute;
    top:50%;
    left:50%;
    transform: translate(-50%, -50%)
}

Só que eu tentei centralizar três botões abaixo, partindo do mesmo padrão, mas não funciona...
Pelo que eu vi na doc, o translate muda a posição de um objeto na tela a partir da multiplicação da matriz de posição do objeto por um vetor. Nesse caso, preciso ter a informação da posição em pixels pra poder fazer esse cálculo, e ter uma ideia de qual o valor de translate aplicar, certo? Ou tem um jeito mais fácil.
Segue o meu código:
<!DOCTYPE html>

       <button >A</button>

     <button>B</button>

       <button>C</button

Comment: Você inventou um "=" na declaração que não existe. Leia a documentação e exemplos existentes aos montes - Estamos aqui para tirar dúvidas, mas é bom ao menos dar uma lida na documentação, sem tentar "no chute" e já perguntar.
Comment: Não percebi isso. Eu estava usando dois exemplos, e não percebi o "igual instruso".
Comment: Aproveite e acrescente um tamanho numa div mais externa, para ver melhor o efeito. Se conseguir resolver, pode publicar no campo abaixo a solução, para poder fechar a pergunta. Eu até pensei em postar uma resposta com o código corrigido, mas não sei ao certo como é o resultado pretendido. Um exemplo do que quer (em imagem, por exemplo, ou uma descrição do resultado) ajudaria.
Comment: Apareceu outro problema. Bou editar  a pergunta
Comment: Publiquei um modelo básico mais simplificado como ponto de partida.
Answer: Seguem algumas correções e simplificações, em "ordem de aparição":

Removido o erro de sintaxe da pergunta original, tinha um = sobrando nas declarações;
Adicionada largura, altura, e removidas as margens do body e html para a página ocupar a área visível;
Adicionado relative ao body para acomodar a base para o absolute dos filhos (na verdade, isso é importante quando se trata de div dentro de div;
Centralizada apenas uma div, já com os 3 botões;
Fechada a tag ;
Simplificada a div que contém os botões;

<!DOCTYPE html>

      <button>A</button>
      <button>B</button>
      <button>C</button>

Comment: eu passei coordenadas pra div que está fora deles. Eles se "ajeitam" dentro dessa div. Pensando de outra forma: você não quer posicionar CADA botão, e sim um conjunto deles. Para isso, uma div em volta. - Experimente aumentar ou diminuir o número de botões, por exemplo pondo 9 botões com um  a cada 3 deles e vai ver que sempre centraliza - e centraliza no 100% que eu pus no body
Comment: Em línguas ocidentais é da esquerda pra direita, mas se vc quebrar com  vai continuar centralizado. Virou uma "caixa elástica" como fizemos
Comment: Um bom exercício é você começar do HTML puro, e ir pondo cada regra do CSS que eu coloquei pra ver o efeito isolado de cada uma
Comment: Entendi. Mas se você passou para os três botões as mesmas coordenadas da tela, como eles não ficaram sobrepostos?
Comment: Ah, claro. Então por padrão, a div "enfilera" os elementos contidos nela da esquerda para direita?
Answer: Não é possível utilizar mais de um id em um elemento, e por definição, um ID não deve se repetir em mais e um elemento em todo documento HTML, deve ser um identificador único para aquele elemento.
Para chegar neste resultado, você pode utilizar as classes (atributo class), onde é permitido utilizar mais de uma classe em um elemento e reutilizar a classe em mais de um elemento.
Seguindo seu exemplo:

.centralizado1 {
  position:absolute;
  top: 46%;
  left: 50%;
  transform: translate(-46%, -50%)
}
.centralizado2 {
  position:absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -30%)
}
.centralizado3 {
  position:absolute;
  top: 54%;
  left: 50%;
  transform: translate(-54%, -10%)
}
<!DOCTYPE html>

   <button>A</button>

    <button>B</button>

    <button>C</button>

    <button>C</button>


C++ setting a value to a enum item inside a class

Question: my name is Josh and I am trying to make this code work but I could achieve nothing so far...
Sorry if It is silly and I am wasting your time, I am new to C++ (which I already love), Let me try to explain.
Basicaly what I want to do is insert a enum into a class, set a value to an iten from the enum(class maybe), but I can't access the item to set a value...
eg. Edge of Fight - 24 Physical Damage / 54 Movement Speed / 5 Ability Power.
Sorry for the bad English, it is not my main language...
#include <iostream>

using namespace std;

class Enemy {
protected:
    int physicalDamage;
    double moveSpeed;
    int abilityPower;
public:
    void setPhysicalDamage(int p) {
        physicalDamage = p;
    }
    void setMoveSpeed(int m) {
        moveSpeed = m;
    }
    void setAbilityPower(int ap) {
        abilityPower = ap;
    }

    virtual void attack() = 0;
    virtual void ability() = 0;
    virtual void speed() = 0;

};

class Itens: public Enemy {
protected:
    enum class itensID {
        gunnersBreaker,
        hitswamSword,
        fineshotsWrath,
        banesBook,
        infinityStar,
        edgeOfFight,
    };

    itensID iID;
public:

    void setItensID(int r) {

        iID.edgeOfFight = r; // Gives me error, I don't really know a way                 around that...
    };                      // But basically what I wanna do is marked in     double slashes...
                           // I don't know if I should use pointers for     that, but I tried and it also didn't work...

};

class Ninja : public Enemy {
public:
    void attack() {
        cout << "Hero: Ninja." << endl;
        cout << "Physical Damage:  " << physicalDamage << endl;
    }
    void ability() {
        cout << "Ability Power: " << abilityPower << endl;
    }
    void speed() {
        cout << "Movement Speed: " << moveSpeed << endl;
    }
};

class Monster : public Enemy {
public:
    void attack() {
        cout << "Hero: Monster." << endl;
        cout << "Physical Damage:  " << physicalDamage << endl;
    }
    void ability() {
        cout << "Ability Power: " << abilityPower << endl;
    }
    void speed() {
        cout << "Movement Speed: " << moveSpeed << endl;
    }
};

int main() {
    Ninja n;
    Monster m;
    Enemy *e1 = &n;
    Enemy *e2 = &m;

    /*

        Find a way to set an enum item to the Ninja hero

                                                            */

    e1->setPhysicalDamage(203);
    e1->setAbilityPower(12);
    e1->setMoveSpeed(321.32);
    e2->setPhysicalDamage(40);
    e2->setAbilityPower(654);
    e2->setMoveSpeed(310.44);

    n.attack();
    n.ability();
    n.speed();
    m.attack();
    m.ability();
    m.speed();
}

I've updated the code, but got a error that I am cracking my head trying to fix it. I'll explain what I am trying to do now.
I want the problem to update Hero's current pd,ap,ms with the addition of the gunnersBreak item
UPDATED CODE!
#include <iostream>
#include <string>

using namespace std;

struct itensID {
    void gunnersBreaker(int pd, int ap, float ms);
    void hitswamSword(int pd, int ap, float ms);
    void fineshotsWrath(int pd, int ap, float ms);
    void banesBook(int pd, int ap, float ms);
    void infinityStar(int pd, int ap, float ms);
    void edgeOfFight(int pd, int ap, float ms);
};

void itensID::gunnersBreaker(int pd, int ap, float ms)
{
    int physicalDamage = pd;
    int abilityPower = ap;
    float moveSpeed = ms;

    cout << "\n Shotgun: Gunner's Break " << endl;
    cout << "\n Stats:";
}

void itensID::hitswamSword(int pd, int ap, float ms)
{
}

void itensID::fineshotsWrath(int pd, int ap, float ms)
{
}

void itensID::banesBook(int pd, int ap, float ms)
{
}

void itensID::infinityStar(int pd, int ap, float ms)
{
}

void itensID::edgeOfFight(int pd, int ap, float ms)
{
}

class Enemy {
protected:
    int physicalDamage;
    int abilityPower;
    float moveSpeed;

public:
    void setEnemyStatus(int p, int a, float m) {
        physicalDamage = p;
        abilityPower = a;
        moveSpeed = m;
    }

    virtual void attack() = 0;
    virtual void ability() = 0;
    virtual void speed() = 0;

};

                             // Basically what I wanna do now is, add two or     three values to the items eg. gunnersBreaker (int pd, int ap & float ms)
                            // Since I am struggling to get this going, I     have decided to set them as string, just to print while I figure-
                           // out how to add multiple values for a item in a     structure, maybe I should make them a void function instead-
                          // of a regular variable? (I would discard this     since regular variables takes only one identifier, I guess)
                         //  or should I make it a class instead?

class Ninja : public Enemy {
public:
    void attack() {
        cout << "Hero: Ninja." << endl;
        cout << "Physical Damage:  " << physicalDamage << endl;
    }
    void ability() {
        cout << "Ability Power: " << abilityPower << endl;
    }
    void speed() {
        cout << "Movement Speed: " << moveSpeed << endl;
    }
};

class Monster : public Enemy {
public:
    void attack() {
        cout << "Hero: Monster." << endl;
        cout << "Physical Damage:  " << physicalDamage << endl;
    }
    void ability() {
        cout << "Ability Power: " << abilityPower << endl;
    }
    void speed() {
        cout << "Movement Speed: " << moveSpeed << endl;
    }
};

int main() {
    Ninja n;
    Monster m;
    Enemy *e1 = &n;
    Enemy *e2 = &m;
    itensID iID;

    /*
        on the lines below ptr1 and ptr2, I got kind of an error,
        I got to find a way to calculate the Enemy Status with the addition     of the item specs
        and print out the item I am using, EG. Hero: Ninja!
                                             Weapon: Gunner's Breaker.
                                             Stats.... and so on...
                                                                                */

    e1->setEnemyStatus(35,10,310.21) + iID.gunnersBreaker(33,11,32.32); //     ptr1
    e2->setEnemyStatus(54,65,235.30);                                  //     ptr2

    n.attack();
    n.ability();
    n.speed();
    m.attack();
    m.ability();
    m.speed();
}

Comment: [Off Topic] Why does Item derive from enemy?  An item shouldn't be an enemy.
Comment: [On Topic] Why not make the enum global, or at least public, so you can have the enumeration passed to the function instead of an `int`?
Comment: [Off Topic] maybe its a cursed sentient object.  Forget it, he's rolling.
Comment: It seems that `class` becomes very confusing when used with `enum`. `edgeOfFight` and other enum items are not class fields and it is not possible to assign anything to them.
Comment: [On Topic] why not `void setItensID( intensID r )`   ?
Comment: @Ghosterrify No, there is no access right to worry about.  You cannot assign to an  enumeration value, only an enumeration object.  `itensID foo = itensID::gunnersBreaker;` is OK.  `itensID::gunnersBreaker = itensID::edgeOfFight` will be a compiler error.
Comment: @infixed I'll do that, but maybe i'll have to work this program from the ground, seems confusing for me... Atleast for what I want to do, eg. Have an item, set pd,ms,ap and be able to use the item on a hero, thanks for the help everyone, I really appreciate!
Comment: @NathanOliver, Thanks, it looks better as a global enum, in a class it was really a mess, I gotta get more into enums, i'll have to find a way to work around it, maybe using normal classes with variables instead of enum items?... Thanks again for the help!
Comment: @VTT, I guess I have to make a normal class and add a bunch of itens in there? I'll look forward to do that and see the outcome, thanks or the help by the way!
Comment: @NathanOliver, sorry to bother you, I have updated the code, I don't know if I should toggle it as unsolved since the problem is solved, but here I go again annoying you :( sorry
Answer: It's because you are trying to use your enum like struct and assign value to one of its element. enums are list of named values which can be used to represent some values (like i.e. flags or states) that are unhandy and/or unsafe to represent by arithmetic types.
Your itensID iID is a variable of your itensID enum class type, so you can assign to it one of named values which you listed in itensID enum class body (i.e. iID = itensID::edgeOfFight).
Comment: thanks! I am going to make some changes on the code, I will have to check some struct forms to get those itens working, again, thanks for the help, I really appreciate!
Comment: sorry to bother you, I've updated the code... Could you take a look at it ? I need some help :(
Comment: thankyou for answering, I thought I had a good base to start a program of that type, but it seems that I am not even close... By the way, thanks for the suggestion, i'm going to start reading the book right now!


How do you calculate multiple objects values in a list

Question: I'm trying to add the sum of objects from a database but so far I have found no success
test = [{'shares': 5}, {'shares': 1}]
# print sum of the two shares (5+1=6)

I've tried to use test['shares'] to print but it results in the error:

list indices must be integers or slices, not str

I've tried sum(test.value())but creates the error

'list' object has no attribute 'values'

And sum(test)creates:

unsupported operand type(s) for +: 'int' and 'dict'

It seems like the objects are wrapped in a list but I do not know how to unwrap it?
Comment: Please note the conventions for formatting [How do I format my posts using Markdown or HTML](http://stackoverflow.com/help/formatting). See my edits please.
Answer: One nice way would be
sum(x['shares'] for x in test)

Why does this work?
Given a dictionary d = {'shares': 7}, then to get the value 7, you call d['shares'].
You want to do that for each dictionary in the list test, so you want to look at x['shares'] for each x in test.
In Python, the function sum can accept something called a "generator expression", which is what we did here.
Comment: Thanks! Seems like this solves all my questions, especially given how there are so many shares in the database to process. Thanks!
Answer: You have a list of dictionary. You have to select the number of dictionary from the list and then use the key to access the value like that :
test[0]['shares']

Next time you can find it on internet easily ...
Answer: test is a list. You want to access its elements by index:
print(test[0]['shares'] + test[1]['shares'])

Or, if you have many object in that list:
print(sum( x['shares'] for x in test ))

Or
s = 0;
for elm in test:
    s += elm['shares']
print(s)

Answer: You are putting your data in a list and using it as dictionary better structure it like.
{'shares': [5, 1]}.
Comment: What to do :),  and also you can calculate the shares like `sum(map['shares'])`
Answer: with below code you can some up all the object values even if its different
test = [{'shares': 5}, {'shares': 1}]

total = 0
for each in test:
  for i in each:
    total += each[i]

print(total)


Looking for a reference for this matrix inequality

Question: Does anyone know the name of this following equation or where it is from?

For any given $x,y \in \mathbb{R}^n$, and matrices $P>0$, $D$ and $S$ of appropriate dimensions, one has
  \begin{equation}
2x^TDSy \leq x^T DPD^T x + y^T S^TP^{-1}Sy.
\end{equation}

I read that in one paper but the author does not give any specific instruction. Then I am supposed to think that should be a regular equation in matrix theory. But I check the book about matrix theory without any finding. Could you help me to identify what it is?
Answer: This is a quadratic form of the subtraction as $(x^TD\sqrt{P}-y^TS^T\sqrt{P^{-1}})(x^TD\sqrt{P}-y^TS^T\sqrt{P^{-1}})^T\geq 0$ where $\sqrt{P^{-1}}$ and $\sqrt{P}$ exist due to the fact that $P\geq 0$.
Comment: Why is it downvoted?


tb mega menu is not showing in bootrap theams in drupal7

Question: I am new user of drupal 7.3. I am using bootstrap 3.0 theme in drupal 7.3.
I am using tb mega menu which is not showing. Black color box will be occurred in navigation block.
Please help me to solve this I want solution step by step. I want used in my project please help me.
Comment: https://groups.drupal.org/node/301648
Answer: I have refer you to below links :

LINK1
LINK2
LINK3
Comment: Compile the LESS files

Compile the LESS files to create your style.css, which contains all of the Bootstrap CSS , Drupal-specific overrides (overrides.less), and your own custom code.

lessc less/style.less > css/style.css

this is solution of tb mega menu problem .but actually i don't know how to compile this file.please help me
Comment: Compile the LESS files .Compile the LESS files to create your style.css, which contains all of the Bootstrap CSS , Drupal-specific overrides (overrides.less), and your own custom code.lessc less/style.less > css/style.css.how to solve this step i don't know.plese help me


How to store date and time from java to the database

Question: I am developping in Android Studio an apps and I need to implement a meeting , so i Use TimePickerDialog and CalenderView to add the date and the time . I want to retreive this 2 informations and store them in myDB .
1- How could I store date from CalendarView to Date class in Java and the same for timePicker.
2-How to insert date from java Class into SQLite and the same for time.
This is my code
RDV_Activity
   CalendarView cv ;
   TextView showTime;
   TimePickerDialog timePicker;
   EditText heure,titre;
   Time time ;
   Date d;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_rdv);

   showTime= (TextView) findViewById(R.id.showTime);
   cv= (CalendarView) findViewById(R.id.cv);
   btn_ajouter = (Button) findViewById(R.id.btn_ajouter);
   heure = (EditText) findViewById(R.id.heure);
   cv.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
     @Override
     public void onSelectedDayChange(@NonNull CalendarView view, int
   year, int month, int dayOfMonth) {
         String date = dayOfMonth + "/" + (month + 1) + "/" + year ;
         d= new Date(year,month,dayOfMonth);
         System.out.println(d.toString());
     }
    });
   heure.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
         final Calendar calendar = Calendar.getInstance();
         final int hour = calendar.get(Calendar.HOUR);
         int minute = calendar.get(Calendar.MINUTE);

         timePicker = new TimePickerDialog(Rdv.this, new
    TimePickerDialog.OnTimeSetListener() {
             @Override
             public void onTimeSet(TimePicker timePicker, int
   selectedHour, int selectedMinute) {
                 showTime.setText( selectedHour + ":" +
       selectedMinute);

             }
         }, hour, minute, true);
         timePicker.setTitle("Choose time");
         time.setHours(hour);
         time.setMinutes(minute);
         System.out.println(""+time.getHours());
         System.out.println(""+1);
         timePicker.show();
         showTime.setText(heure.getText());

     }
     });
   titre = (EditText) findViewById(R.id.titre);

    RDV r = new RDV(d,time,titre.getText().toString());

   }

    }

RDV Class
     private final int idR;
     private  int cpt=0;
     private Date dateR;
     private Time heure ;
     private String titre ;

     public RDV(Date dateR, Time heure, String titre)
    {
        this.dateR = dateR;
        this.heure = heure;
        this.titre = titre;

           cpt++;
        idR = cpt;
              }

DB
   String CREATE_TABLE_RDV = "CREATE TABLE " + table_Rdv + " (" + ID_R + "
   INTEGER PRIMARY KEY AUTOINCREMENT, "+ TITRE +
        " VARCHAR NOT NULL, " +DATE_R+ " Date NOT NULL, " +HEURE_R+ "
    Time NOT NULL, " +ID_F+ " INTEGER NOT NULL ,"+
        " CONSTRAINT FK1 FOREIGN  KEY ( " +ID_F+") REFERENCES
   "+table_Femme+"("+ID_F+") )";
   db.execSQL(CREATE_TABLE_RDV);

  public void insererRdv(RDV r)
     {
   SQLiteDatabase db = this.getWritableDatabase();
   ContentValues vals = new ContentValues();

   vals.put(TITRE,r.getTitre());
   vals.put(HEURE_R,r.getHeure().toString());
   vals.put(DATE_R ,r.getDateR().toString());

   db.insert(table_Rdv,null,vals);
   db.close();

  }

Thank you .
Comment: Duplicate of https://stackoverflow.com/q/218384/6296561
Comment: @Monir did you read that stack trace you posted? Do you not understand how that's relevant to the post your question keeps being closed as a duplicate of?
Comment: What exactly is your question? I see much code, but not a specific problem. Exchanging date and time between Java and a database have covered many many times already. How have all the thousands of existing posts here not addressed your issue? How is your Question here distinct? Always search Stack Overflow before posting.
Comment: Use one of the formats listed here: https://www.sqlite.org/lang_datefunc.html
Comment: Also didn't you already ask this earlier today and have it closed as a duplicate?
Comment: It's not the same error that's why i reposted . You should read the question not only the title Mr Zoe
Comment: So could you stop telling me it's duplicate I've written 3 different question and still not having an answer from you , you keep telling me it's duplicated and it's not so please just take a look .
Comment: @Shawn i don't know why it keeps being closed as a duplicate it's not only about null pointer I was asking how to retreive the date and time ? I've 3 questions about how to use date and time class
Comment: Date and time are nothing but integers(mostly). You can store their state in integer form. To retrieve, simply get an instance of a calendar and load it up with the read values from DB?
Comment: @TaseerAhmad I have to store in the DB , and how to store a date in integer form ? I was asking how to retreive the information of the CalenderView and store it into Date Class
Comment: @Basil Bourque I've searched before and didn't found any solution. You could just read the two questions and then judge my post.
Comment: So to be clear , my problem is how to convert date from the calendar view to a date class ? And from TimePicker to time ? Then Store this 2 informations into my DB and the code is for helping to specify my need . Thank you all of you friends and sorry if my questions wasn't clear . If I've found a solution to my problem I wouldn't post it but It has been two days that I searched and no solution. Thank you . Maybe I didn't search well.
Answer: Here's a Working example based upon your code:-
Which utilises the Calendar and the SimpleDateFormat classes to save the date and time in a single column both as a long (the more efficient way i.e. takes less space) and also as a String. BOTH are compatible with the SQLite Date and Time functions so date/time manipulations are a breeze as is returning dates and time in virtually any format you want.
The DatabaseHelper
public class DBHelper extends SQLiteOpenHelper {

    public static final String DBNAME = "mydb";
    public static final int DBVERSION = 1;

    public static final String table_Rdv = "rdv";
    public static final String ID_R = BaseColumns._ID;
    public static final String TITRE = "titre";
    public static final String DATE_R ="date_r";
    public static final String HEURE_R = "heure_r";
    public static final String ID_F = "id_f";
    public static final String DATETIMELONG = "datetimelong";
    public static final String DATETIMESTRING = "datetimestring";

    public DBHelper(Context context) {
        super(context, DBNAME, null, DBVERSION);
        this.getWritableDatabase();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        String CREATE_TABLE_RDV = "CREATE TABLE " + table_Rdv + " (" +
                ID_R + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                TITRE + " VARCHAR NOT NULL, " +
                DATE_R+ " Date NOT NULL, " + //<<<<<<<<<< Column Not needed
                HEURE_R+ " Time NOT NULL, " + //<< Column not needed
                // Note only one of the two following columns are needed
                // Using SQLite date and time functions you can do very much what you want
                //         see https://www.sqlite.org/lang_datefunc.html
                DATETIMELONG + " INTEGER, " + //<<<<<<<<<< Column will hold both date and time as long
                DATETIMESTRING + " TEXT, " + //<<<<<<<<<< Column will hold both date and time as String YYYY-MM-DD HH:MM
                ID_F+ " INTEGER NOT NULL " +
                //", CONSTRAINT FK1 FOREIGN  KEY ( " + ID_F + ") REFERENCES "+ table_Femme + "("+ID_F+") " + // Commented out for demo
                ")";
        db.execSQL(CREATE_TABLE_RDV);
    }

    public long addRDVRow(String titre, long datetimelong, String datetimestring) {
        ContentValues cv = new ContentValues();
        cv.put(TITRE,titre);
        cv.put(DATE_R,"NOTHING NEEDED HERE AS NOT USED");
        cv.put(HEURE_R,"NOTHING NEEDED HERE AS NOT USED");
        cv.put(DATETIMELONG,datetimelong);
        cv.put(DATETIMESTRING,datetimestring);
        cv.put(ID_F,0); //<<<<<<<<<< as no fk constraint anything will do for demo so 0
        SQLiteDatabase db = this.getWritableDatabase();
        return db.insert(table_Rdv,null,cv);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

The activity :-
public class MainActivity extends AppCompatActivity {

    CalendarView cv;
    TimePickerDialog timepicker;
    TextView showtime;
    TextView showdatetime; //<<<<<<<<<< ADDED for demo
    Button btn_ajouter;

    Calendar cal;
    SimpleDateFormat sdfFull = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm");
    int mYear,mMonth,mDay,mHour,mMin;

    DBHelper mDBHlpr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mDBHlpr = new DBHelper(this);

        cv = this.findViewById(R.id.cv);
        cal = Calendar.getInstance();

        showtime = this.findViewById(R.id.showtime);
        showdatetime = this.findViewById(R.id.showdatetime);
        btn_ajouter = this.findViewById(R.id.btn_ajouter);
        handleDateTime(); // set to show current date time
        handleDate(); // Handle the Calendar View
        handleTime(); // Handle the TimePicker

        btn_ajouter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDBHlpr.addRDVRow("Whatever",cal.getTimeInMillis(),sdfFull.format(cal.getTime())); //<<<<<<<<<< Add new row to db

                //for demonstration
                DatabaseUtils.dumpCursor(
                        mDBHlpr.getWritableDatabase().query(
                                DBHelper.table_Rdv,
                                null,null,null,null,null,null
                        )
                );
            }
        });
    }

    public void handleDate() {
        cv.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
            @Override
            public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
                mYear = year;
                mMonth = month;
                mDay = dayOfMonth;
                handleDateTime();
            }
        });
    }
    public void handleTime() {
        showtime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                timepicker = new TimePickerDialog(v.getContext(), new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        mHour = hourOfDay;
                        mMin = minute;
                        handleDateTime();
                    }
                },mHour,mMin,true);
                timepicker.setTitle("Pick Time");
                timepicker.show();
            }
        });
    }

    private void handleDateTime() {
        cal.set(mYear,mMonth,mDay,mHour,mMin);
        showtime.setText(sdfTime.format(cal.getTime()));
        showdatetime.setText(sdfFull.format(cal.getTime()) + " or as long " + String.valueOf(cal.getTimeInMillis())); // SQL YYYY-MM-DD HH:MM format
    }
}

Result
The app looks like :-

After clicking OK the TextViews show :-

After Click the Button then the row is added and shown in the log e.g. (2nd row, first was added previously)

05-01 11:17:40.282 23152-23152/q.so55927409 I/System.out: >>>>> Dumping cursor android.database.sqlite.SQLiteCursor@a40a2ab
05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out: 0 {
05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out:    _id=1
05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out:    titre=Whatever
05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out:    date_r=NOTHING NEEDED HERE AS NOT USED
05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out:    heure_r=NOTHING NEEDED HERE AS NOT USED
05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out:    datetimelong=-125838902353924
05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out:    datetimestring=2019-05-16 15:20
05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out:    id_f=0
05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out: }
05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out: 1 {
05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out:    _id=2
05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out:    titre=Whatever
05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out:    date_r=NOTHING NEEDED HERE AS NOT USED
05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out:    heure_r=NOTHING NEEDED HERE AS NOT USED
05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out:    datetimelong=-125838880753924
05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out:    datetimestring=2019-05-16 21:20
05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out:    id_f=0
05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out: }
05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out: <<<<<

Comment: Thank u very much
Comment: good afternoon How can I store each one in variable ? Not at the same ? Thank you
Comment: If you look that's already done the one value "the date" is used to get the date and also the time via SimpleDateFormat's for the display e.g. `showtime.setText(sdfTime.format(cal.getTime()));`


Package.json variable not being picked up

Question: I have the following functionality that locally loads some products out of stock depending on the command run in the terminal:
const updates = process.env.option === "oos" ? oosUpdates : insUpdates
log.info("updates: ", JSON.stringify(updates))
const result = await loadUpdateVariants(cache, updates as UpdateType[])

In my package.json I have:
"update:oos": "ts-node src/loaders/mock/update-variants.ts --option oos",
"update:ins": "ts-node src/loaders/mock/update-variants.ts --option ins"

however when I run yarn update:oos I am getting the instock products meaning that this process.env.option === "oos" is not working out correctly.
Comment: Does this answer your question? [Sending command line arguments to npm script](https://stackoverflow.com/questions/11580961/sending-command-line-arguments-to-npm-script)
Comment: Doesn't `--option` go on `process.argv` and not `process.env`?
Answer: process.env gives you access to environment variables. If you want to use environment variables, you can set them like this:
"update:oos": "OPTION=oos ts-node src/loaders/mock/update-variants.ts",
"update:ins": "OPTION=ins ts-node src/loaders/mock/update-variants.ts"

This is the "vanilla" (without any extra dependencies) approach - but may encounter issues on Windows. If you want your command to work well cross-platform, you might consider using cross-env
Comment: Don't set environment variables like that, it isn't supported properly cross platform. Use `cross-env` instead.
Comment: Good point, thanks, I have added in a note to the answer about that.


Regions missing on page templates defined in a controller

Question: I have two custom blocks that I created in files placed in the modules/custom/mymodule/src/Plugin/Block folder.
I defined two extra regions in the mytheme.info.yml file
I placed the blocks in the regions using the 'Block layout' page in the admin area.
It's all working great on all pages that use the "normal" twig template naming conventions, such as page.html.twig, page--front.html.twig and other templates I created based on the suggestions in the comments twig debug outputs.
My problems started when I created templates via a Controller. Here is an example from my routing.yml file:
mytheme.bikes:
  path: '/catalog/Bikes'
  defaults:
    _controller: '\Drupal\mytheme\Controller\MyPageController::catalog_bikes'
    _title: 'Bikes'
  requirements:
    _permission: 'access content'

And the controller:
public function catalog_bikes() {
  return array(
    '#type' => 'page',
    '#theme' => 'page__bikes',
  );
}

If i go on mysite.com/catalog/Bikes the page--bikes.html.twig template is loaded, BUT, without the extra regions I added to mytheme.info.yml file
Answer: Are you rendering the regions in your twig template?
Like
{{ page.custom_region }}

Comment: yes I am doing exactly that
Answer: You've got a fundamental misunderstanding here on how the controller will work. When you return a response from a controller, it becomes the content on that page. You cannot assign the template for the page in your controller. If you want to use page--bikes.twig.html on that path, then you need to implement hook_theme_suggestions_HOOK_alter(), using the current path to determine the template suggestion(s):
hook_theme_suggestions_HOOK_alter(array &$suggestions, array $variables)
{
  $current_path = \Drupal::service('path.current')->getPath()
  $path_args = explode('/', $current_path);
  // Check if we are on a catalog path, and that there is an
  // specific element on that page
  if($path_args[0] == 'catalog' && isset($path_args[1]))
  {
    $suggestions[] = 'page__catalog__' . $path_args[1];
  }
}

This will allow you to use page--catalog--bikes.twig.html if you are on the /catalog/bikes page. I would suggest using 'catalog' as part of the template name, to prevent potential collisions with other modules.
Comment: I did what I did based on another thread I found on SE yesterday.. I tried what you suggested and while the template does load I still don't get the extra regions.


Is it possible to find infinitely many computable and non-computable functions that provide the following conditions?

Question: Let,

a) $f:\mathbb{N}\longrightarrow \left\{0,1,2 \right\}$ or a sequence  $f(n):= x_n$ where $x_n\in \left\{0,1,2\right\}$ and $g:\mathbb{N}\longrightarrow \left\{0,1,2 \right\}$ or a sequence $g(n):= y_n$ where $y_n\in \left\{0,1,2\right\}$
b)  $f:\mathbb{N}\longrightarrow \left\{0,1 \right\}$ or a sequence  $f(n):= x_n$ where $x_n\in \left\{0,1\right\}$ and $g:\mathbb{N}\longrightarrow \left\{0,1 \right\}$ or a sequence $g(n):= y_n$ where $y_n\in \left\{0,1\right\}$

Question-1.

Is it possible to find such non-trivial functions $f(n)$ and $g(n)$, which gives

$\qquad$ $\qquad$ $\displaystyle \lim_{k \to \infty }\dfrac{\displaystyle \sum_{n=1}^{k} \left(m^n \times f(n)  \right)}{\displaystyle \sum_{n=1}^{k} \left(m^n \times g(n)  \right)}=\infty$ $\qquad$  and $\qquad$ $\displaystyle \lim_{k \to \infty }\dfrac{\displaystyle \sum_{n=1}^{k} \left(m^n \times g(n)  \right)}{\displaystyle \sum_{n=1}^{k} \left(m^n \times f(n)  \right)}=0$
where, $m\in\mathbb{Z^{+}}, m \geq 3.$

Or without a unique limit point:

$\qquad$ $\quad$ $\displaystyle \lim_{k \to \infty }\text{sup}\dfrac{\displaystyle \sum_{n=1}^{k} \left(m^n \times f(n)  \right)}{\displaystyle \sum_{n=1}^{k} \left(m^n \times g(n)  \right)}=\infty$ $\qquad$  and $\quad$ $\displaystyle \lim_{k \to \infty }\text{inf}\dfrac{\displaystyle \sum_{n=1}^{k} \left(m^n \times g(n)  \right)}{\displaystyle \sum_{n=1}^{k} \left(m^n \times f(n)  \right)}=0$
where, $m\in\mathbb{Z^{+}}, m \geq 3.$

For example let, $f(n)$ and $g(n)$ be constant functions, where $g(n)=0$ and $f(n)=1$ or $f(n)=2$ which works.
But, I`m looking for a non-constant or non-trivial functions which provide the conditions of the problem. How can I find such  functions?
But, we can choose infinitely many computable functions, for example $f(n)= n\mod3$ $\quad$ and $g(n)=n^2 \mod3 $   which doesn`t work. In fact, it is much easier to find such functions!
Then, I have $2$ more short questions.

Question-2.

Is it possible to find infinitely many computable and non-computable functions that provide these conditions?

Question-3.

Is it possible to find such functions $f(n)$ and $g(n)$ which given by a unique mathematical formula?

This question is related to the question I asked before.
But, the new question is different and expressed  more detailed here.
Thank you!
Answer: Let Z, be the set of functions from $\mathbb N$ to $\{0,1,2\}$ such that they are ultimately zero constant $$g\in Z \Leftrightarrow \exists N,\forall n\ge N, g(n)=0$$
Then you can easily prove that $f$ and $g$ verify the limits if and only if $g\in Z$ and $f\notin Z$.
Hence, as $Z$ contains only recursive functions, $g$ must be recursive. However, $f$ can be recursive or not.


How can I write users table data in custom file?

Question: I have a number of users in my site,I have developed custom module for drupal mail functionality.
But I want to write test cases for custom module.
then here is the problem is how can I get the (db_select) users table data and write down in .test file.
for example in .module file we use like this:
$select = db_select('{users}', 'users');
$select -> addField('users', 'name', 'users_name');
$select -> addField('users', 'uid', 'uid');
$select -> addField('users', 'mail', 'users_mail');
$select -> addField('users', 'created', 'users_created');
$select -> addField('users', 'access', 'users_access');
$select -> addField('user_relationships', 'requester_id', 'requester_id');
$select -> addField('users_roles', 'rid', 'role_id');
$select -> addField('users_user_relationships', 'mail', 'users_user_relationships_mail');
$select -> leftjoin('user_relationships', 'user_relationships', "users.uid=user_relationships.requestee_id");
$select -> leftjoin('users', 'users_user_relationships', "user_relationships.requester_id=users_user_relationships.uid");
$select -> innerjoin('users_roles', 'users_roles', "users.uid = users_roles.uid");
$select -> condition('users.status', 0, '<>');
$select -> condition('users_roles.rid', array(
  '4',
  '5'
), 'IN');
$subresult = $select -> execute();

and i have wrote .test file like this
<?php
class BiTestMailsTests extends DrupalWebTestCase {
protected $privileged_user;
public static function getInfo() {
  return array(
    'name' => 'Test Mails',
    'description' => 'Tests for the mail module.',
    'group' => 'Test Mail Group',
 );
 }
public function setUp() {
   parent::setUp(array('mails'));

   }

public function testmail() {
    // Create an administrative user.
    $account = $this->drupalCreateUser(array('administer actions'));
    $this->drupalLogin($account);

      //database files
    $results= db_select('users','u')->fields('u',array('uid','name','mail','created','access'))->execute()->fetchAll();
    if($results){
     foreach($results as $res){
     $user_fields = user_load($res -> uid);
     $this->verbose('language:'.$language);
     $string= 'uid:'.$res->uid.' ,name:'.$res->name.' ,mail:'.$res->mail.',created date:'.$res->created.',Access:'.$res->access.'\n\r';
     $this->verbose($string);
    }
    }
    }
    }

but temporary user created and that values are getting.
i don't want temp values,i want database USERS table values.
How can I write down users information(name and email) in .test file?
Answer: Your just need get your select put it in FOREACH and write down in file.(something like below code can help you_
$results= db_select('users','u')->fields('u',array('uid','name','email'))->execute()->fetchAll();
if($results){
     $fh=fopen(drupal_get_path('module',   'yourcustommodulename').'/usertest.txt','w+');
     foreach($results as $res){
     $string= 'uid:'.$res->uid.' ,name:'.$res->name.' ,email:'.$res->email.'\n\r';
    fwrite($fh,$string);
  }
  fclose($fh);

}
Comment: how can i retrieve his role and put it in one array.
Comment: i have edited my question,how can i write that query in .test file.
Comment: @User you can add each of `users` table fields, you just need add it to  `->fields('u',array('uid','name','email'))`,as example if you need `Roles` use `->fields('u',array('uid','name','email','roles'))`
Comment: but users table values are not getting,only temporary values are getting.
Comment: i have edited my question,please tell me some sollutions for that.


The equalizer of the projections is the diagonal map

Question: I want to prove that the equalizer of $\pi_0,\pi_1: B^2 \rightarrow B$ is the diagonal $\delta_B:B \rightarrow B^2$.
That $\delta_B$ equalizes is easy enough but the universal part is a little bit more tricky for me. Let $x:T \rightarrow B^2$ such that $\pi_0x =\pi_1 x$, then there should exist a $\bar{x}:T \rightarrow B$ such that $x=\delta_B \bar{x}$.
My first thought was to try $\bar{x}=\pi_0 x$, but that doesn't help since $\delta_B \bar{x}= \delta_B (\pi_0 x) = (\delta_B \pi_0)x$ doesn't equal $x$.
Any help is much appreciated!
Answer: I want to prove this in a different style via the notion of a universal element. My particular proof has the benefit of not needing to know the answer beforehand, but the other approaches could easily be adapted to calculate the resulting arrow as well.  I'm not proposing that this is a better way of solving this particular problem, I just think it's worth seeing what it would look like. I do think a universal element/representability approach is generally a good way to deal with universal properties though.
Finding the equalizer of $\pi_0,\pi_1$ means finding an object that represents the functor $\{h\mid h\in\text{Hom}(-,B\times B)\land\pi_0 \circ h = \pi_1 \circ h\}$, that is we want an object $E$ and a natural isomorphism $$\text{Hom}(-,E) \cong \{h\mid h\in\text{Hom}(-,B\times B)\land \pi_0 \circ h = \pi_1 \circ h\}$$
The universal property for $B\times B$ looks like the following in this form.
$$\text{Hom}(-,B\times B)\cong\text{Hom}(-,B)\times\text{Hom}(-,B)$$
The universal element, in general, is the image of $id$ via the natural transformation.  So for products, the pair of arrows $(\pi_0,\pi_1)$ is the universal element. For pairs, I'll write the inverse natural transformation as $(p,q)\mapsto \langle p,q \rangle$. That it is the inverse means $\langle \pi_0,\pi_1 \rangle = id$ which is one of the universal properties for pairs. $\delta = \langle id,id \rangle$.
Okay. The above was all context.  Here's the actual calculation.
$$\begin{align}
\text{Hom}(-,E) & \cong \{h\mid h\in\text{Hom}(-,B\times B)\land\pi_0 \circ h = \pi_1 \circ h\} \\
& \cong \{(p,q)\mid (p,q)\in\text{Hom}(-,B)\times\text{Hom}(-,B)\land p = q\} \\
& = \{ (p,p) \mid p\in\text{Hom}(-,B)\} \\
& \cong \text{Hom}(-,B)
\end{align}$$
By Yoneda, $E \cong B$, but we'll just choose $E = B$.  To calculate the universal element, we just push $id$ through the natural isomorphisms backwards.  $id \mapsto (id, id) \mapsto \langle id,id \rangle = \delta$. $\square$
The first isomorphism is by definition of $E$ being an equalizer.  The second comes from representability of pairs, but it may not be completely obvious, so you should work out why it holds. The remainder is set-theoretic reasoning.  In general, representability reduces categorical reasoning to set-theoretic reasoning allowing you to leverage the mathematical experience you already have.  Slightly less generally, via representability limits and colimits are (both) calculated from limits in $\mathbf{Set}$. More precisely, they are limits in a category of $\mathbf{Set}$-valued functors, but those are calculated point-wise.
Answer: By definition $\delta_B$ is the unique arrow $B\to B\times B$ with $\pi_0\delta_B=1_B=\pi_1\delta_B$.
If $x:T\to B\times B$ such that $\pi_0x=\pi_1x$ then for $\bar x:=\pi_0x=\pi_1x$ we find the equalities:

$\pi_0(\delta_B\bar x)=(\pi_0\delta_B)\bar x=1_B\bar x=\bar x=\pi_0x$
$\pi_1(\delta_B\bar x)=(\pi_1\delta_B)\bar x=1_B\bar x=\bar x=\pi_1x$

This allows the conclusion that: $$\delta_B\bar x=x$$
Comment: Thanks very much! This was actually a lot easier when looked at from the right perspective!
Comment: You are very welcome.
Answer: $\delta_B \pi_0 x$ does equal $x$.
Consider that it has the properties
$$ \pi_0 (\delta_B \pi_0 x) = \pi_0 x \qquad \pi_1 (\delta_B \pi_0 x) = \pi_0 x$$
because $\pi_0\delta_B = \pi_1\delta_B = \mathit{id}_B$.
This means that $\delta_B \pi_0 x$ satisfies the universal property required of the map $\pi_0 x \times \pi_0 x$. But so does $x$ itself -- and by definition of $B\times B$ there is a unique map that does this.


Correlation formula for a Quadratic

Question: I have used quadratic regression on a dataset to find the graph of best fit, that is, finding the coefficients a, b and c in the general formula of y = ax^2 + bx + c.
Having done that I would now like to find the correlation coefficient of that fit to the data. Can anybody help with either the formula for the correlation coefficient or the coefficient of determination for a quadratic?
Comment: This is just multiple regression on the variables $x$ and $x^2,$ so go ahead and use the standard formulas.
Comment: Welcome to CV havelly. It is somewhat unclear what you mean by correlation coefficient for a quadratic. Pearson's correlation coefficient assumes a *linear*, not quadratic relationship between $x$ and $y$. Spearman's correlation coefficient assumes a [*monotonic*](https://en.wikipedia.org/wiki/Monotonic_function) relationship between $x$ and $y$. I assume you are not asking about Pearson's (or Spearman's) correlation coefficient between $x^{2}$ and $y$, since that seems very obvious.
Comment: Thank you for the welcome. Perhaps I will re-frame the question as it can be confusing. I have used quadratic regression on a dataset with two variables and from that the a, b and c coefficients have been determined so I have an equation  like y = 5x^2 + 2x + 7. Now this is not a perfect match to the data, that is, the graph does not exactly go through all the data points but will be fairly close to them. How can I now calculate the correlation coefficient for this quadratic equation to the dataset?
Comment: Nope. That does not clarify. See my first comment.
Comment: It's plausible you're looking for the correlation coefficient between the fitted values and the responses.  This is closely related to $R^2,$ the so-called "coefficient of determination." See, for instance, https://stats.stackexchange.com/questions/36064 for a formula.
Answer: I notice that for these sort of questions there is always a lot of pedantry in the community about the use of the term "correlation". Us non-statisticians use the term to generally mean "relationship", but some people might not get that. So like others have told you, you can't compute the correlation coefficient for a non-linear relationship such as a quadratic relationship. However, you can measure the Root Mean Squared Error and Adjusted R-squared, which will tell you about the "goodness of fit" of your model. You can also do an F-test, which will tell you how much better your model is compared to a degenerate model consisting of only a constant term. All of these measures can be computed in Matlab using the function fitnlm. I know it's been a while since this question was posted so you probably figured this out, but this could still help others. Best of luck.
Comment: found the statistician :-)
Comment: I would like to suggest that you might see "pedantry" where others who see *multiple possible meanings* seek enough clarity to meet this site's requirements for posing objectively answerable, mutually understood questions.  The distinction is perhaps due to relative levels of experience, because with more experience comes the awareness of alternative interpretations: but please do not mistake the comments of experienced statisticians for the nit-picking of pedants unless you have good evidence. (cc @Alexis)
Comment: Isn't transforming to quadratic function values and then derive a correlation coefficient efficient enough?
Answer:
Thank you for the welcome. Perhaps I will re-frame the question as it can be confusing. I have used quadratic regression on a dataset with two variables and from that the a, b and c coefficients have been determined so I have an equation like y = 5x^2 + 2x + 7. Now this is not a perfect match to the data, that is, the graph does not exactly go through all the data points but will be fairly close to them. How can I now calculate the correlation coefficient for this quadratic equation to the dataset?

This is exactly what the $R^2$ will tell you! If you do a simple linear regression, $R^2$ is equal to the squared correlation, so this is highly analogous.
When you do the parabolic fit, particularly if your parabola is symmetric, you lose the usual meaning of the sign. I have not seen this done, but if you want to take the square root of $R^2$ and then give it a sign according to the sign of the parameter on the $x^2$ to indicate if the "quadratic correlation" corresponds to an upward- or downward-opening parabola, that might make sense. Since this is not standard, however, please do define what you're doing.
$R^2$, however, will be what gives you some sense of how tight the fit is to the parabola of best fit, much as $R^2$ in simple linear regression tells you how tight the fit is to the parabola of best fit.

Correlation formula for a Quadratic


Send As not Working sending from Outlook Client

Question: Hey i set up a DL in office 365 and added members. I can send emails on behalf of the distribution group and it sends from office 365 but when i go to my outlook client i get an error that i cannot send on behalf of the user. This is the only feature not working.
Anyone have any ideas? I am in the group to send on behalf of as well as other users. Again we can send with no error on 0365. Cannot in microsoft 365 client app on desktop.
All messages are received that are sent when not on behalf of
0x80070005-0x000004dc-0x00000524 error code
Comment: Swith off 'Cache Mode' and try again, if it works reset the outlook cache.
Comment: How is everything going now? Have you got your issue fixed yet?
Answer: A simple solution that I explored and worked for this issue in Outlook.
Right click on the shared mailbox in Outlook, select Data File Properties, then Permissions tab on the newly opened box, then change the 'Default' permission from 'None' to either 'Owner' or 'Publishing Editor' etc.
You can also allow different users for different permissions based on their roles by keeping 'Default' as 'None'.
Answer: It has been a while, how is everything going now? As I know, it would take a while for the permissions to be synced to your Outlook desktop client. So, it is suggested for you to try the same operations again and see if the issue has any difference.
If the issue still continues, since the same send on behalf operation can work fine on your web mail, I'm afraid that your issue is more related to your Outlook desktop client. According to my experience, most of the similar cases are all related to the old offline address book. So, please try unchecking the Use Cached Exchange mode option via Account settings to switch to the online Exchange mode, restart the Outlook desktop client and see if the issue has any difference.
If it can indeed work fine without any issues, it is suggested to try to update your address book via Send/Receive>Send/Receive Group>Download Address Group, or remove the files in the path: C:\Users#user#\AppData\Local\Microsoft\Outlook\Offline Address Books and restart your Outlook to make Outlook redownload your address book from your mail server.
Similar issue:http://www.chicagotech.net/WordPress/2018/10/02/outlook-error-is-0x80070005-0x000004dc-0x00000524/


Teste de Unidade Entity Framework Core

Question: Olá, estou começando um projeto e é a primeira vez que trabalho com teste de unidade, estamos tentando realizar o  teste de unidade no EF Core, so que ao testar o Get, nao estou conseguindo pegar o valor de _empresaService, segue o codigo de teste, fiz uma injeção de dependencia e acho que é por isso que nao estou conseguindo.
<code>public class EmpresaTest
    {
        private readonly IEmpresaService _empresaService;

        public EmpresaTest()
        {
            var service = new ServiceCollection();
            service.AddDbContext<VetorPDVContext>((s, o) => o.UseInMemoryDatabase("pdvDI").EnableSensitiveDataLogging());
            service.AddScoped<VetorPDVContext, VetorPDVContext>();
            service.AddTransient<IEmpresaRepository, EmpresaRepository>();
            service.AddTransient<IEmpresaService, EmpresaService>();
            service.AddTransient<IEmpresaAppService, EmpresaAppService>();

            var provider = service.BuildServiceProvider();
            _empresaService = provider.GetService<IEmpresaService>();

            InitContext();
        }

        public void InitContext()
        {
            var controller = new EmpresaAppService(_empresaService);
            var empresa = new EmpresaModel { CodigoEmpresa = 1, CgcEmpresa = "00000000/0000-00", RazaoSocial = "Empresa 01", NomeFantasia = "Empresa 01" };
            controller.Add(empresa);
        }
        [Fact]
        public void TestGetAsync()
        {
           var result = _empresaService.Get(emp => emp.CodigoEmpresa == 1).Result.ToList();
        }
    }
</code>
Answer: O que ocorre é que você parece estar indo efetivamente ao banco, o que não faz sentido, o teste deve ser feito ao que refere-se ao método.
Caso não conheça, sugiro que faça um mock do serviço, desta forma você manipula os resultados esperados dos testes para qualquer parte do seu serviço.
Costumo usar o Moq, existe muito material disponível sobre ele.
Nuget Moq

Teste de Unidade Entity Framework Core


Indefinite integral of rational expression involving cubic polynomials

Question: I was given the following exercise:

$$\int \frac{x^3}{(x^2+1)^3}dx$$

As a tip, my professor suggested using the following substitution: $t=x^2+1$.
Notice that if  $t=x^2+1$, then $x^2=t-1$ and therefore $x=(t-1)^\frac{1}{2}$. Then
$$x^3=x^2\cdot x=(t-1)(t-1)^\frac{1}{2}=(t-1)^\frac{3}{2}$$
and we have that
$$\int \frac{x^3}{(x^2+1)^3}dx=\int \frac{(t-1)^\frac{3}{2}}{t^3}dt.$$
But now that I have applied the suggested substitution, I don't really see how to continue with this integral. Integrating by parts doesn't seem to get me nowhere, and I can't seem to find any way to apply the substitution method. Am I missing something, or perhaps I made a mistake changing my integration variable from $x$ to $t=x^2+1$?
Thanks in advance.
Comment: How did you get rid of the $dx$, by the way?
Comment: Apparently I didn't get rid of it at all, as it was pointed out by Robert Z in his solution. Thanks Andrew!
Answer: You forgot that, since $x=(t-1)^{\frac{1}{2}}$, we have also
$$dx=D((t-1)^{\frac{1}{2}})\, dt=\frac{1}{2}(t-1)^{-\frac{1}{2}}\, dt.$$
Therefore, we find
$$\int \frac{x^3}{(x^2+1)^3}dx=\int \frac{(t-1)^\frac{3}{2}}{t^3}\cdot
\color{blue}{\frac{1}{2}(t-1)^{-\frac{1}{2}}}\, dt=
\frac{1}{2}\int \frac{t-1}{t^3}\, dt=\frac{1}{2}\int \frac{dt}{t^2}-\frac{1}{2}\int \frac{dt}{t^3}.$$
Now it should be easy to finish the job.
Comment: Of course, I completely missed that. Thanks.
Comment: From $t = x^2 + 1$, it might be a bit simpler to use $dt = 2xdx \implies \frac{dt}{2} = xdx$, so $x^3dx = (x^2)xdx = (t - 1)\frac{dt}{2}$.
Comment: @JohnOmielan I agree, this is another way to consider the relationship between $dx$ and $dt$. Thanks for your comment.
Answer: Partial integration may also work as follows:
\begin{eqnarray*} \int \frac{x^3}{(x^2+1)^3}dx
 & = & \int x^2\frac{x}{(x^2+1)^3}dx \\
& = & x^2\left(-\frac{1}{4}\frac{1}{(x^2+1)^2}\right) + \frac{1}{4}\int \frac{2x}{(x^2+1)^2}dx \\
& = & -\frac{1}{4}\frac{x^2}{(x^2+1)^2} - \frac{1}{4}\frac{1}{x^2+1} (+C)
\end{eqnarray*}


ODE - Determining a conservative system

Question: I have to show that $$2y^2-2x^2+x^4$$ is conserved along all orbits.
I know that I need to find a function E = E(x, y) such that
$$ \frac{\partial{E}}{\partial{x}}\cdot x^{'} +  \frac{\partial{E}}{\partial{y}}\cdot y^{'} =  \frac{\partial{E}}{\partial{x}}\cdot f+  \frac{\partial{E}}{\partial{y}}\cdot g = 0 $$
Can I say that $E(x,y)=2y^2-2x^2+x^4$ and how do I choose $x^{'}$ and $y^{'}$?
I tried solving and I got $x^{'}=y$ and  $y^{'}=x-x^3$. Is this right?
Comment: If we are allowed to define our own system of ODEs, I vote for the following:  $x'(t)=0, y'(t)=0$.
Comment: @Michael Too trivial :-P
Comment: This problem description seems incomplete.
Comment: I am also thinking the same thing.
Comment: Good!  For example, I would assume a question about ODEs would have an ODE somewhere.
Answer: Take $H=\frac14(2y^2-2x^2+x^4)$ as Hamiltonian and consider the system
$$
x'=\frac{\partial H}{\partial y},\qquad y'=-\frac{\partial H}{\partial x}
$$

ODE - Determining a conservative system


Differences between log-log, semi-log and linear regression

Question: Can somebody please explain the differences between using the in the linear/semi-log/log form and also pros and cons of each other.
Comment: Please make this question more specific. In its current form it does not conform to the guidelines of this site. It cannot have one definite answer.
Comment: There might be some useful discussion [here](http://stats.stackexchange.com/questions/134154/what-are-the-formulas-for-exponential-logarithmic-and-polynomial-trendlines)
Answer: Pick the transformations that make logical sense for you application. Before you see the data, how do you think changes in $x$ affect changes in $y$?

For $y = a + bx$, $\Delta y = b\Delta x$. Meaning, a 1 unit increase in $x$ results in a $b$ unit increase in $y$.
For $\log(y) = a + bx$, $\%\Delta y = b\Delta x$. Meaning, a 1 unit increase in $x$ results in $y$ being multiplied by $(1+b)$.
For $y = a + b \log(x)$, $\Delta y = b\%\Delta x$. Meaning, a doubling in $x$ results in a $b$ unit increase in $y$.
For $\log(y) = a + b \log(x)$, $\%\Delta y = b\%\Delta x$. Meaning, a doubling in $x$ results in $y$ being multiplied by $(1+b)$.
If none of these interpretations make sense for your application, you might need a different transformation.
Comment: in my application I try to evaluate the price of a real-estate depending on their characteristics. I'm using the Hedonic-Method. In some papers is written that the semi-log form would be the best, but for different real estates, I got different forms which give the best result.
Comment: but most of the estimations are better when using the semi-log form
Answer: Terminology differs greatly among (sub-(sub-))disciplines, but I suspect you mean just a linear regression where both the y and the x are log transformed (log-log), where either the y or the x is log transformed (semi-log) or both the y and x are not transformed (linear).
The pros and cons just boil down to what fits the data and/or theory best.
Comment: There is a lucid introductory survey within Edward R. Tufte. 1974. _Data analysis for politics and policy_. Englewood Cliffs, NJ: Prentice-Hall. At the time of writing it's available for USD 2 from www.edwardtufte.com (This kind of stuff doesn't date.)


How do you arrange a list in Python and then return it?

Question: Hello I have the following python script, which obtains information from a list and concatena for a javascript that I import in a test application for my TCC.
import json

lista = [
    {
        "ExceptionsAPI": {
            "ExceptionName": "aad_training",
            "TargetHostname": "empresa1.org",
            "TargetName": "empresa1"
        }
    },
    {
        "ExceptionsAPI": {
            "ExceptionName": "aad_account",
            "TargetHostname": "empresa1.org",
            "TargetName": "empresa1"
        }
    },
    {
        "ExceptionsAPI": {
            "ExceptionName": "AccountStructure",
            "TargetHostname": "empresa1.org",
            "TargetName": "empresa1"
        }
    },
    {
        "ExceptionsAPI": {
            "ExceptionName": "philippe",
            "TargetHostname": "empresa2.info",
            "TargetName": "empresa2"
        }
    },
    {
        "ExceptionsAPI": {
            "ExceptionName": "porto",
            "TargetHostname": "empresa2.info",
            "TargetName": "empresa2"
        }
    },
    {
        "ExceptionsAPI": {
            "ExceptionName": "obidos",
            "TargetHostname": "empresa3.net",
            "TargetName": "empresa3"
        }
    },
    {
        "ExceptionsAPI": {
            "ExceptionName": "coimbra",
            "TargetHostname": "empresa3.net",
            "TargetName": "empresa3"
        }
    }
]

    regexp = []
    target = []
    for chaves in lista:
        dicionario = chaves['ExceptionsAPI']
        target.append(dicionario['TargetName'])
        hostname = (dicionario['TargetHostname'])
        regexp.append(dicionario['ExceptionName'])

    regexp = str('|').join(regexp)
    print('\n Targets in the List'.join(target))

    print('\n We have the following exceptions for the company1:', regexp)

    print('\n We have the following domain:', hostname)

Output:
    empresa1
     Targets in Listaempresa2
     Targets in Listaempresa3
    ('\n We have the following exceptions for the company1', 'aad_training|aad_account|coimbra')
    ('\n  We have the following domain:', 'empresa3.net')

It's working, but I need help. I need you to go back to each 'TargetName' an organization like this below:
So, as you can verify, for each target name writes with print and returns me the correct organization of each 'ExecptionName' of each 'TargetName'
what I need and that for each target being 1 or 100 it returns to me this organization and assembleit automatically.
what I need and that the return is like this:
    The following targets are listed:

    Targets in the List: company1
    Targets in the List: company2
    Targets in the List: company3

    We have the following exceptions for the company1:
    your domain and: empresa1.org
    their targets are: aad_training;aad_account; AccountStructure, New

    We have the following exceptions for the company2:
    your domain and: empresa2.info
    its targets are: philippe;porto

    We have the following exceptions for the company3:
    your domain and: empresa3.net
    its targets are: obidos;coimbra

Comment: Please clean up the output to match the code you've posted. It is not clear what's your desired result.
Answer: Please use the below for automated listing of your requirements.
import re
lista = [
    {
        "ExceptionsAPI": {
            "ExceptionName": "aad_training",
            "TargetHostname": "empresa1.org",
            "TargetName": "empresa1"
        }
    },
    {
        "ExceptionsAPI": {
            "ExceptionName": "aad_account",
            "TargetHostname": "empresa1.org",
            "TargetName": "empresa1"
        }
    },
    {
        "ExceptionsAPI": {
            "ExceptionName": "AccountStructure",
            "TargetHostname": "empresa1.org",
            "TargetName": "empresa1"
        }
    },
    {
        "ExceptionsAPI": {
            "ExceptionName": "philippe",
            "TargetHostname": "empresa2.info",
            "TargetName": "empresa2"
        }
    },
    {
        "ExceptionsAPI": {
            "ExceptionName": "porto",
            "TargetHostname": "empresa2.info",
            "TargetName": "empresa2"
        }
    },
    {
        "ExceptionsAPI": {
            "ExceptionName": "obidos",
            "TargetHostname": "empresa3.net",
            "TargetName": "empresa3"
        }
    },
    {
        "ExceptionsAPI": {
            "ExceptionName": "coimbra",
            "TargetHostname": "empresa3.net",
            "TargetName": "empresa3"
        }
    }
]

companies = set(filter(lambda y: re.match('^[a-zA-Z0-9]+$',y),map(lambda x: x['ExceptionsAPI']['TargetName'],lista)))

print(str('\n').join(set(map(lambda x: f'{x[0]} {x[1]}',zip(['Targets in the List:']*len(companies),companies)))))

for i in sorted(companies):
    print(f'We have the following exceptions for the {i}')
    clist = list(filter(lambda x:x['ExceptionsAPI']['TargetName'] == i,lista))
    hostname = set(map(lambda x:x['ExceptionsAPI']['TargetHostname'],clist))
    targets = set(map(lambda x:x['ExceptionsAPI']['ExceptionName'],clist))
    print(f'your domain and: {",".join(hostname)}')
    print(f'its targets are: {";".join(targets)}')

This will give you the expected output:
Targets in the List: empresa1
Targets in the List: empresa3
Targets in the List: empresa2
We have the following exceptions for the empresa1
your domain and: empresa1.org
its targets are: AccountStructure;aad_training;aad_account
We have the following exceptions for the empresa2
your domain and: empresa2.info
its targets are: philippe;porto
We have the following exceptions for the empresa3
your domain and: empresa3.net
its targets are: obidos;coimbra

Comment: perfect, it worked :)

Just one more doubt, imagine that I get a value in json in the TargetName and ExceptionName field with invalid characters such as (. Ç - _ ,) how not to run if I receive these values.

i want to allow a-z letters and numbers only.
Comment: You can use regex to check and skip [a-zA-Z0-9]+, anything that matches this would return true else false, skip the value for false.Also, please vote my answer. :)
Comment: can you help me in which part of the code I add regex?

i tried two places and it didn't work.


.after() jquery em JS Puro?

Question: Em jquery:
$( "#main article:nth-child(3)" ).after( "
" );

Como ficaria em JS puro?
Answer: A função jQuery .after() insere um elemento irmão depois, em javascript nativo isso é feito com insertBefore(), segundo a documentação:

(insertBefore) Adiciona o nó especificado, antes de um elemento de referência, como filho do nó atual.
(...)
Não existe um método insertAfter. Mas ele pode ser emulado combinando o método insertBefore com nextSibling.

Dessa forma deve-se inserir o novo nó no elemento pai antes do próximo elemento irmão.
A forma curta fica:
elemento.parent.insertBefore(novoElemento, elemento.nextSibling);

O código abaixo adiciona um novo nó como é feito na pergunta, é de fácil compreensão e os comentários complementam.

var elementos = document.querySelectorAll('span:nth-child(3)');
var elemento, pai, div;
for (var i = 0; i < elementos.length; i++) {
  elemento = elementos[i];
  pai = elemento.parentNode;
  div = document.createElement('div');
  div.style.clear = 'both';
  // insere no elemento pai, antes do próximo irmão
  pai.insertBefore(div, elemento.nextSibling)
  // se o segundo parâmetro é nulo será inserido como último filho
}

// se for apenas um elemento utilize a linha abaixo
// e apague o loop for
var elemento = document.querySelector('li:nth-child(3)');
item
item
item
item
Comment: Bem visto, `++`
Answer: Use insertAdjacentHTML(posição, conteúdo) (suporte):
A posição é definida em relação ao elemento pelos tipos seguintes:

"afterbegin": Dentro do elemento, antes de seu primeiro filho (childNode).
"afterend": Após o próprio elemento.
"beforebegin": Antes do próprio elemento.
"beforeend":  Dentro do elemento, após seu último filho (childNode).

E o posicionamento ficaria:

foo

`

O conteúdo é string a ser analisada como HTML ou XML e inserido na árvore.

Exemplo:

var elemento = document.querySelector('p');
elemento.insertAdjacentHTML('afterend', '
Overflow
');
p { display: inline }

Stack

Comment: boa resposta, `+1`. Pelo que vi da documentação a função  `insertAdjacentHTML` aceita HTML como texto mas não um elemento criado por exemplo com `createElement`. Entretanto o Chrome e o IE tem um método [`insertAdjacentElement`](https://msdn.microsoft.com/en-us/library/ms536451(v=vs.85).aspx), mesmo não existindo tal método na recomendação W3C

.after() jquery em JS Puro?