text:
Q: How does pseudoreplication differ from resampling I wonder how pseudoreplication (https://en.wikipedia.org/wiki/Pseudoreplication) differs from resampling (which is simply resampling with replacement from a given sample).
On the one hand, resampling methods offer a convenient way to assess the distribution of statistics (which is good).
On the other hand, pseudoreplication seems to have a really bad reputation and is stated to be a problem. I understand that pseudoreplication was pointed out as a problem because of repeated measurements of an individual which are clearly correlated, while performing statistical tests etc. which assume uncorrelated data. ("Pseudoreplication occurs when observations are not statistically independent, but treated as if they are" https://bmcneurosci.biomedcentral.com/articles/10.1186/1471-2202-11-5#:~:text=Pseudoreplication%20occurs%20when%20observations%20are,correlated%20in%20time%20or%20space.)
However, I found wordings like

*

*"pseudoreplication techniques, especially bootstrap ..." https://www.google.de/books/edition/Practical_Methods_for_Design_and_Analysi/reYkGe9PLMQC?hl=de&gbpv=1&dq=%22pseudoreplication%22%20%22bootstrap%22&pg=PA149&printsec=frontcover&bsq=%22pseudoreplication%22%20%22bootstrap%22

*"The next step in the logic is that of pseudoreplication. This involves
resampling the data after they are collected but in a way that
reflects the sampling procedures"  https://support.sas.com/resources/papers/proceedings/proceedings/sugi22/STATS/PAPER279.PDF
which suggest that resampling techniques produce pseudoreplications.
Additionally, I found this book which seems to discuss pseudoreplication due to boostrapping on page 272 (but I do not get the point of the argument)
https://books.google.de/books?id=B9PDDQAAQBAJ&lpg=PA272&ots=Doj3ob14Jn&dq=%22pseudoreplication%22%20%22resampling%22&hl=de&pg=PA272#v=onepage&q&f=false
If pseudoreplication is such a big problem, then why doesn't this imply that resampling always has to suffer from this problem of pseudoreplication? And if this pseudoreplication is a problem in the bootstrap, is there a nice illustration showing the problem of psueodreplication and when do I know that I am running into the problem of pseudoreplication when applying the bootstrap?
I am struggling with "pseudoreplication" being branded as an incredible huge problem whenever you search for it, but also resampling (which is really cool) being called a pseudoreplication method. I want to get the implications right here.
PS: having a set of paired feature vectors and labels, i.e. ((feature_1, feature_2, ...), label) it is clear to me that it only makes sense to do a pair bootstrap and resample the whole tuple (feature vector, label) because each feature_i might be correlated to another feature. But applying the bootstrap here to resample single feature values is an obvious application error.
PPS: This post has more literature on pseudoreplication: Is Hurlbert 1984 the best introductory overview to pseudoreplication?

A: I coined the term pseudoreplication for a class of statistical errors in the late 1970s not realizing it had occasionally been used in the past (CJ MCCarthy 1969)for completely different concepts or practices. The wikipedia article (which I had no role in) is focused on my first paper on the topic but is unclear, out of date and reflects unawareness of a large body of post-1984 papers on the topic. Below is a list of my own on the topic. I can send a pdfs; just contact me at hurlbert@sdsu.edu. I suggest the 2009 paper as an introduction to this literature.
Hurlbert, S.H.  1990.  Pastor binocularis:  Now we have no excuse [review of Design of Experiments by R. Mead]. Ecology 71: 1222-1228.
Hurlbert, S. H. and M. D. White.  1993.  Experiments with freshwater invertebrate zooplanktivores: Quality of statistical analyses.  Bull. Mar. Sci. 53: 128-153.
Lombardi, C.M. and S.H. Hurlbert. 1996.  Sunfish cognition and pseudoreplication.  Animal Behaviour 52:419-422
Hurlbert, S.H., 1997.  Experiments in ecology [Review of book by same title by A.J. Underwood].  Endeavour 21:172-173.
Hurlbert, S.H., and C.M. Lombardi. 2003. Design and analysis: uncertain intent, uncertain result [review of Experimental design and data analysis for biologists by G. Quinn and M. Keough]. Ecology 83:810-812.
Hurlbert, S.H. and W.G. Meikle. 2003. Pseudoreplication, fungi, and locusts. Journal of Economic Entomology 96:533-535.
Hurlbert, S.H. 2004. On misinterpretations of pseudoreplication and related matters: a reply to Oksanen. Oikos 104: 591-597.
Kozlov, M. and S.H. Hurlbert. 2006. Pseudoreplication, chatter, and the international nature of science. Journal of Fundamental Biology 67(22):128-135. [In Russian; English translation available as pdf].
Hurlbert, S.H. 2009. The ancient black art and transdisciplinary extent of pseudoreplication.   Journal of Comparative Psychology 123: 434-443.
Hurlbert, S.H. 2010. Pseudoreplication capstone: Correction of 12 errors in Koehnle & Schank    (2009). Department of Biology, San Diego State University, San Diego, California. 5 pp.
Hurlbert, S.H. 2012. Pseudofactorialism, response structures, and collective responsibility. Austral Ecology 38: 646-663 + suppl. inform.
Hurlbert, S.H. 2013. Affirmation of the classical terminology for experimental design via a critique of Casella's Statistical Design. Agronomy Journal 105: 412-418 + suppl. inform.
Hurlbert, S.H. 2021. Pseudoreplication revisited: Some little-known history of an ancient big problem. Manuscript in revision.

A: If I understand correctly, pseudoreplication is for example about treating highly correlated data as if it was independent data.
In such a case also the bootstrap would have trouble because (with insufficient sample size) the empirical distribution function would not match the population distribution function. If we would apply the bootstrap in such a case (where the empirical distribution function differs from the population distribution function due to small sample size and high correlation), we would also run into the problem of pseudoreplication with the bootstrap method.
However, given the empirical distribution function is a good representation of the population distribution function, then the bootstrap does not have a problem of pseudoreplication.


text:
Q: How do I remove a non-present drive from the list? When I got this new PC, it had a floppy drive attached. Recently I decided that I wasn't going to need it, ever, and it only made some noise on startup. So I took out the cables connected to it, and it no longer makes noise obviously. Problem solved. But Nautilus still shows the floppy drive in the list of drives, and I can't get rid of it despite it not actually being present. It is also shown on the launcher. Clicking it does nothing. How do I remove these buttons?
This is what sudo fdisk -l gives me:
Disk /dev/sdb: 203.9 GB, 203928109056 bytes
255 heads, 63 sectors/track, 24792 cylinders, total 398297088 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0xdc4bdc4b

   Device Boot      Start         End      Blocks   Id  System
/dev/sdb1            4096   398297087   199146496   83  Linux

Disk /dev/sda: 120.0 GB, 120033041920 bytes
255 heads, 63 sectors/track, 14593 cylinders, total 234439535 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x000c1b44

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *        2048      499711      248832   83  Linux
/dev/sda2          501758   234438655   116968449    5  Extended
/dev/sda5          501760   234438655   116968448   8e  Linux LVM

Disk /dev/mapper/ubuntu--vg-root: 113.3 GB, 113330094080 bytes
255 heads, 63 sectors/track, 13778 cylinders, total 221347840 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

Disk /dev/mapper/ubuntu--vg-root doesn't contain a valid partition table

Disk /dev/mapper/ubuntu--vg-swap_1: 6442 MB, 6442450944 bytes
255 heads, 63 sectors/track, 783 cylinders, total 12582912 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

Disk /dev/mapper/ubuntu--vg-swap_1 doesn't contain a valid partition table

It doesn't appear to contain any info on floppy drives or missing drives.
And this is what cat /etc/fstab says:
# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
/dev/mapper/ubuntu--vg-root /               ext4    errors=remount-ro 0       1
# /boot was on /dev/sda1 during installation
UUID=4ce4e749-7286-46d6-b756-cb09cb51fead /boot           ext2    defaults            0       2
/dev/mapper/ubuntu--vg-swap_1 none            swap    sw              0       0
/dev/fd0        /media/floppy0  auto    rw,user,noauto,exec,utf8 0       0

It does say something about a floppy drive, but nothing about it being missing, defunct, or anything like that.

A: First, you should definitely remove your floppy drive from fstab, you can use a simple text editor for this. If this does not solve your problem in itself (it should though), please refer to this old answer for a similar question.
If it is a desktop PC, another option is trying to disable it in the BIOS.

redpajama_set_name: RedPajamaStackExchange


text:
Q: I want to be able to reorder the list by tapping on any part of the list. in flutter I am now using Flutter to create a sortable list. And now I can sort it, but I can't move the list without clicking the button on the far right. Please let me know how to fix this problem or how I can change the order of the list by tapping on any part of the list.
sorry,
I'm writing English using a translator, so the sentences and words may be wrong.
List
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';

void main() {
  // 最初に表示するWidget
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // 右上に表示される"debug"ラベルを消す
      debugShowCheckedModeBanner: false,
      // アプリ名
      title: 'My Todo App',
      theme: ThemeData(
        // テーマカラー
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      // リスト一覧画面を表示
      home: TodoListPage(),
    );
  }
}

// リスト一覧画面用Widget
class TodoListPage extends StatefulWidget {
  @override
  _TodoListPageState createState() => _TodoListPageState();
}

class _TodoListPageState extends State<TodoListPage> {
  // Todoリストのデータ
  List<String> todoList = [];

  void reorderData(int oldindex, int newindex) {
    setState(() {
      if (newindex > oldindex) {
        newindex -= 1;
      }
      final items = todoList.removeAt(oldindex);
      todoList.insert(newindex, items);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // AppBarを表示し、タイトルも設定
      appBar: AppBar(
        title: Text('List list'),
      ),
      // データを元にListViewを作成
      body: ReorderableListView.builder(
        itemCount: todoList.length,
        itemBuilder: (context, index) {
          return Card(
            key: ValueKey(todoList[index]),
          child: ListTile(
                  onTap: () async {
                    // ダイアログを表示------------------------------------
                    showDialog(
                      context: context,
                      builder: (BuildContext context) {
                        return Column(
                          children: <Widget>[
                            AlertDialog(
                              content: SingleChildScrollView(
                                child: ListBody(
                                  children: <Widget>[
                                    Column(
                                      children: <Widget>[
                                        TextButton.icon(
                                          icon: const Icon(
                                            Icons.add,
                                            color: Colors.black,
                                          ),
                                          label: const Text('Edit'),
                                          onPressed: () async {
                                            var morenewText =
                                                await Navigator.of(context)
                                                    .push(
                                              MaterialPageRoute(
                                                builder: (context) =>
                                                    TodoAddPage(
                                                        todoList[index]),
                                              ),
                                            );
                                            setState(() {
                                              todoList[index] = morenewText;
                                            });
                                          },
                                        ),
                                        ElevatedButton(
                                          child: const Text('Delete'),
                                          onPressed: () {
                                            setState(() {});
                                            todoList.removeAt(index);
                                            Navigator.pop(context);
                                          },
                                          style: ElevatedButton.styleFrom(
                                            primary: Colors.blue,
                                          ),
                                        ),
                                        ElevatedButton(
                                          child: const Text('Cancel'),
                                          onPressed: () {
                                            Navigator.of(context).pop();
                                          },
                                        ),
                                      ],
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ],
                        );
                      },
                    );
                  },
                    title: Text(todoList[index]),
          ),
          );
        },
        onReorder: reorderData,
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          // "push"で新規画面に遷移
          // リスト追加画面から渡される値を受け取る
          var newListText = await Navigator.of(context).push(
            MaterialPageRoute(builder: (context) {
              // 遷移先の画面としてリスト追加画面を指定
              return TodoAddPage(null);
            }),
          );
          if (newListText != null) {
            // キャンセルした場合は newListText が null となるので注意
            setState(() {
              // リスト追加
              todoList.add(newListText);
            });
          }
        },
        child: Icon(Icons.add),
      ),
    );
  }
}

class TodoAddPage extends StatefulWidget {
  final oldnama;
  TodoAddPage(this.oldnama);

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

class _TodoAddPageState extends State<TodoAddPage> {
  var newname = '';

  @override
  Widget build(BuildContext context) {
    if (widget.oldnama != null) {
      newname = widget.oldnama;
    }
    return Scaffold(
      appBar: AppBar(
        title: Text('Add list'),
      ),
      body: Container(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            // 入力されたテキストを表示
            const SizedBox(height: 8),
            // テキスト入力
            TextFormField(
              //テキスト入力の初期値を決める
              initialValue: newname,
              // 入力されたテキストの値を受け取る(valueが入力されたテキスト)
              onChanged: (String value) {
                // データが変更したことを知らせる(画面を更新する)
                // データを変更
                newname = value;
              },
            ),
            const SizedBox(height: 8),
            Container(
              // 横幅いっぱいに広げる
              width: double.infinity,
              // リスト追加ボタン
              child: ElevatedButton(
                onPressed: () {
                  // "pop"で前の画面に戻る
                  // "pop"の引数から前の画面にデータを渡す
                  Navigator.of(context).pop(newname);
                },
                child: Text('Add list', style: TextStyle(color: Colors.white)),
              ),
            ),
            const SizedBox(height: 8),
            Container(
              // 横幅いっぱいに広げる
              width: double.infinity,
              // キャンセルボタン
              child: TextButton(
                // ボタンをクリックした時の処理
                onPressed: () {
                  // "pop"で前の画面に戻る
                  Navigator.of(context).pop();
                },
                child: Text('Cancel'),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

A: Welcome to SOF.
This behavior is by default (https://api.flutter.dev/flutter/material/ReorderableListView-class.html), on mobile you can long click, while on desktop you should use drag handle.
But you can use custom libraries, like this one : https://pub.dev/packages/flutter_reorderable_list


text:
Q: Histogram binwidth (in)consistency between base graphics and ggplot2 I ran into the following scenario...
The following code produce the 2 identical histogram:
library(ggplot2)
data("diamonds")
ggplot(diamonds, aes(x=price)) + geom_histogram(binwidth=1000)
qplot(price, data = diamonds, binwidth = 1000)

However, I do not understand how they derive the first bar/bin on the left, in fact, the whole histogram seems wrong to me.

On the other hand:
hist(diamonds$price,breaks = seq(0,20000, by=1000))

produces the following graph which seems right to me:

To validate the data I ran this code:
br = seq(0,20000,by=1000)

ranges = paste(head(br,-1), br[-1], sep=" - ")
freq = hist(diamonds$price, breaks = br, include.lowest=TRUE, plot=FALSE)

data.frame(range = ranges, frequency = freq$counts)

and it produces:
           range frequency
1       0 - 1000     14524
2    1000 - 2000      9683
3    2000 - 3000      6129
4    3000 - 4000      4225
5    4000 - 5000      4665
...

So where does that first bar/bin in ggplot or qplot come from?

A: The ggplot histogram bars are centered on 0, 1000, 2000, etc., whereas the base histogram bars are centered on 500, 1500, 2500, etc. To check this, compare the bar counts in each histogram with table counts where we set the breaks explicitly.
table(cut(diamonds$price, breaks=seq(-500,20000,1000)))

(-500,500]       (500,1.5e+03]   (1.5e+03,2.5e+03]   (2.5e+03,3.5e+03]   (3.5e+03,4.5e+03]
      1749               18261                7532                4958                4535
etc.

theme_set(theme_classic())
ggplot(diamonds, aes(x=price)) +
  geom_histogram(binwidth=1000, fill="grey80", colour="black", lwd=0.2) +
  stat_bin(binwidth=1000, geom="text", aes(label=..count..),
           position=position_stack(vjust=0.5), size=3)

And for the base histogram:
freq = hist(diamonds$price)$counts
tab = unname(table(cut(diamonds$price, breaks=seq(0,19000,1000))))

cbind(freq, tab)

       freq   tab
 [1,] 14524 14524
 [2,]  9683  9683
 [3,]  6129  6129
 [4,]  4225  4225
 [5,]  4665  4665
 [6,]  3163  3163
 [7,]  2278  2278
 [8,]  1668  1668
 [9,]  1307  1307
[10,]  1076  1076
[11,]   934   934
[12,]   825   825
[13,]   701   701
[14,]   603   603
[15,]   504   504
[16,]   513   513
[17,]   425   425
[18,]   405   405
[19,]   312   312

To get the same breaks in the ggplot histogram, you can use the center argument in addition to binwidth:
ggplot(diamonds, aes(x=price)) +
  geom_histogram(binwidth=1000, center=500, fill="grey80", colour="black", lwd=0.2) +
  stat_bin(binwidth=1000, center=500, geom="text", aes(label=..count..),
           position=position_stack(vjust=0.5), size=3)


text:
Q: Get argv from bprm_check_security in linux kernel. Is the documentation wrong? According to Linux Kernel's doc:

bprm_check_security:
This hook mediates the point when a search for a binary handler will
begin.  It allows a check against the bprm->cred->security value
which was set in the preceding creds_for_exec call.  The argv list and
envp list are reliably available in bprm.  This hook may be called
multiple times during a single execve.
bprm contains the linux_binprm structure.

However, the value of argv and envp (e.g. bprm->mm->arg_start) are actually NULL at this point. This is due to the fact these values are setup in setup_arg_pages is called after the hook. Also, the current struct still points to the old process thus it cannot be used to get these data.
So my question is: Is the documentation incorrect or is there an alternate way to reliably get the arguments at this point?

Side note: I know that this post already asks a quite similar question but I don't think it's a duplicate since this post asks a way to get argv from bprm_check_security, while I think that might not be possible thus I ask a confirmation that the issue comes from the doc. Additionally, no correct answer were given to this post.


text:
Q: type ahead search in WPF datagrid Hi I have a  grid with collection of student
public class Student
{
public string First{get;set;}
public string Last{get;set;}
public int Age{get;set;}
}

MyGrid.ItemsSource= new List<Student>(){new Student{First="First1",Last="Last1",Age=1},
new Student{First="First2",Last="Last2",Age=2}},
new Student{First="First3",Last="Last3",Age=3}},
new Student{First="First4",Last="Last4",Age=4}},};

Now after the page or grid is loaded user will simply type in some characters and the application has to select the specific row that matches the user input with first or last name.
This is exact similar to what we see in windows explorer or visual studio just type in to select folder in Win Explorer or a .cs file in visualstudio.
how do we achieve this ?

A: After two day research I finally found the answer.
it is very simple to achieve this functionality.
Set an attached property to desired property name and it works magically.
TextSearch.TextPath="First"

A: Your DataGrid would be as follows:
<DataGrid x:Name="myDataGrid" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding Key}" Header="Key"/>
                <DataGridTextColumn Binding="{Binding Value}" Header="Value"/>
            </DataGrid.Columns>
        </DataGrid>

If you want something like Key x Value you do not need to create a model for this, the .NET Framework 4.5 already has a specific class for this, the class Dictionary <TKey, TValue> (TKey is the type of key data and TValue is the type of value data, so you would need a C# code like (or equal to) the following:
Dictionary<string, string> dictionary = new Dictionary<string, string>()
{
     {"Key1","Value1"},
     {"Key2","Value2"},
     {"Key3","Value3"}
};

this.myDataGrid.ItemsSource = dictionary;


text:
Q: DataGrid Row & Cell Style in XAML I want to set a DataGrid style within app.xaml. I've tried adding a style in however I am unsure of the semantics required to add a Cell and Row style.
This is what I have tried so far;
<Style TargetType="DataGrid" x:Name="noighlightRowDataGrid">
    <DataGrid.CellStyle>
        <Style TargetType="DataGridCell">
            <Style.Triggers>
                <Trigger Property="IsSelected"
                Value="True">
                    <Setter Property="Background"
                Value="White" />
                    <Setter Property="Foreground"
                Value="Black" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </DataGrid.CellStyle>
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Style.Triggers>
                <Trigger Property="IsSelected"
                Value="True">
                    <Setter Property="BorderBrush"
                Value="Blue" />
                    <Setter Property="BorderThickness" Value="2" />
            </Trigger>
        </Style.Triggers>
    </Style>
</DataGrid.RowStyle>

I can see that dropping the DataGrid.CellStyle into the DataGrid style isn't going to work but like I said I am unsure on how to create the style properly.

A: You can specify the row and cell styles independently.
<Style TargetType="DataGridCell">
    <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="Background" Value="White" />
            <Setter Property="Foreground" Value="Black" />
        </Trigger>
    </Style.Triggers>
</Style>
<Style TargetType="DataGridRow">
    <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="BorderBrush" Value="Blue" />
            <Setter Property="BorderThickness" Value="2" />
        </Trigger>
    </Style.Triggers>
</Style>


text:
Q: How to remove leading zero from double calculation? Consider the following, how do I remove the leading zero, and retain 3 decimals places? savePercentageDecimals returns 0.923, I would like just .923
    //Figure out Save Percentage
    let savePercentage = 12.0 / (1.0 + 12.0)
    let savePercentageDecimals = String(format: "%.3f",savePercentage)

Thanks in advance!

A: NumberFormatter is the class you want to use when displaying numbers as string. In your case, this will work :
let formatter = NumberFormatter()
formatter.minimumIntegerDigits = 0
formatter.minimumFractionDigits = 3
formatter.maximumFractionDigits = 3

let savePercentage = 12.0 / (1.0 + 12.0)
let savePercentageDecimals = formatter.string(from: NSNumber(value: savePercentage)) // .923

By using minimumIntegerDigits above, it doesn't remove leading significant numbers (>= 1):
let moreThan100Percent = (12.0 / (1.0 + 12.0)) + 1.0
let formattedWithDecimals = formatter.string(from: NSNumber(value: moreThan100Percent)) // 1.923


text:
Q: Why does the SpringBatch MultiResourcePartitioner not recognize jobParameters? More to the point, what to do about it? It's a pretty straight forward setup. I have a file of potentially 5m records that I need to read and do some work with and then send to the db. The mechanics of processing and writing are not important. I need to be able to pass the path and file name [ /opt/etc/app/partner/input_file.csv ] into the process as a parameter. That's easy enough, add it to the JobParameters and give it to the JobLauncher.
JobParametersBuilder jpBuilder = new JobParametersBuilder() ;
jpBuilder.addString("filePath", "/opt/etc/app/partner/input_file.csv") ;
jobLauncher.run(job, jpBuilder.toJobParameters() ;

Done, now to make the context aware of it. Again simple matter of referencing jobParameters.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:batch="http://www.springframework.org/schema/batch"
    xsi:schemaLocation="
    http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch-2.1.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <description>PoC to demonstrate variable row content handling</description>

    <batch:job id="poc" job-repository="jobRepository" incrementer="runIdIncrementer" restartable="true">
        <batch:step id="pocReadWriteStep">
            <batch:partition step="step" partitioner="partitioner">
                <batch:handler task-executor="taskExecutor"/>
            </batch:partition>
        </batch:step>
    </batch:job>

    <batch:step id="step">
        <batch:tasklet task-executor="taskExecutor" throttle-limit="20" transaction-manager="transactionManager" allow-start-if-complete="true">
            <batch:transaction-attributes isolation="READ_UNCOMMITTED"/>
            <batch:chunk
                reader="reader"
                processor="processor"
                writer="writer"
                commit-interval="20">
            </batch:chunk>
        </batch:tasklet>
    </batch:step>

    <bean id="reader" class="org.springframework.batch.item.file.FlatFileItemReader" scope="step">
        <property name="resource" value="file:#{jobParameters['filePath']}"/>
        <property name="lineMapper">
            <bean class="org.springframework.batch.item.file.mapping.PatternMatchingCompositeLineMapper">
                <property name="tokenizers">
                    <map>
                        <entry key="*" value-ref="lineTokenizer"/>
                    </map>
                </property>
                <property name="fieldSetMappers">
                    <map>
                        <entry key="*" value-ref="fieldSetMapper"/>
                    </map>
                </property>
            </bean>
        </property>
    </bean>

    <bean id="lineTokenizer" class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer"/>

    <bean id="fieldSetMapper" class="org.springframework.batch.item.file.mapping.PassThroughFieldSetMapper"/>

    <bean id="processor" class="com.verifi.springbatchpoc.PocProcessor"/>

    <bean id="writer" class="com.verifi.springbatchpoc.PocWriter"/>

    <bean id="runIdIncrementer" class="org.springframework.batch.core.launch.support.RunIdIncrementer"/>

    <bean id="partitioner" class="org.springframework.batch.core.partition.support.MultiResourcePartitioner">
        <property name="resources" value="file:#{jobParameters['filePath']}"/>
    </bean>

    <bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
        <property name="corePoolSize" value="20"/>
    </bean>

</beans>

Except that in the MultiResourcePartitioner it can't seem to recognize the reference to jobParameters. I can hard code the path and file name and it's quite happy, but that doesn't carry the mail for this implementation.
Since I'm sure someone is going to ask, here's the stack trace from the error (well part of it anyway).
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1086)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    ... 46 more
Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Field or property 'jobParameters' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext'
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:207)
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:71)
    at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:52)
    at org.springframework.expression.spel.ast.SpelNodeImpl.getTypedValue(SpelNodeImpl.java:102)
    at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:97)
    at org.springframework.expression.common.CompositeStringExpression.getValue(CompositeStringExpression.java:82)
    at org.springframework.expression.common.CompositeStringExpression.getValue(CompositeStringExpression.java:1)
    at org.springframework.context.expression.StandardBeanExpressionResolver.evaluate(StandardBeanExpressionResolver.java:138)
    ... 52 more

Thoughts, comments, suggestions?

A: I think you should add scope="step" like:
 <bean id="partitioner" class="org.springframework.batch.core.partition.support.MultiResourcePartitioner"
scope="step">
        <property name="resources" value="file:#{jobParameters['filePath']}"/>
    </bean>


text:
Q: find element that doesn't equal a string in xpath Need help in finding element that doesn't equal to a string, Here is my XML:
<collection >
<device>
    <name>Test</name>
    <dcs>
        <dc>
            <nodes>
                <node>
                    <name>Host1</name>
                </node>
                <node>
                    <name>test</name>
                </node>
                <node>
                    <name>testing</name>
                </node>
            </nodes>
        </dc>
        <dc>
            <nodes>
                <node>
                    <name>test</name>
                </node>
                <node>
                    <name>testing</name>
                </node>
            </nodes>
        </dc>
    </dcs>
</device>

XPath I have tried:
/collection/device/dcs/dc/nodes/node[not(contains(name,'test'))]

O/p:
 <node>
    <name>Host1</name>
</node>

Expected O/p:
<node>
      <name>Host1</name>
</node>
<node>
      <name>testing</name>
</node>

Actual output is ignoring testing also but that I need in output.
Can anyone help me?
Thanks in advance.

A: To filter out nodes having inner text exactly equals certain value, use = operator wrapped in not() instead of using contains() in the same way  :
/collection/device/dcs/dc/nodes/node[not(name='test')]


text:
Q: Non-primary key column value oriented auto increment in MySQL It was hard for me to describe the problem in the title. But I'm looking should actually be very trivial.
Having such a table:
+-----------------------------------+
| id | club_id | member_id | name   |
├-----------------------------------┤
| 1  | 120     | 1         | Thomas |
| 2  | 83      | 1         | Robert |
| 3  | 120     | 2         | James  |
+-----------------------------------+

id - auto-incrementing primary key
club_id - foreign key reference
member_id - auto-incrementing for each club
name - just an example for data
So I think what I want is clear. It's like having a members table with auto incrementing id, just that every "club" in my app can have members.
Does a database-solution for this even exist or would I need to provide this from my application?


text:
Q: Git rollback push, .gitignore - ignored I have some problem with git. I have a file .gitignore with content:
uploads
.htaccess
robots.txt
etc..

I did:
 git commit -a -m "GIT TEST"

And git sent my files: .htaccess and other (in .gitignore). Why ? How can I cancel this commit ? (commit is pushed to repo "git push origin master")

A: If a file was already being tracked by git before it was added to .gitignore, it won't be automatically ignored just because it's in .gitignore now. You'll need to
git rm --cached .htaccess
git commit

to tell git to stop tracking that file. You can do that on the next commit and push cycle, but if you really need to amend the most recent commit to remove the file, you can do this:
git rm --cached .htaccess
git commit --amend
git push -f

(but beware if others might have already fetched the "bad" commit - this will cause them grief). If the commit in question isn't the most recent one, but is farther back in history, you can accomplish the same thing with git filter-branch (examples of the exact syntax should be pretty easy to find) followed by git push -f, but the same caveats apply.


text:
Q: React: state inside children not updating through props I want to set the state value of children component using props and then display the same for the respective form field. I did that inside the componentDidMount() but it doesn't work.
Code:
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      tweetCount: this.props.tweetCount
    };
  }

  componentDidMount() {
    const tweetCount = this.props.tweetCount;
    this.setState({ tweetCount });
  }

  render() {
    return (
      <React.Fragment>
        <Form>
          <FormGroup>
            <Label for="tweetCount">
              Tweets per Column (between 1 and 30):
              {this.state.tweetCount}
            </Label>
            <Input
              id="tweetCount"
              type="range"
              min="1"
              max="30"
              value={this.state.tweetCount}
              onChange={this.changeTweetCount}
              step="1"
            />
          </FormGroup>
        </Form>
      </React.Fragment>
    );
  }
}

A: If you use React that version is upper than 16.3 then use getDerivedStateFromProp so inside of using componentDidMount or componentWillReceiveProps use this code :
static getDerivedStateFromProps(props, state)
{
  return{
    tweetCount:props.tweetCount
  }
}


text:
Q: Android setText of multiple TextView from AsyncTask I've used the AsyncTask example from vogella website, I've created a class file with it.
I'm calling it from Activity A to update the postalcode's TextView, it's working.
I'm wondering how can I call the same AsyncTask from Activity B to update another postal code TextView.
So one AsyncTask, 2 calls from different Activities to update different TextViews.
I've to do something onPostExecute(), right?
Some example code, is much appreciated.
Thanks in advance

A: You can (I guess) pass the TextView to the AsyncTask when you instantiate it.
All without the IDE open so apologies if the syntax is off...
public class ExampleTask extends AsyncTask<Void, Void, Void> {
    private TextView targetTextView;

    public ExampleTask(TextView target) {
     targetTextView = target;
    }

    @Override
    protected String doInBackground(Void... orSomething) {
      //do work and get a value I guess
    }

    @Override
    protected void onPostExecute(String result) {
      targetTextView.setText(result);
    }
  }

Then you'd call this:
ExampleTask task = new ExampleTask(theTextViewToUpdate);
task.execute();

You'd want to be careful about the scope of the task objects you instantiate as that reference to a TextView could end up leaking memory from your activities.

A: Here I am  not good, but you can try
It is possible to reuse AsyncTask for different Activities.
For this you must take different parameter from different Activities.
In AsyncTask Class initiate a constructor with a case parameter (which is described in other activities) which will decide ,it is called by Activity A or B or C.
Now use switch case statement and move ahead.


text:
Q: Как запретить создание файла .recently-used в Linux? Как запретить создание файла .recently-used в Linux ?
Графическая оболочка - Mate.

A: Чтобы очистить "последние файлы" Nautilus (И не только Nautilus) нужно удалить этот файл командой:
rm ~/.local/share/recently-used.xbel

Чтобы отключить функцию recently-used:
gedit ~/.config/gtk-3.0/settings.ini # вместо gedit может быть любой текстовик

и под "[Settings]", вставляем следующие строчки:
gtk-recent-files-max-age=0
gtk-recent-files-limit=0

В итоге файл settings.ini должен выглядеть так:
[Settings]
gtk-recent-files-max-age=0
gtk-recent-files-limit=0

Источник


text:
Q: Is it possible to train except for a specific area when implementing cycleGAN? Recently, I am conducting research to create fake images using cycleGAN. The figure below is an example of the cycleGAN result. It can be seen that all areas are changed as in the image. However, I want to change the image only for a specific area. Is it possible to change only the image of the part except for the red marked part (disease part) using cycleGAN?
enter image description here

A: I think what you describe is possible. You would need to alter the cycleGan pipeline. To focus the representational capacity of the network on everything other than the red marked part you could replace the red marked part with the same part from the original image, this would enforce a focus on the other regions. When taking the cycle consistency pipeline shown below, I'm referring to adding the original image parts after e.g. Generator A2B.
Cycle consistency loss pipeline


text:
Q: Has the function srid(geometry) been removed or has the name changed? I am in the process of restoring a database that relied on PostGIS version 1.5 functions to a newer Postgresql engine that leverages PostGIS 2.2 functions.  In my restore process, I receive the following error:
pg_restore: [archiver (db)] could not execute query: ERROR:  function srid(geometry) does not exist.
I know this error is caused by a constraint on one of my tables that utilizes the srid(geometry) function.  I want to alter the constraint to use the new function name -- if it exists.  Has this function been removed or has it been renamed since PostGIS version 1.5?
I am unable to use the legacy PostGIS functions because I am restoring to an AWS RDS instance.  RDS instances do not allow the creation of functions that use C language libraries from the underlying OS for security reasons.  That is why I am in this situation.

A: The function has indeed been renamed.
In Postgis 2.0, use ST_srid.
Alternatively, following https://github.com/mapbox/osm-bright/issues/45 you can use legacy.sql or legacy_minimal.sql to bring those old functions into Postgis 2.0 for compatibility. You might find them in C:\Program Files\PostgreSQL\<version>\share\contrib\postgis-<version>\ for Windows installations.


text:
Q: Missing txn-current file in TortoiseSVN My TortoiseSVN project was working fine until yesterday. But today when I tried to commit it, got below error message. I am pretty sure I haven't deleted that file myself. Any ideas to recover it / some other workaround?
TortoiseSVN 1.6.16, Build 21511 - 32 Bit , 2011/06/01 19:00:35
Subversion 1.6.17,
apr 1.3.12
apr-utils 1.3.12
neon 0.29.6
OpenSSL 1.0.0d 8 Feb 2011
zlib 1.2.5
I am running it on Windows-7. I have a dual-boot system (other OS Ubuntu)

Thanks.

A: Preface: Using file:/// access-level for Subversion is always bad idea for any longer than few transactions task
Face: If you lost file, you have to repair it

The "txn-current" file is a file with a single line of text that
  contains only a base-36 number.  The current value will be used in the
  next transaction name, along with the revision number the transaction
  is based on.  This sequence number ensures that transaction names are
  not reused, even if the transaction is aborted and a new transaction
  based on the same revision is begun.

tells us Subversion own repo
Recipe from accepted answer for "svn commit problem, Cannot read 'd:\UC\db\txn-current': End of file found" (svnadmin verify + svnadmin recover) is perfectly valid and usable also


text:
Q: OIDC Logging out issue , How to control the browser programatically/manually? I'm using OIDC client in my Xamarin App(Code below) So when I make the call oidcClient.LogoutAsync browser opens, and while I'm awaiting the response back from the browser to the app if I need to minimise the app for some reason. The call then gets interrupted and the app stays on the browser, Never gives a response back, unless user manually closes the browser. Now I have no control over the browser from my app, Is there a way to avoid this. Maybe not open the browser altogether and logout silently. Please suggest a workaround.
private OidcClient InitializeAuthClient()
{
    var options = new OidcClientOptions
    {
        Authority = Config.AuthorityURL,
        ClientId = Config.ClientId,
        Scope = Config.Scope,
        RedirectUri = Config.RedirectUri,
        ClientSecret = Config.ClientSecret,
        PostLogoutRedirectUri = Config.RedirectUri,
        Browser = new WebAuthenticatorBrowser(),
    };
    return new OidcClient(options);
}

OidcClient oidcClient = InitializeAuthClient();
LogoutResult logoutResult = await oidcClient.LogoutAsync(new LogoutRequest
{ BrowserDisplayMode = IdentityModel.OidcClient.Browser.DisplayMode.Hidden, IdTokenHint = authData.idToken });


text:
Q: free basic compiler error 23: File not found, libsupc++.a I am trying to compile a simple a hello word QBASIC program in ubutu 12.04. downloaded and installed as instructed here. http://www.freebasic.net/get
print "hello word"

I compiled it.
 fbc hello.bas

But I got the following error.
hello.bas() error 23: File not found, libsupc++.a
ld: cannot find -lncurses
ld: cannot find -lsupc++

A: You need to install additional packages. Please see:-
http://www.freebasic.net/wiki/wikka.php?wakka=CompilerInstalling


text:
Q: How to add a button in the TableviewController? I was wondering how to add a simple static button at the bottom right of the Tableviewcontroller background, its will be contact infos.
I have tried through through the storyboard with no success.Do you have any clue for that?
Thank you  ,
Regards,

A: Take ViewController and Add TableView inside it.
Take one View and set the bottom of the view controller and set button inside that View.

A: I would suggest you to make a normal ViewController, add a tableView and save an space for that button, take note that you have to set the delegates and datasource for that tableview.

A: You could use footerView if you want this button to appear only at the bottom of the whole TableViewController. To do that, you can drag a view after the cell in the hierarchy:

A: If you really want to use a UITableViewController, you could create a normal UIViewController, add a container in it and embed a UITableViewController in the container. Here's an example:

A: Create a UIView with UIButton and set this view as TableView's FooterView


text:
Q: Subspace as system of linear equations Given a subspace we can write the subspace as a condition on the $b$ vector ($ax=b$) so in our case the column space
$\begin{pmatrix}
2 & -3 &3 &2 &x \\
-2 &3 &-1 &-1 &y\\
0 & 3 &1 &2 & z\\
2 & 3 &3 &5 &w
\end{pmatrix}$
row reducing the systems give use conditions on the vector that in the span, namelly
$\begin{pmatrix}
2 & -3 &3 &2 &x \\
0 &0 &2 &1 &x+y\\
0 & 6 &2 &4 & w+y\\
0 & 0 &0 &0 &w+y-2z
\end{pmatrix}$
So for a vector to be in the span of the columns or in this case after the row reduced form the  column space its need to satisfy $w+y-2z=0$ so the $x$ coordinate get any value at it is  $0x+w+y-2z=0?$
Solving for $0x+w+y-2z=0?$ we will get the column space?

A: Yes. The column space of the given matrix is the set of vectors $(x,y,z,w)$ that satisfy the constraint $w + y - 2z = 0$. So, not only can $x$ be arbitrary, you can also take $y$ and $z$ to be arbitrary, and then describe $w$ in terms of $y$ and $z$. Hence, the column space is the set
$$
\{ (x,y,z,2z - y) \in \mathbb{R}^4 : x,y,z \in \mathbb{R} \}.
$$


text:
Q: Missing Schema for WordPress theme.json According to the docs, one can simple add
$schema": "https://schemas.wp.org/trunk/theme.json",

to the beginning of the JSON file to load the schema
VS code gives me the error that it's missing:

And sure enough, going to https://schemas.wp.org/trunk/theme.json it doesn't exist:

I've seen posts such as this one about missing schema which says to go to https://schemas.wp.org/wp/5.9/theme.json but same result. Searching around it seems like their security certificate expired at some point, but surely they resolved that many months ago.
I'd like to resolve this to get the benefits of schema (autocomplete / intellisense) in the file, especially since the file is getting larger and this is a large project with multiple people working on it.
Help appreciated.

A: It seems like https://schemas.wp.org/trunk/theme.json is not reachable for you even though it is online (I can reach the URL). The url forwards to ttps://raw.githubusercontent.com/WordPress/gutenberg/trunk/schemas/json/theme.json which might be accessible for you. If yes, you can add this direct url as the value for $schema.


text:
Q: Unable to remove the "SE for Android" application from my account In the early days of my smartphone usage, I had installed and authorised the "SE for Android" application, which was the official app for using SE on phone.
Now that the app has been discontinued, and while checking my settings on SE, I noticed that the app was listed as authorised.
When trying to remove the same from my profile settings, the clicking on "Remove" button does nothing. There are no errors reported to the dev console either.
Is the support for app so dead that you can't even revoke the permissions?
The only extension enabled in the browser is dark reader.
I tried clicking the remove button from meta.se, as well as my profiles on SO, but same results.


text:
Q: MYSQL query not working with PHP with form I am having trouble with this code. I want to add a row into the table via a HTML form. Here is the code:
EDIT: Here is the HTML code of the form:
<form role = "form" action = "aanmaken.php" method = "post" class = "col-lg-4 col-lg-offset-1 col-md-8 col-sm-12">

            Naam event:
            <input id = "eventName" class = "form-control" type = "text" name = "eventName" placeholder = "Hier typen">

            Datum:
            <input id = "date" class = "form-control" type = "text" name = "date" placeholder="YYYY-MM-DD">

            Tijd:
            <input id = "time" class = "form-control" type = "text" name = "time" maxlength="5" placeholder="18:00">

            Max spelers:
            <input id = "max_spelers" class = "form-control" type = "number" name = "max_spelers" maxlength="2" placeholder="Hier typen">

        <input id = "submit" type="submit" value="Aanmaken">
    </form>

And the PHP:
include 'connect.php';

$eventName = $_POST['eventName'];
$date = $_POST['date'];
$time = $_POST['time'];
$aantal_spelers = $_POST['max_spelers'];

$addEvent = "INSERT INTO `dbi286018`.`dutch_delight` (`id`, `eventName`, `date`, `time`, `aantal_spelers`, `current_spelers`) VALUES (NULL, $eventName, $date, $time, $aantal_spelers, \'0\');";

if ($conn->query($addEvent) === TRUE) {
    echo "Je hebt een evenement aangemaakt! Vraag op het forum of op xbox live of mensen je evenement willen bijwonen.";
}
else {
    echo "Er ging iets fout tijdens het aanmaken van je evenement... probeer het later nog eens, of neem contact op met een van de leiders.";
    mysql_error();
}

I keep getting the else statement. Is there something I am doing wrong?
Thanks!

A: You can try this using PDO because mysql_* functions are deprecated and PDO is more secure:
try {
    $conn = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASSWORD);
} catch(PDOException $e) {
    echo $e->getMessage();
    die();
}
$eventName = $_POST['eventName'];
$date = $_POST['date'];
$time = $_POST['time'];
$aantal_spelers = $_POST['max_spelers'];
$sql = "INSERT INTO `dbi286018`.`dutch_delight` (`id`, `eventName`, `date`, `time`, `aantal_spelers`, `current_spelers`) VALUES (:id, :event_name, :date, :time, :aantal_spelers, :current_spelers)";
//Prepare your query
$stmt = $conn->prepare($sql);
//Execute your query binding variables
$stmt->execute(array(':id'=>NULL, ':event_name'=>$eventName, ':date'=>$date, ':time'=>$time, ':aantal_spelers'=>$aantal_spelers, ':current_spelers'=>0));


text:
Q: Show UIAlert before unwinding segue I'm trying to fire an alert that asks if you want to save or delete a draft after pressing cancel. I'm quite close, but I can't seem to get it right.
I'm unwinding from 'ReplyMailViewController'(ViewController A) to 'MailContentViewController'(ViewController B).
I added the following code in ViewController A to show the alert and 'hold' the segue perform:
override func shouldPerformSegue(withIdentifier identifier: String?, sender: Any?) -> Bool {
    if let ident = identifier {
        if ident == "cancelDraft" {

            let saveDraftActionHandler = { (action:UIAlertAction!) -> Void in
                NSLog("EXIT")
            }

            let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)

            let deleteDraftAction = UIAlertAction(title: "Delete Draft", style: .destructive, handler: nil)
            alertController.addAction(deleteDraftAction)
            let saveDraftAction = UIAlertAction(title: "Save Draft", style: .default, handler: saveDraftActionHandler)
            alertController.addAction(saveDraftAction)
            let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
            alertController.addAction(cancelAction)

            present(alertController, animated: true, completion: nil)

            return false
        }
    }
    return true
}

The segue holds with this code, but the issue is that I can't figure out how to continue the unwind segue after pressing 'Save Draft' for example.
I also have an unwind function in View Controller B, but I can't seem to figure out how I can use this one for this task:
@IBAction func cancelToMailContentViewController(_ segue: UIStoryboardSegue) {

}

A: Instead of perform the segue directly you need to show your UIAlertViewController first and according to the user response execute your segue or not
@IBAction func showAlertViewController(){
    let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)

    let replyAction = UIAlertAction(title: "Delete Draft", style: .destructive, handler: nil)

    let replyAllAction = UIAlertAction(title: "Save Draft", style: .default) { (action) in
        //Do whatever you need here
    }

    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action) in
        self.performSegue(withIdentifier: "cancelDraft", sender: action) //executing the segue on cancel
    }
    alertController.addAction(replyAllAction)
    alertController.addAction(replyAction)
    alertController.addAction(cancelAction)
    present(alertController, animated: true, completion: nil)

}

After this you only need to change the unwind segue action to execute this method, and your segue will be executed if you press cancel in the UIAlertViewController via self.performSegue(withIdentifier: #<SegueIdentifier>, sender: #<sender>)

A: First, make the alert with two options:
class ViewController: UIViewController {

    @IBAction func showAlertButtonTapped(_ sender: UIButton) {

        // create the alert
        let alert = UIAlertController(title: "UIAlertController", message: "Save this work?", preferredStyle: UIAlertControllerStyle.alert)

        // add the actions (buttons)
        alert.addAction(UIAlertAction(title: "Hell Yeah", style: UIAlertActionStyle.default, handler: nil))
        alert.addAction(UIAlertAction(title: "Hell No", style: UIAlertActionStyle.cancel, handler: nil))

        // show the alert
        self.present(alert, animated: true, completion: nil)
    }

After this, you have to make the segue and then name it (also connect it by control dragging from the view controller yellow icon to the other view controller):

After that put this your code to execute the segue:
self.performSegue(withIdentifier: ":)", sender: self)

After that you are going to execute the segue when the user responds to the alert:
if buttonTitle == "Hell Yeah" {
    elf.performSegue(withIdentifier: ":)", sender: self)
}

so, in the end, your code should look like this:
 class ViewController: UIViewController {

    @IBAction func showAlertButtonTapped(_ sender: UIButton) {
        // create the alert
        let alert = UIAlertController(title: "UIAlertController", message: "Save this work?", preferredStyle: UIAlertControllerStyle.alert)

        // add the actions (buttons)
        alert.addAction(UIAlertAction(title: "Hell Yeah", style: UIAlertActionStyle.default, handler: nil))

        alert.addAction(UIAlertAction(title: "Hell No", style: UIAlertActionStyle.cancel, handler: nil))

        // show the alert
        self.present(alert, animated: true, completion: nil)

        if buttonTitle == "Hell Yeah" {
            self.performSegue(withIdentifier: ":)", sender: self)
        }

    }
}


text:
Q: hg clone results in error 'An existing connection was forcibly closed by the remote host' randomly from one machine I have seen other questions about mercurial resulting in 'An existing connection was forcibly closed by the remote host' errors, but not specifically this case.
When I clone or do a large pull from one particular machine (actually our CI box) I get this error. This machine has been cloning this project for months without any problem, but this has just started today.
If I clone to an early revision, sometimes it works, and sometimes I het the same message.
It seems to be fine from all other machines.
Disk space is not particularly low on the CI box, and no firewall settings have been changed.
Any clues on what else could be a cause or how to go about debuggin this?

A: If your CI box is running hgweb (the WSGI container that is the production-grade version of hg serve) then it's probably running it in some WSGI container, be it apache, gunicorn or whatever.  If that container has a response timeout after which it cuts off the response, sometime 10 or 30 seconds, then perhaps you need to increase it.
Regardless as @Eiver suggests what you have isn't a mercurial problem but a web server problem and it one that the person administering the web server needs to solve for you.


text:
Q: How to Make Python Print something at nth Iteration within a For Loop? I want to preface my question by saying that I am very new to Python and have only started using it for a specific class in grad school.
I have written a script to find the root of a function using iterative methods such as the Fixed-point, Bisection, and Newton-Raphson methods. The python code for my algorithms are as follows:
Fixed-Point Method:
def fixedpoint(func, g_func,x0,tol, MAXIT):

    def g(x):
        return eval(g_func)

    print(f"Seeking root of {func}.")
    print("FIXED POINT ITERATION:")
    iterated_x = g(x0)
    for i in range(0, MAXIT):
        iterated_x = g(iterated_x)
        print("Iteration", i + 1, iterated_x)
        condition = abs(g(iterated_x) - (iterated_x))
        if condition < tol:
            print(f"The root converges to {iterated_x} after {i+1} iterations.")
            break
        if i == MAXIT and condition >= tol:
            print("ERROR: The root did not converge after maximum iterations.")

fixedpoint('x**2 - 4*x + 2', '(x**2+2)/4', 0.75, 10**(-4), 100)
fixedpoint('math.exp(-x) + x - 7 ', '7 - math.exp(-x)', 0.75, 10**(-4), 100)

Bisection Method:
def bisection(func,a, b, tol, MAXIT):

    def f(x):
        return eval(func)

    print(f"Seeking root of {func}")
    print("BISECTION METHOD:")
    if f(a)*f(b) <0:
        for i in range(0, MAXIT):
            c = (a+b)/2
            if f(a)*f(c) < 0:
                a = a
                b = c
                print(f"Iteration", i + 1, f(c))
            elif f(b)*f(c) < 0:
                b = b
                a = c
                print(f"Iteration", i + 1, f(c))
            if f(c) == 0 or abs(f(c)) < tol:
                print ("Exact Solution Found")
                print(f"Iteration", i + 1, c)
                print("The root converges to", c, "after", i + 1, "iterations.")
                break
            elif i == MAXIT and abs(f(c)) > tol:
                print("Bisection method fails.")

    return None

bisection('x**2 - 4*x + 2',0.5, 1, 10**(-4), 100)
bisection('math.exp(-x) + x - 7',6, 8, 10**(-4), 100)

Newton-Raphson Method:
def newtonraphson(func, deriv, x0, tol, MAXIT):

    def f(x):
        return eval(func)

    def ddx(x):
        return eval(deriv)

    print(f"Seeking root of {func}.")
    print("NEWTON-RAPHSON METHOD:")

    for i in range(1, MAXIT):
        iterated_x = x0 - (f(x0)/ddx(x0))
        x0 = iterated_x
        print(f"Iteration", i, x0)

        if f(x0) < tol:
            print(f"The root converges to {x0} after {i} iterations.")
            break
        elif i==MAXIT and f(x0) > tol:
            print("After maximum iterations, root was not found.")

newtonraphson('x**2-4*x+2', '2*x-4', 0.75,10**(-4), 100)
newtonraphson('math.exp(-x) + x - 7', '-(math.exp(-x)) + 1', 0.75,10**(-4), 100)

While my script is successfully able to find the roots for the equations I am interested in, I am stuck with a simpler problem. Basically, I want to tell my program that if after maximum iterations, my tolerance condition is not fulfilled, print "Method Failed".
However, my code does not print the statement I want it to when I experiment with functions that don't coverage when maximum iterations is set at 100 and tolerance is set to 0.0001.
Is my syntax right for the fail print statement?
Do conditions like "if i==MAXIT and f(x0) > tol" make sense in the context of the function I have written?
I would appreciate any and all advice for this issue as I am trying hard to improve at Python.
Thank you.

A: The problem you are facing is that range in python only function from the start index to one before the end index. That is, range(0,3) goes over the numbers (0,1,2). What is happening in your code is that you simply fail to activate the fail condition because the index never actually reaches that value. However, the fix is easy. In your functions where you say:
for i in range(1,MAXIT):
    if f(x0) < tol:
        print(f"The root converges to {x0} after {i} iterations.")
        break
    elif i==MAXIT and f(x0) > tol:
        print("After maximum iterations, root was not found.")

simply replace it with
for i in range(1,MAXIT):
    if f(x0) < tol:
        print(f"The root converges to {x0} after {i} iterations.")
        return

print("After maximum iterations, root was not found.")

instead. What this will do is stop the function if it finds the solution, and give you your error message if you manage to get through the entire loop without finding the answer.

A: A good way to achieve this in Python is to use the for\else construct.  Essentially, if you hang an "else" clause off of your for loop, it will execute if the loop doesn't terminate early due to a break statement.  It's very useful for loops that are searching for something, and root finding definitely fits that mold.  So your fixed point iteration loop would look like:
for i in range(0, MAXIT):
    iterated_x = g(iterated_x)
    condition = abs(g(iterated_x) - (iterated_x))
    if condition < tol:
        print(f"The root converges to {iterated_x} after {i+1} iterations.")
        break
else:
    print("ERROR: The root did not converge after maximum iterations.")

One advantage of doing it this way is that it doesn't matter if you change your success criteria in the loop--the else clause runs if you don't declare success with the break statement no matter how success is defined.


text:
Q: Reachability relation set How can i define reachable relation set of R for a given di-graph below?

A: The reachability relation $R$ for that digraph is the set of all ordered pairs of vertices $\langle x,y\rangle$ such that there is a directed path from $x$ to $y$ in the graph. For example, $\langle b,d\rangle\in R$ by virtue of the path $b\to f\to d$, and $\langle c,c\rangle\in R$ by virtue of the path $c\to d\to c$.
Start with vertex $a$; what vertices can you reach via directed paths from $a$? Then go on to vertices $b,c,d,e$, and $f$ in turn and answer the same question.
There are other ways to find $R$ — using the adjacency matrix of the digraph, for instance — but this is the most basic.


text:
Q: How to assign "*" to IfMatch - conditional header I download blob content from Azure blob storage. I am trying to set conditional header ETag value as "*".
When i give IfMatch = "*", says cannot implicitly convert string to Azure.ETag.
        Conditions = new BlobRequestConditions()
        {
           IfMatch = "*"

        }

How do I assign IfMatch to *. Thank you.

A: Not sure, but you are looking for this? You can not assign a String value to an ETag
IfMatch = new ETag("*")


text:
Q: Linking to jquery script file from master page or default page in ASP.NET I'm working with jquery ui in asp.net web forms I have loaded the libraries and everything is working ok but i can only run the scripts by placing the script in the head section of the master page or the default page. I cant seem to link to an external script file and run the script from it.
I have this in the head of my master page:
  <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
  <script src="Scripts/js/jquery-ui-1.8.13.custom.min.js" type="text/javascript"> </script>
  <script src="Scripts/myscript.js" type="text/javascript"></script> <!--this does not load -->
  <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
  <link href="Scripts/css/jquery-ui-1.8.13.custom.css" rel="stylesheet" type="text/css"   />

I have tried various things but it doesn't seem to work
Any ideas what I'm doing wrong ?

A: your script cannot be found because of the relative location from the master page.
Try
 <script src='<%= ResolveUrl("~/Scripts/js/jquery-ui-1.8.13.custom.min.js")%>' type="text/javascript"></script>


text:
Q: Change the value of a variable inside a function I want to change a value in the stack inside another function.
int Function(int *var){
    int i=125;
    var = i;
}
int Function2(){
    int apple;
    Function(&apple);
    printf("%d", apple);
}

This shows me error: assignment makes pointer from integer without a cast at this line var = 125;.
I want to copy the value of i into var in order to get apple = 125. (But when I will leave the Function, i inside the stack will be freed.)
I don't see where I made a mistake.

A: You need to dereference the pointer.
*var = 125;

As written you are trying to change the address stored in the pointer (i.e., the thing the pointer is pointing to).

A: In your code int *var = &apple Occur.
Imagine that apple variable stored at address 0x1000000,
So var holds the address of apple. so var pointing to 0x1000000.
If you do var = i then var variable leave 0x1000000 address and hold new address as value of i which is 125, which is invalid as lower memory address can't be accessible.
So you must have to do *var = i, as this fulfill your requirement.


text:
Q: conda create environment command gives 'Found conflicts! Looking for incompatible packages.' I installed miniconda via choco install miniconda3.
Creating a python3 environment works fine.
conda create --name envA python=3 --verbose

But creating a python2 environment has a problem.
conda create --name envB python=2 --verbose

Collecting package metadata (current_repodata.json): ...working... done
Solving environment: ...working... failed with repodata from current_repodata.json, will retry with next repodata source.
Collecting package metadata (repodata.json): ...working... done
Solving environment: ...working...
Found conflicts! Looking for incompatible packages.
failed
Traceback (most recent call last):
...

File "C:\Users\fred\miniconda3\lib\site-packages\conda\resolve.py", line 352, in find_conflicts
    raise UnsatisfiableError(bad_deps, strict=strict_channel_priority)
conda.exceptions.UnsatisfiableError

A: @cel gets credit for this
Switching to mamba provided better diagnostics.
mamba create -n foo python=2

Looking for: ['python=2']

conda-forge/win-64                                          Using cache
conda-forge/noarch                                          Using cache
Encountered problems while solving:
 - nothing provides vc 9.* needed by python-2.7.12-0

Then use mamba to find vc.
mamba search vc

# Name                       Version           Build  Channel
vc                              14.1      h21ff451_1  conda-forge
vc                              14.1      h6d1b3ff_2  conda-forge
...

The vc v9 can be found in the defaults channel.
mamba search 'vc[channel=defaults]'

# Name                       Version           Build  Channel
vc                                 9      h2eaa2aa_6  pkgs/main
...

Updating the .condarc with the defaults channel, corrected the problem.
channels:
  - conda-forge
  - defaults
channel_priority: disabled

As a final note, should someone else find themselves in this situation...
The ~/.condarc got changed (dropping the defaults channel) as part of installing mambaforge.


text:
Q: How to fix the subcaption and add borders like panel using multicol in latex? In the code, I want the captions of each image to start with (a), (b), etc. and I want to add borders. But it is coming as a separate figure number. I tried using subfigure, but then all the images in a single column.
First I tried-
\documentclass{article}
\usepackage{multicol}
\usepackage{graphicx}
\usepackage{float}

\begin{document}

\begin{figure}[H]
\begin{multicols}{2}
\includegraphics[width=\linewidth]{countyeffect}
\caption{Random effect due to counties obtained from spline coefficients}
\label{fig7:a} \par
\includegraphics[width=\linewidth]{statemean}\caption{Mean value of states}
\label{fig7:b} \par
\end{multicols}
\begin{multicols}{2}
\includegraphics[width=\linewidth]{stateslope} \caption{Effect due to slopes}
\label{fig7:c} \par
\includegraphics[width=\linewidth]{overalllocation}\caption{Overall location effect due to variation in states and counties}
\label{fig7:d} \par
\end{multicols}
\caption{Illustration of different kind of location effects}
\end{figure}

\end{document}

source: Multiple figures in a two column latex file
I get the following image-

But when I try
\begin{figure}[H]
\begin{multicols}{2}
\begin{subfigure}{.5\textwidth}
\includegraphics[width=\linewidth]{countyeffect}
\caption{Random effect due to counties obtained from spline coefficients}
\label{fig7:a}
\includegraphics[width=\linewidth]{statemean}\caption{Mean value of states}
\label{fig7:b}
\end{subfigure}%
\end{multicols}
\begin{multicols}{2}
\begin{subfigure}{.5\textwidth}
\includegraphics[width=\linewidth]{stateslope} \caption{Effect due to slopes}
 \label{fig7:c}
 \includegraphics[width=\linewidth]{overalllocation}\caption{Overall location effect due to variation in states and counties}
  \label{fig7:d}
  \end{subfigure}%
  \end{multicols}
  \caption{Illustration of different kind of location effects}
  \end{figure}

Then the subfigures are starting with (a), (b) etc. but I am getting a single column of all the images.
But I want something like following-

Thanks.

A: Use the subfig or subcaption package, not subfigure (not longer maintained). You do not need the  multicol package for a 2x2 layout:

\documentclass{article}
\usepackage{graphicx}
\usepackage{subfig}
\begin{document}
\begin{figure}
\subfloat[\label{fig7:a}][Random effect due to counties
obtained from spline coefficients]
{\includegraphics[width=.45\linewidth]{example-image}}\hfill
\subfloat[\label{fig7:b}][Mean value of states]
{\includegraphics[width=.45\linewidth]{example-image-a}}\par
\subfloat[\label{fig7:c}][Effect due to slopes]
{\includegraphics[width=.45\linewidth]{example-image-b}}\hfill
\subfloat[\label{fig7:d}][Overall location effect due to variation
in states and counties]
{\includegraphics[width=.45\linewidth]{example-image-c}}
 \caption{Illustration of different kind of location effects}
 \end{figure}
\end{document}

If you want borders, the simplest could be a basic 2x2 tabular:

subfig version:
\documentclass{article}
\usepackage{graphicx}
\usepackage{subfig}
\begin{document}
\begin{figure}
\centering
\begin{tabular}{|c|c|}
\hline
\subfloat[\label{fig7:a}][Random effect due to counties obtained
from spline coefficients]
{\includegraphics[width=.45\linewidth]{example-image}} &
\subfloat[\label{fig7:b}][Mean value of states]
{\includegraphics[width=.45\linewidth]{example-image-a}}\\\hline
\subfloat[\label{fig7:c}][Effect due to slopes]
{\includegraphics[width=.45\linewidth]{example-image-b}} &
\subfloat[\label{fig7:d}][Overall location effect due to variation
in states and counties]
{\includegraphics[width=.45\linewidth]{example-image-c}}\\\hline
\end{tabular}
 \caption{Illustration of different kind of location effects}
 \end{figure}
\end{document}

subcaption version:
\documentclass{article}
\usepackage{graphicx}
\usepackage{subcaption}
\begin{document}
adasd
\begin{figure}
\centering
\begin{tabular}{|c|c|}\hline
\begin{subfigure}[c][5.5cm][c]{.45\linewidth}
\smallskip\includegraphics[width=\linewidth]{example-image}
\caption{Random effect due to counties obtained from
spline coefficients}
\vfill\label{fig7:a}\end{subfigure} &
\begin{subfigure}[c][5.5cm][c]{.45\linewidth}
\smallskip\includegraphics[width=\linewidth]{example-image-a}
\caption{Mean value of states}
\vfill \label{fig7:b}\end{subfigure}\\\hline
\begin{subfigure}[c][5.5cm][c]{.45\linewidth}
\smallskip\includegraphics[width=\linewidth]{example-image-b}
\caption{Effect due to slopes}
\vfill \label{fig7:c} \end{subfigure} &
\begin{subfigure}[c][5.5cm][c]{.45\linewidth}
\smallskip\includegraphics[width=\linewidth]{example-image-c}
\caption{Overall location effect due to variation in
states and counties}
\vfill\label{fig7:d}\end{subfigure} \\\hline
 \end{tabular}
\caption{Illustration of different kind of location effects}
\end{figure}
\end{document}


text:
Q: SPMetal Person column generation I'm using SPMetal to generate a class for my lists to use in a Sandbox-solution (with Sandbox Visual WebParts).
However, when I generate the classes for a list column of type "Person or Group" with display value "Name with Picture", I only get the string for that person's name back (SPMetal only generates a string property for this field).
[Microsoft.SharePoint.Linq.ColumnAttribute(Name = "Person", Storage = "_personNameWithPicture", ReadOnly = true, FieldType = "User", IsLookupValue = true)]
public string PersonNameWithPicture
{
    get
    {
        return this._personNameWithPicture;
    }
    set
    {
        if ((value != this._personNameWithPicture))
        {
            this.OnPropertyChanging("PersonNameWithPicture", this._personNameWithPicture);
            this._personNameWithPicture = value;
            this.OnPropertyChanged("PersonNameWithPicture");
        }
    }
}

Is there any way to get both the person's name and the profile picture, like it does in the default list view?
Thanks

A: i'm afraid you can't get the profile picture directly.
linq to sharepoint can retrieve only id or displayname from a User field (lookup field) by set the ColumnAttribute  IsLookupValue = true or IsLookupId = true
so you can get a spuser object by the userid first, then get the profile picture.


text:
Q: Bit flipping algorithm implementation or psuedo-code I am trying to understand and implement Bit flipping algorithm
Can someone share the psuedocode for the algorithm and explain in detail? I cannot understand the answer.
I also want to understand what topic this question falls under (like Dynamic Programming or Optimization).

A: The answer was saying to build up the string of all $1$ incrementally from the beginning: to have first bits $1$, then to have first two bits $1$, ..., then to have the first $n-k+1$ bits all in $1$.
The algorithm is that if the first $i-1$ bits are all $1$ and the $i$th bit is $0$  (where $1 \le i \le n-k+1$), then flip the bits from $i$ to $i+k-1$ inclusive will make at least the first $i$ bits all $1$.


text:
Q: Paperclip is processing attachments even when they don't pass validation? I have a model that uses paperclips for image attachments
I currently require that the attachment be an image using a validation
validates_attachment_content_type :image, :content_type => /^image\/(jpg|jpeg|pjpeg|png|x-png|gif)$/, :message => 'file type is not allowed (only jpeg/png/gif images)'

However when I try to upload a non-image I get these error messages.
Image /var/folders/1f/0jtzzpl56sdcb92spkx6rpch0000gn/T/10-21-201120120908-44073-j59q0s.pdf is not recognized by the 'identify' command.
Image /var/folders/1f/0jtzzpl56sdcb92spkx6rpch0000gn/T/10-21-201120120908-44073-j59q0s.pdf is not recognized by the 'identify' command.
Image content type file type is not allowed (only jpeg/png/gif images)

So it seems like the file is being passed to ImageMagick even though the file does not pass the validation. I want the last error message only and not the first 2.
How can I either suppress the two first messages or make sure that the file is not processed unless it passes the content type validation?

A: Check out following link, you might find your solution here by adding custom method
https://groups.google.com/forum/?fromgroups=#!topic/paperclip-plugin/oVnIgfAfrLU
Thanks,
Nidhi Sarvaiya

A: Solved with
before_post_process :process_only_images

def process_only_images
    if !(image.content_type =~ %r{^(image|(x-)?application)/(x-png|pjpeg|jpeg|jpg|png|gif)$})
      return false
    end
end


text:
Q: CI3.0 passing variable between controller and module I have this method:
public function signup_validation()   {
//definizioni setting per email di conferma
  $emailsetting = array('mailtype' => 'html' );
  $emailfrom = 'misure@lagiumentabardata.netsons.org';
  $emailsubject ='Conferma registrazione';

$this->load->library('form_validation');

$this->form_validation->set_rules('email','Email','required|trim|valid_email|is_unique[user.email]'); //check se la mail è davvero una mail valida e se esiste gia nel database     $this->form_validation->set_rules('password','Password','required|trim');   $this->form_validation->set_rules('cpassword','Conferma Password','required|trim|matches[password]');

$this->form_validation->set_message('is_unique','email già esistente nel nostro database'); //override messaggio di errore

//check se il form è valido allora passa altrimenti ritorna al form.    if ($this->form_validation->run() == true) {
    //generare key
  $key = sha1(uniqid());
  //inviare una mail all'utente
  $this->load->library('email', $emailsetting); //caricamento libreria
  $this->load->model('model_users'); //caricamento modello per il controllo del db utente

  $this->email->from($emailfrom,'La Giumenta Bardata');
  $this->email->to($this->input->post('email'));
  $this->email->subject($emailsubject);

  $emailmessage = "
ciao mondo

                  click qui"; //fare riferimento alla funzione register_user

  $this->email->message($emailmessage);

  //controllo scrittura dell'utente nel db
  if ($this->model_users->add_temp_user($key) == true) { //passaggio chiave al modello che si occupa di aggiungerlo al DB
    //invio email utente
    if ($this->email->send() == true) {
      echo "email inviata correttamente";
    } else { echo "errore nell'invio stronzo";}
  } else { echo "problemi nell'inserimento del db"; }

} else {
    echo '';
    $this->registrazione();     }   }

In a signup.php controller.
First of all I don't understand why if I move $emailmessage variable where I set all the variables ($emailsetting, $emailfrom etc.) I get an error that the $emailmessage variable is undefined -.-
but, the real problem is that i can't pass the $key variable to a module:
 public function add_temp_user($key){

 $data = array('email' => $this->input->post('email'),
               'nome' => $this->input->post('nome'),
               'cognome' => $this->input->post('cognome'),
               'password' => md5($this->input->post('password')),
               'userkey'=>$key
               );

  $query = $this->db->insert('temp_users',$data);  //generazione query

  //check se la query è stata eseguita correttamente
  if ($query) {
    return true;
  } else {
    return false;
  }
 }

How can I pass a variable from a controller to a module? I try everything, from set the $key as public to set the __construct and nothing work...when the app needs to call the model I have an Undefined $key variable..
Thanks for help

A: You can move $emailmessage = up where the other things are set. But the line $key = sha1(uniqid()); must come before those assignments.
I tested this as best I could without having your database. Seems to work. $key makes it to the model anyway.
Notice that I build the link  'html');
    $emailfrom = 'misure@lagiumentabardata.netsons.org';
    $emailsubject = 'Conferma registrazione';
    $emailmessage = "
ciao mondo

      click qui"; //fare riferimento alla funzione register_user

    $this->load->library('form_validation');

    $this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email|is_unique[user.email]'); //check se la mail è davvero una mail valida e se esiste gia nel database     $this->form_validation->set_rules('password','Password','required|trim');   $this->form_validation->set_rules('cpassword','Conferma Password','required|trim|matches[password]');

    $this->form_validation->set_message('is_unique', 'email già esistente nel nostro database'); //override messaggio di errore
//check se il form è valido allora passa altrimenti ritorna al form.    if ($this->form_validation->run() == true) {
    //inviare una mail all'utente
    $this->load->library('email', $emailsetting); //caricamento libreria
    $this->load->model('model_users'); //caricamento modello per il controllo del db utente

    //use chaining here, much more efficient
    $this->email
        ->from($emailfrom, 'La Giumenta Bardata')
        ->to($this->input->post('email'))
        ->subject($emailsubject)
        ->message($emailmessage);

    //controllo scrittura dell'utente nel db
    if($this->model_users->add_temp_user($key))
    { //passaggio chiave al modello che si occupa di aggiungerlo al DB
      //invio email utente
      if($this->email->send() == true)
      {
        echo "email inviata correttamente";
      }
      else
      {
        echo "errore nell'invio stronzo";
      }
    }
    else
    {
      echo "problemi nell'inserimento del db";
    }
//these lines are not connected to anything as you have them in your question.
// So I have commented them out
//else {
//    echo '';
//    $this->registrazione();     }
  }

Here's the model function.
I capture the inputs like this input->post(NULL, TRUE); because it grabs all the inputs at once. That eliminates multiple calls to input->. With the second argument=TRUE the inputs are sanitized.
Because db->insert() returns either true or false there is no need for the if/then statement.
  public function add_temp_user($key)
  {
    $posted = $this->input->post(NULL, TRUE);
    $data = array('email' => $posted('email'),
        'nome' => $posted('nome'),
        'cognome' => $posted('cognome'),
        'password' => md5($posted('password')),
        'userkey' => $key
    );
    //tornare successo o il fallimento di ricerca
    return $this->db->insert('temp_users', $data);  //generazione query
  }


text:
Q: Adding a location that is tied to a userID via Foreign Key I'm learning .NET here and have build a small API that allows me to register users, retrieve user lists, or a single user, as well as edit them.  Microsoft Identity is used for most of this process.
I am now trying to add new section to this API that will handle physical locations.  Each location will be tied back to a specific user, so there may be one or multiple locations per user.  I'm having trouble building this part of it though.  I cant seem to figure out how to tie the ID of the user to the location as a foreign key.  I've been battling this one now for quite some time.
I have the controller build for the location calls, and the DTO's, but it does not seem to want to actually work correctly.
Anyone up to talking a look and letting me know what needs to be done and how to do this? I'm a bit lost and really wanting to learn how this works. The github repo with the full working project is here:
https://github.com/sapper6fd/API

A: The issue at hand here was the way it was configured.
The following adjustments fixed the issue:
CreateLocation() method:
[HttpPost]
        public async Task<IActionResult> CreateLocation(int clientId, LocationCreateDto locationCreateDto)
        {
            //  Grab the current users roles to verify they have access to this API call
            var userRole = User.FindFirst(ClaimTypes.Role).ToString();

            if (userRole != "http://schemas.microsoft.com/ws/2008/06/identity/claims/role: GlobalAdmin")
                return Unauthorized();

            // Create the new location
            var newLocation = _mapper.Map<Locations>(locationCreateDto);

            _repo.Add(newLocation);

            if (await _repo.SaveAll())
            {
                var locationToReturn = _mapper.Map<LocationCreateDto>(newLocation);
                return CreatedAtRoute(nameof(GetLocation), new { id = locationToReturn.Id, userid=clientId }, locationToReturn);
            }
            throw new Exception("Unable to create new location. Failed to save.");
        }

HttpGet Method:
[HttpGet("{id}", Name = nameof(GetLocation))]
        public async Task<IActionResult> GetLocation(int id)
        {
            var location = await _repo.GetLocation(id);

            var locationToReturn = _mapper.Map<LocationCreateDto>(location);

            return Ok(locationToReturn);
        }


text:
Q: Free all the memory allocated by malloc(), realloc() in C I'm trying to free() all the allocated memory by malloc(), realloc() but valgrind says that the is a memory leak.
The code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) {

    int lines_allocated = 128;
    int max_line_len = 50;

    FILE *fp;

    /* File allocate lines of text */
    char **array = (char **)malloc(sizeof(char*)*lines_allocated);
    if (array==NULL) {
        fprintf(stderr,"Out of memory (1).\n");
        exit(1);
    }

    FILE *file = fopen("file.txt", "r");
    if (file == NULL) {
        fprintf(stderr,"Error opening file.\n");
        exit(2);
    }

    int il;
    for (il = 0; 1; il++) {
        int j;

        /* Have we gone over our line allocation? */
        if (il >= lines_allocated) {
            int new_size;

            /* Double our allocation and re-allocate */
            new_size = lines_allocated*2;
            array = (char **)realloc(array,sizeof(char*)*new_size);

            if (array==NULL) {
                fprintf(stderr,"Out of memory.\n");
                exit(3);
            }

            lines_allocated = new_size;
        }

        /* Allocate space for the next line */
        array[il] = malloc(max_line_len);
        if (array[il]==NULL) {
                fprintf(stderr,"Out of memory (3).\n");
                exit(4);
            }
        if (fgets(array[il], max_line_len-1, file)==NULL)
            break;

        /* Get rid of CR or LF at end of line */
        for (j=strlen(array[il])-1;j>=0 && (array[il][j]=='\n' || array[il][j]=='\r');j--)
            ;

        array[il][j+1]='\0';
    }

    /* Close file */
    fclose(file);

    /* Print and free the every element of the array */
    int cc;
    for (cc = 0; cc < il; cc++) {
        printf("%s\n", array[cc]);

        /* Free the every element of the array */
        free(array[cc]);
    }

    /* Free hole array */
    free(array);

    return 0;
}

valgrind ./main
valgrind --leak-check=full --show-reachable=yes ./main
==4806== Memcheck, a memory error detector
==4806== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==4806== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==4806== Command: ./main
==4806==
1
2
3
4
5
6
7
8
9
10
11
==4806==
==4806== HEAP SUMMARY:
==4806==     in use at exit: 50 bytes in 1 blocks
==4806==   total heap usage: 14 allocs, 13 frees, 2,192 bytes allocated
==4806==
==4806== 50 bytes in 1 blocks are definitely lost in loss record 1 of 1
==4806==    at 0x4C2AC3D: malloc (vg_replace_malloc.c:299)
==4806==    by 0x40092E: main (in /var/www/mem/main)
==4806==
==4806== LEAK SUMMARY:
==4806==    definitely lost: 50 bytes in 1 blocks
==4806==    indirectly lost: 0 bytes in 0 blocks
==4806==      possibly lost: 0 bytes in 0 blocks
==4806==    still reachable: 0 bytes in 0 blocks
==4806==         suppressed: 0 bytes in 0 blocks
==4806==
==4806== For counts of detected and suppressed errors, rerun with: -v
==4806== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

How to free the memory correctly? It says that there should one more block of memory to free but where is it?

A: Just replace
for (cc = 0; cc < il; cc++)

with
for (cc = 0; cc <= il; cc++)

To figure that out, imagine what happens if allocating loop for (il = 0; 1; il++) iterates only once. In this case control does not reach il++, so il remains zero and for (cc = 0; cc < il; cc++) iterates zero times. In general case the freeing loop makes one iteration less than allocating loop.

A: Your code leaks the last allocation, because il is never incremented when fgets(array[il], max_line_len-1, file) returns NULL.
Moving array[il] = malloc(max_line_len); along with its NULL check to after fgets will fix this problem. An added benefit to this approach is that you can make your allocations of the exact size, rather than allocating at max_line_len.
// Check that we will need the allocation
char temp[max_line_len];
if (fgets(temp, max_line_len-1, file)==NULL) {
    break;
}
// Allocate only when we are sure that we are going to need it
temp[max_line_len-1] = '\0';
size_t len = strlen(temp);
array[il] = malloc(len+1);
if (array[il]==NULL) {
    fprintf(stderr,"Out of memory (3).\n");
    exit(4);
}

Note: assigning realloc back to the variable being reallocated could result in leaking the memory that has been previously allocated to that variable. It is not a problem in your code, because you call exit(4) right away, but you should be aware of the general problem with this assignment.

A: If you're having miscellaneous problems, and intermixing calls to various allocators, and are awfully persnickety about things, then implement a wrapper for the various memory allocators (this can be done cleverly using macros) that caches the address of the newly allocated buffer somewhere (e.g., atop a stack) and then--at some point--navigates the stack and frees everybody.  Don't intermix random calls here and there to free() or its analogues.  When something is freed, overwrite the something with zero so you don't accidentally try to free() it a second time, which will upset free().
HOW TO CLEVERLY USE MACROS (I said it, so I'd better make it work now) and avoid recursive problems:
Let's use malloc() as our first victim.
In another source file, create a function _malloc() that calls malloc().
In the source file that contains all your memory allocation and deallocation, define malloc() as follows:
#define malloc( n )  ( *sp++ = _malloc( n ) )

There has to be code invoked as a preamble that sets up a stack and points sp at its base.  Make it nice and big: you'd be surprised how many times malloc() and its brethren may end up being called.  At various times — when it's appropriate, actually — call your own free_all() that does this:
void free_all() {
  while( --sp >= base_of_malloc_buf_stack ) {
    free( *sp );
    *sp = 0; /* avoid future re-free() */
  }
}

A: for (cc = 0; cc < il; cc++) {

If il is a valid index of array (and it is), the comparison in the loop should be:
for (cc = 0; cc <= il; cc++) {

in order to trigger the very last element of array (and free its memory).


text:
Q: How can I add a preconfigured/template Xcode breakpoint? About 80% of the time, when I add an Xcode breakpoint I want it to have:

*

*An action of "Log Message"

*The text of "%B %H" to print to the console when it's encountered

*The "Automatically continue" checkbox checked

Setting this up is possible, but tedious. I know that you can create a breakpoint like this in LLDB using a breakpoint set command, which I could alias. However, I believe that this would require the debugger to be running and paused. It also forgets the breakpoint when the process ends, and doesn't show up in Xcode.
What I'd really like is to be able to run a script via a keyboard command from within Xcode to set my template breakpoint on the current line.
Is there any way to do this?


text:
Q: bxslider stop on mouse hover custom pagination I have a bxSlider on my webpage.
I'm trying to stop slider when mouse hover my custom paginator.
Here is my html:

'.$sliderTitle.'

'.$sliderTitle.'

'.$slideIndexShow++.'

'.$slideIndexShow++.'

And here is my js;
// Main Slider
var slider = jQuery('#slider').bxSlider({
    auto: true,
    speed: 500,
    delay: 5000,
    autoHover: true,
    stopAuto: false,
    pagerCustom: '#slider-paginate'
});

Here is what i've tried so far:
$(document).on('hover','#slider-paginate',function() {
     slider.stopAuto();
     slider.startAuto();
});

Unfortunately it didn't work. What am i missing? What is wrong with my javascript code?
How can i stop bxslider when mouse is hover on paginator elements?

A: I found answer myself;
i used 2 events;
First one for hover and other for mouseleave
Solution:
$('#slider-paginate').hover(function(){
     slider.stopAuto();
});
$('#slider-paginate').mouseleave(function(){
     slider.startAuto();
});


text:
Q: Stop a looping GIF icon I am using an animated GIF image as icon to button.
But this GIF loops without stopping.
How can I play this GIF icon animation just once?

A: When creating an animated GIF, there are options to have it only loop a single time. That is where you need to look for a solution to this problem. Swing itself provides no methodology to change the behavior.


text:
Q: XMLHttpRequest not working (blank page) I copied this code from W3Schools (along with the original XML file cd_catalog.xml) and I'm getting a blank page:

I tried Opera, Firefox, IE and Chrome.
Nothing. :(

A: Since you're not using a web server try doing this:
xmlhttp.open("GET","file:///C:/cd_catalog.xml", false);

You may end up needing a web server because the browsers will not allow your script access to the local files, e.g. see discussion here:
http://www.webdeveloper.com/forum/showthread.php?t=233306
So consider setting up a simple web server on your machine, like lighttpd.
EDIT: the way I interpret the spec ( http://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#the-open%28%29-method ) is that this must be done through HTTP.  It's not absolutely clear though. A file: URL may not be allowed in this context so the expectation is that the code snippet above may not work and you will need a web server.
A related question is:
Read file:// URLs in IE XMLHttpRequest
and
Allow Google Chrome to use XMLHttpRequest to load a URL from a local file

A: Upload your code to a web server. You will get the desired output on all browsers such as IE, Chrome, or Mozilla. But if you try this same code on the local machine, then IE and Chrome won't work.


text:
Q: Time changes of the Itō integral Let $(B_t^1, \ldots, B_t^d)$ be a standard $d$-dimensional Brownian motion, and $H_t^j$, $j=1, \ldots d$ be continuous processes adapted to the filtration $\{\mathcal{F}_t\}$. Let
$$Z_t = \sum_{j=1}^d \int_0^t H_s^j dB_s^j$$
$$\langle Z \rangle_t = \sum_{j=1}^d \int_0^t (H_s^j)^2 ds$$
where the above integrals are the Itō integral against Brownian motion. Suppose that with probability $1$, we have
$$\lim_{t \to \infty} \langle Z \rangle_t = \infty$$
and define stopping times $\tau_r$ by
$$\tau_r = \inf\{t : \langle Z \rangle_t = r\}$$
Then I want to show that $W_r = Z_{\tau_r}$ is a standard Brownian motion with respect to the filtration $\mathcal{F}_{\tau_r}$.
The way to do this is to let $y \in \mathbb{R}$ and apply Itō's formula to $Y_t := \exp(iyZ_t + y^2 \langle Z\rangle_t/2)$ in order to show that $Y_t$ is a local martingale. I do not see how to do this, can anyone help? What are we integrating to apply Itō's fomula? (Please explain all the steps as thoroughly as possible, I am very new to stochastic calculus and cannot fill in gaps to arguments yet).

A: I think the best way to show that a continuous process is actually a Brownian motion is to use Paul Lévy's characterisation. That is, to show that the quadratic variation of this process is equal to r.
By the way this is a particular case of a slightly more general result known as Dambis-Dubins-Schwarz theorem. You can find its proof for example in the book of Karatzas and Shreve "Brownian Motion and Stochastic Calculus"
Best Regards


text:
Q: How to switch to a window for which Title is not defined Title is not defined in the window, so getTitle() makes no sense
// Getting current/ Parent window handle
String currentWindoHadle= driver.getWindowHandle();

// Switch to PrintStandardInv window
CustomSeleniumMethods.switchToWindowByTitle(driver, "", tests);

public static void switchToWindowByTitle(WebDriver driver, String windowTitle, ExtentTest tests) throws IOException

{
try {
boolean isWindowFound=false;
String currentWindoHadle1= driver.getWindowHandle();
Set<String> allWindowHandles1= driver.getWindowHandles();
for(String h:allWindowHandles1)
{
if(!h.equals(currentWindoHadle1))
driver.switchTo().window(h);
String title= driver.getTitle();
        System.out.println("title inside function call " + title);
        if(title.equals(windowTitle))
        {
            tests.pass("Switched to window title: "+windowTitle);
            driver.manage().window().maximize();
            isWindowFound=true;
            break;
        }

This works, however can anyone please suggest a better way to switch to a window where Title is not defined. Please refer emage. Here using getTitle() makes no sense for comparing with "" blank window Title

A: I solve this problem Like
 if(driver.getCurrentUrl().startsWith("https://www.google."))
  {
                //your condition

  }

We just get current URL and if my targeted URL starts with or contains something then we can write code like this way


text:
Q: Can I add array to android buttons? My button is:
  <Button
      android:text=""
      android:id="@+id/b1"
      android:gravity="center_horizontal"
      android:layout_width="100dp"
      android:layout_height="100dp"
      android:background="@drawable/the_border"
      android:textSize="75sp"/>

And I have many of them (b0, b1, b2)...
My java:
    for(int index = 0; index < 9; index++)
    {
        places[index] = (Button) findViewById(R.id.b + index);
        places[index].setOnClickListener(this);
    }

How could I do this? findViewById(R.id.b + index) needs to be changed. Is it possible? Thanks

A: Use the tag property to give them sequential tags of 0, 1, 2, etc., then findViewWithTag() in a loop to build an array. Note that tag is a string, it's not numeric.

A: In that way you are not adding that buttons at the layout.
1) you cannot give to those buttons (or container/element in general) the same ID. An id is an unique identifier so it has to be unique
2) findViewById will search into the layout three to find an element with that id. If that element don't exist (you are not adding them to the layout) it will fail with a nullpointerexception.
What you have to do is to create Buttons from your java code and add them to a container (for example a LinearLayout).
So you do a findViewById and look for the container, then you add View (the button) to that container.
Do you need a code example?