text:
Q: How to add JRadioButton to two columuns of a JTable and ButtonGroup them. I  want a JTable which consists of 2 columns(having RadioButton) Active and Inactive  such that if Active Column is Selected then Inactive RadioButton gets Unselected and Vice versa means that in a single row only 1 radiobutton can be selected out of 2 radiobuttons. the code for radiobutton is below . I am not able 2 add buttongroup for this 2 columns.
 public class NewJFrame extends javax.swing.JFrame {
    DefaultTableModel dt;
    public JRadioButton radioButton=new JRadioButton();

       public class RadioButtonCellEditorRenderer extends AbstractCellEditor implements TableCellRenderer, TableCellEditor, ActionListener {

            public RadioButtonCellEditorRenderer() {

                radioButton.addActionListener(this);
                radioButton.setOpaque(false);
            }

            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                radioButton.setSelected(Boolean.TRUE.equals(value));
                return radioButton;
            }

            @Override
            public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
                radioButton.setSelected(Boolean.TRUE.equals(value));
                return radioButton;
            }

            @Override
            public void actionPerformed(ActionEvent e) {
                stopCellEditing();
            }

            @Override
            public Object getCellEditorValue() {
                return radioButton.isSelected();
            }

        }

        public NewJFrame() {
            initComponents();

            for(int i=0;i <10;i++)
            {

                  //ButtonGroup bp[i]= new ButtonGroup();
            dt.addRow(new Object[]{null,false,false});

            }
           // jTable1.setValueAt(false, 5, 1);

        }

        /**
         * This method is called from within the constructor to initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is always
         * regenerated by the Form Editor.
         */
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {

            buttonGroup1 = new javax.swing.ButtonGroup();
            jScrollPane4 = new javax.swing.JScrollPane();
            jTable1 = new javax.swing.JTable();

            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

            dt= (new javax.swing.table.DefaultTableModel(new Object[][]{{null,null,null}},new String [] {"Name","Select", "Unselect"})
                {
                    Class[] types = new Class [] {java.lang.Integer.class,java.lang.String.class, java.lang.String.class};

                    public Class getColumnClass(int columnIndex) {
                        return types [columnIndex];
                    }
                    public boolean isCellEditable(int r,int c)
                    {

                        return true;
                    }
                });

                //JTextField textBox= new JTextField();
                jTable1.setModel(dt);
                TableColumn column = jTable1.getColumnModel().getColumn(1);
                column.setCellEditor(new RadioButtonCellEditorRenderer());
                column.setCellRenderer(new RadioButtonCellEditorRenderer());
                TableColumn column1 = jTable1.getColumnModel().getColumn(2);
                column1.setCellEditor(new RadioButtonCellEditorRenderer());
                column1.setCellRenderer(new RadioButtonCellEditorRenderer());
                jTable1.getTableHeader().setReorderingAllowed(false);
                jScrollPane4.setViewportView(jTable1);

                javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
                getContentPane().setLayout(layout);
                layout.setHorizontalGroup(
                    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(13, Short.MAX_VALUE))
                );
                layout.setVerticalGroup(
                    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(28, 28, 28)
                        .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 243, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(29, Short.MAX_VALUE))
                );

                pack();
            }// </editor-fold>

        /**
         * @param args the command line arguments
         */
        public static void main(String args[]) {
            /* Set the Nimbus look and feel */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
             * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
             */
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>

            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new NewJFrame().setVisible(true);
                }
            });
        }

A: This is a sample code which I have and I modified it and placed another JRadioButton in column 2 for your requirement. Both columns one and two are grouped row wise like ButtonGroup.
Output:

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;

 /** Dialog class **/
public class DisplayTable extends JDialog {
   public void initialize() {

   SourceTableModel stm = new SourceTableModel();
   JTable sourceTable = new JTable(stm);

   sourceTable.getColumnModel().getColumn(0).setCellRenderer(new RadioButtonRenderer());
   sourceTable.getColumnModel().getColumn(0).setCellEditor(new RadioButtonEditor(new JCheckBox()));

sourceTable.getColumnModel().getColumn(1).setCellRenderer(new RadioButtonRenderer());
sourceTable.getColumnModel().getColumn(1).setCellEditor(new RadioButtonEditor(new JCheckBox()));

JPanel panel = new JPanel();
panel.add(new JScrollPane(sourceTable));
add(panel, BorderLayout.CENTER);

JPanel btnPanel = new JPanel();
JButton btnApply = new JButton("Close");
btnPanel.add(btnApply);

btnApply.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent arg0) {
        System.exit(0);
    }
});

add(btnPanel, BorderLayout.SOUTH);

setTitle("Radio Button in JTable Example");
setModal(true);
pack();
setVisible(true);
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new DisplayTable().initialize();
        }
    });
}

}

/** Table Model class for the Table **/
class SourceTableModel extends AbstractTableModel  {

private static final long serialVersionUID = 1L;

private List<SourceModel> sourceList = new ArrayList<SourceModel>();
private String[] columnNamesList = {"Active", "InActive", "One", "Two"};

public SourceTableModel() {
    this.sourceList = getSourceDOList();
}

@Override
public String getColumnName(int column) {
    return columnNamesList[column];
}

@Override
public int getRowCount() {
    return sourceList.size();
}

@Override
public int getColumnCount() {
    return columnNamesList.length;
}

@Override
public Class<?> getColumnClass(int columnIndex) {
    return ((columnIndex == 0 || columnIndex == 1) ? Boolean.class : String.class);
}

@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
    return ((columnIndex == 0 || columnIndex == 1) ? true : false);
}

/**
     **Important:** Here when ever user clicks on the column one then other column values should be made false. Similarly vice-versa is also true.
**/
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
    SourceModel model = (SourceModel) sourceList.get(rowIndex);
    switch (columnIndex) {
case 0:
        model.setSelect(true);
        model.setInActive(false);
        fireTableRowsUpdated(0, getRowCount() - 1);
        break;
case 1:
        model.setSelect(false);
        model.setInActive(true);
        fireTableRowsUpdated(0, getRowCount() - 1);
        break;
case 2:
    model.setFactory((String) aValue);
    break;
case 3:
    model.setSupplier((String) aValue);
    break;
}
fireTableCellUpdated(rowIndex, columnIndex);
}

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
SourceModel source = sourceList.get(rowIndex);
//SourceModel source = getSourceDOList().get(rowIndex);
switch(columnIndex){
case 0:
    return source.isSelect();
case 1:
    return source.isInActive();
case 2:
    return source.getFactory();
case 3:
    return source.getSupplier();
default:
    return null;
}
}

/**
 * List for populating the table.
 * @return list of sourceDO's.
 */
private List<SourceModel> getSourceDOList() {
   List<SourceModel> tempSourceList = new ArrayList<SourceModel>();
   for (int index = 0; index < 5; index++) {

    SourceModel source = new SourceModel();
    source.setSelect(false);
    source.setInActive(false);
    source.setFactory("One " + index);
    source.setSupplier("Two " + index);

    tempSourceList.add(source);
}
return tempSourceList;
}
}

/** Class that is holding the model for each row **/
class SourceModel {

private boolean active;
private boolean inActive;
private String factory;
private String supplier;

public SourceModel() {
    // No Code;
}

public SourceModel(boolean select, boolean inActive, String factory, String supplier) {
    super();
    this.active = select;
    this.inActive = inActive;
    this.factory = factory;
    this.supplier = supplier;
}

public boolean isSelect() {
    return active;
}

public void setSelect(boolean select) {
    this.active = select;
}

public String getFactory() {
    return factory;
}

public boolean isInActive() {
    return inActive;
}

public void setInActive(boolean inActive) {
    this.inActive = inActive;
}

public void setFactory(String factory) {
    this.factory = factory;
}

public String getSupplier() {
    return supplier;
}

public void setSupplier(String supplier) {
    this.supplier = supplier;
}
}

/** Renderer class for JRadioButton **/
class RadioButtonRenderer implements TableCellRenderer {

    public JRadioButton btn = new JRadioButton();
    public Component getTableCellRendererComponent(JTable table, Object value,
      boolean isSelected, boolean hasFocus, int row, int column) {

      if (value == null)
          return null;
      btn.setSelected((Boolean) value);
      return btn;
  }
}

/** Editor class for JRadioButton **/
class RadioButtonEditor extends DefaultCellEditor implements ItemListener {

public JRadioButton btn = new JRadioButton();

public RadioButtonEditor(JCheckBox checkBox) {
    super(checkBox);
}

public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {

    if (value == null)
        return null;

    btn.addItemListener(this);

    if (((Boolean) value).booleanValue())
        btn.setSelected(true);
    else
        btn.setSelected(false);

    return btn;
}

public Object getCellEditorValue() {
    if(btn.isSelected() == true)
        return new Boolean(true);
    else
        return new Boolean(false);
}

public void itemStateChanged(ItemEvent e) {
    super.fireEditingStopped();
}
}

EDIT:
After defining columns in the table model you need to use Rendering and Editing for columns 0 and 1 using the following statement.
sourceTable.getColumnModel().getColumn(1).setCellRenderer(new RadioButtonRenderer());
sourceTable.getColumnModel().getColumn(1).setCellEditor(new RadioButtonEditor(new JCheckBox()));

Similarly you need to do for 2nd and 3rd columns (as you needed) also. One important step you have to look is setValueAt(..) method in the TableModel, you need to group columns (0, 1) and (2, 3) so when ever 0th column is selected then make 1st column as deselected and same is for 2 and 3 columns. Look at the setValueAt(..) method code below for case 2. When ever user selects second column then we will make that column as true and make third column as false. You just need to do the same for column-2 and column-3.
   case 2:
        model.setSelect(true);
        model.setInActive(false);
        break;


text:
Q: Parse CSV file which contains a new line to php array I have a CSV file with:
Test1,One line
Test2,"Two lines

Hello"
Test3,One line

As you can see, one of the columns has a value which is separated with a new line.
To parse this CSV file into an array, I run:
$csvArray = array();
$csvData = file_get_contents('file.csv');
$lines = explode(PHP_EOL, $csvData);
foreach ($lines as $line) {
    $csvArray[] = str_getcsv($line);
}
// print_r($csvArray);

It works beside one problem. It reads the new line in the value as a new row, which is completely incorrect.
How do I make it so that it properly reads a multi-line value?
Edit: this question focuses on new lines.

A: $fp = fopen('filecsv', 'r');

$csvArray = array();

while ($row = fgetcsv($fp)) {
    $csvArray[] = $row;
}

fclose($fp);

Using explode(PHP_EOL, $csvData) will not correctly split the CSV by its row delimitor.  The multi line cell is encapsulated with quotations meaning the row will continue onto new lines until they are closed.
PHP's built in fgetcsv function will correctly read a single row from a file, moving the pointer to the next row in the process. While str_getcsv will only read a single row from a string without considering additional rows (because its a string, not a stream).
Since you have already split the string with explode, your CSV row is broken, so the row will be incomplete.

redpajama_set_name: RedPajamaStackExchange


text:
Q: React component do not gets updated after changing the the state in componentDidMount I'm working on a react component that render a table with some data coming down from an API on the server as follows:

var ModulesTable = React.createClass({

    getInitialState: function () {
        return {
            modules: ""
        };
    },
    componentDidMount: function () {

        var get = $.get("/api/Modules/GetModules")
            .done(function (results) {

                if (results != null) {
                    var rows = results.map((module) => {

                        var statusImg;
                        if (module.IsActive)
                            statusImg = ;

                        return
                        (

                            {module.ModuleId}
                            {module.ModuleName}
                            {statusImg}

);
                    }
                    );
                    this.setState({
                        modules: rows
                    });
                }
            }
                .bind(this))
            .fail(function (err) {
                alert(err);
            });

    },
    render: function () {
        return (

                    ID
                    Name
                    Used

                {this.state.modules}

);
    }
});

ReactDOM.render(
    <ModulesTable />,
    document.getElementById("tableContainer"));

The problem is the component is not gets updated with the data returned from the API and the console show no signs of any error plus the API is working fine.
I suspect that the problem with setState probably.
what i'm doing wrong here?

A: this does not work with jQuery xhr callbacks. Just try this instead
    const self = this;
    var get = $.get("/api/Modules/GetModules")
        .done(function (results) {

            if (results != null) {
                var rows = results.map((module) => {

                    var statusImg;
                    if (module.IsActive)
                        statusImg = ;

                    return
                    (

                        {module.ModuleId}
                        {module.ModuleName}
                        {statusImg}

);
                }
                );
                self.setState({
                    modules: rows
                });
            }
        }
            .bind(this))
        .fail(function (err) {
            alert(err);
        });

A: I've found a solution by getting rid of map function and use the regular for loop fixed my problem as following :
componentDidMount: function () {

        var get = $.get("/api/Modules/GetModules")
            .done(function (results) {
                if (results != null) {

                    var rows = [];
                    for (var i = 0; i < results.length; i++) {
                        var module = results[i];

                        if (module.IsActive) {

                            rows.push(

                                    {module.ModuleId}
                                    {module.ModuleName}

                            );
                        }

                        else {
                            rows.push(

                                    {module.ModuleId}
                                    {module.ModuleName}

                            );
                        }

                    }

                    this.setState({
                        modules: rows
                    });

                    console.log(rows);
                }
            }.bind(this))
            .fail(function (err) {
                alert(err);
            });
    }

A: this.state.modules instead of modules, see demo @ https://jsfiddle.net/wv3yopo0/2674/


text:
Q: How to handle spring boot logout redirect in nginx? We have a spring boot web application application which redirects logout to index page with 301 redirect.
The following snipper we used in nginx to handle the redirect. But it is not getting redirected. 502 Bad gateway error is displayed.
location /UI/
{
proxy_pass http://localhost:6080/UI/;
proxy_set_header Host $http_host;
proxy_redirect / /;
proxy_intercept_errors on;
error_page 301 302 307 = @handle_redirects;
}
location @handle_redirects
{
set $saved_redirect_location '$upstream_http_location';
proxy_pass $saved_redirect_location;
}

Where UI is the name of the web application WAR running in tomcat.
In spring boot security.xml the following line is there.

Any advice?


text:
Q: Is it possible to create group chat dialog/room from the server instead of client? I am using ruby on rails at server side. I want to use quickblox as chat solution. And my requirement is to create group chat room from the server side instead of client side(android, ios). I am able to register user from the backend, but the issue is I am getting the following error, while creating a chat dialog, from the server.
I am using this link for integrating the quickblox api:
http://quickblox.com/developers/Chat#Create_dialog
Error {"errors":{"base":["Forbidden. Need user."]}}.

A: To create a dialog you need to be logged in
Use next request http://quickblox.com/developers/Authentication_and_Authorization#API_User_Sign_In


text:
Q: How to submit a form only if all the required attr fields are filled using bootstrap? I have to submit the form only if all the input fields which has the required="required" attribute.
My form:
<form method="post" action="/actions.php/" data-js-validate="true" data-js-highlight-state-msg="true" data-js-show-valid-msg="true">
    <input type="text" name="amount[]" required="required" placeholder="Amount" class="inputChangeVal" data-js-input-type="number" />
    <input type="text" name="grade[]" required="required" placeholder="Amount" class="inputChangeVal" data-js-input-type="number" />
    <button class="btn" type="submit" name="confirm" >Pay Now</button>
</form>

I wanted to submit the form after showing a message box.
As you see my form action is another php file.
so I prevent the default behavior and then send the form if the continue button is clicked.
I use bootsrap for that.
Bootstrap model :

                <button type="button" class="close" data-dismiss="modal">×</button>

Proccess Payment

                "Your about to make a online payment. Click 'Edit' to review the data before proceeding or click 'Continue' to confirm the details for payment."

                <button class="btn btn-default" data-dismiss="modal">Edit</button>
                <button class="btn btn-primary" id="continuebtn">Continue</button>

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

and the jQuery for that:

but this one sends the from if I click the button Continue button.
No matter the input fields are filled or not..
What I want is the form should be submitted only if the fileds required="required" are filled..
how can I do this?

A: first of all add a id attribute on your submit button with the name of 'payBtn'.
after that
replace the following jquery with your current js

by the way. if you use html 5 the and you don't do anything, every input filed with the required property will be checked by modern browsers automaticly. that's the reason because i don't use it if don't have to filter fields for special chars.

A: If $('#formid').submit() doesn't show the missing fields like when we click on submit button, then what about creating a hidden submit button and simulating a click?
If you put something like the following inside your form:
<input id="send" type="submit" style="display: none"/>

Now the JavaScript part:
    $(document).ready(function(){
        $('#continuebtn').on('click', function(event){
            $('#send').trigger('click');
        })
    });

You'll see that when you click on your #continuebtn you'll get the missing fields.
The browser already knows where are the missing fields. It's much more productive to reuse it instead of writing jquery calls and reinvent the wheel.
I believe that this is not the best solution but it works with very little modification of our code base.

A: You can easily make a field required by including required within the input type.
My example:

<input required type="text" name="PhoneNumber" id="phonenumber">


text:
Q: confusionMatrix - Error: `data` and `reference` should be factors with the same levels created a Logistic model:
Banks_Logit<- glm(Banks$Financial.Condition ~ .,data = Banks, family="binomial")
options(scipen=999)

summary(Banks_Logit)

then:
pred <-predict(Banks_Logit,Banks)
gain <-gains(Banks$Financial.Condition,pred,groups=20)

plot(c(0,gain$cume.pct.of.total*sum(Banks$Financial.Condition))~
   c(0,gain$cume.obs),
 xlab = "Observations", ylab = "Cumulative", main="Model Performance", type="l")
      lines(c(0,sum(Banks$Financial.Condition))~c(0,dim(Banks)[1]),lty=2)

library(caret)
confusionMatrix(ifelse(pred >0.5, 1,0), Banks$Financial.Condition)

error -
Error: data and reference should be factors with the same levels.
this is the pred data
        1                        2                        3                        4                        5                        6                        7                        8                        9                       10
0.9999999999999997779554 0.9999999999999997779554 0.9999999999999997779554 0.9999999999999997779554 0.9999999999999997779554 0.9999999999999997779554 0.9999999999138624584560 0.9999999999891036051025 0.9999999999995110577800 0.9999999999999997779554
                      11                       12                       13                       14                       15                       16                       17                       18                       19                       20
0.0000000000176082421301 0.0000000000352379135751 0.0000000000431425778626 0.0000000000000002220446 0.0000000000002227450487 0.0000000000000002220446 0.0000000000000002220446 0.0000000000000002220446 0.0000000000000002220446 0.0000000000000002220446

str(pred)
 Named num [1:20] 1 1 1 1 1 ...
 - attr(*, "names")= chr [1:20] "1" "2" "3" "4" ...

this is the dataset (Str(Banks):
'data.frame':   20 obs. of  5 variables:
 $ Obs                : int  1 2 3 4 5 6 7 8 9 10 ...
 $ Financial.Condition: int  1 1 1 1 1 1 1 1 1 1 ...
 $ TotCap.Assets      : num  9.7 1 6.9 5.8 4.3 9.1 11.9 8.1 9.3 1.1 ...
 $ TotExp.Assets      : num  0.12 0.11 0.09 0.1 0.11 0.13 0.1 0.13 0.16 0.16 ...
 $ TotLns.Lses.Assets : num  0.65 0.62 1.02 0.67 0.69 0.74 0.79 0.63 0.72 0.57 ...

A: Some example data:
Banks = data.frame(Obs = 1:100,Financial.Condition=rbinom(100,1,0.5),
TotCap.Assets = runif(100),
TotExp.Assets = runif(100),TotLns.Lses.Assets = runif(100))

You can just provide the table for confusionMatrix , to get the other metrics:
library(caret)

Banks_Logit<- glm(Banks$Financial.Condition ~ .,data = Banks, family="binomial")
pred <-predict(Banks_Logit,Banks)
confusionMatrix(table(ifelse(pred >0.5, 1,0), Banks$Financial.Condition))

Confusion Matrix and Statistics

     0  1
  0 36 33
  1  8 23

               Accuracy : 0.59
                 95% CI : (0.4871, 0.6874)
    No Information Rate : 0.56
    P-Value [Acc > NIR] : 0.3084356

                  Kappa : 0.2158

 Mcnemar's Test P-Value : 0.0001781

            Sensitivity : 0.8182
            Specificity : 0.4107
         Pos Pred Value : 0.5217
         Neg Pred Value : 0.7419
             Prevalence : 0.4400
         Detection Rate : 0.3600
   Detection Prevalence : 0.6900
      Balanced Accuracy : 0.6144

       'Positive' Class : 0


text:
Q: Retrieve rows from a table which has multiple dependencies I'm using Oracle 11g DB and I need to retrieve row id 2 from Table A, as it has two rows on Table B where the Table D's status is true TRUE.
Row id 1 from Table A cannot be retrieve, as it has two rows but out-of those two rows one of the row's Table D's status is FALSE.
How to select above rows from a single sql select query?
Table A
Id  | FName      | LName
-----------------------------
1   | Jhone      | A
2   | Alice      | B
3   | Bob        | C

Table B
A.Id  | order_id
--------------
1     | 1
1     | 2
2     | 3
2     | 1

Table C
B.order_id  | order_type
--------------
1           | X
2           | Y
3           | Z

Table D
C.order_type  | order_status
--------------
X           | TRUE
Y           | FALSE
Z           | TRUE

A: This returns all a where there is no false d, which is what I think you want:
select a.*
from a
where not exists (select 1
                  from b join
                       c
                       on b.order_id = c.order_id join
                       d
                       on c.order_type = d.order_type
                  where b.id = a.id and
                        d.order_status = 'false'
                 );


text:
Q: StreamSaver.js - Error in downloading (Network failed) I using StreamSaver and NodeJS together for save 10,000,000 Records into a file with .Json format. After run app and downloaded about many records(200,000 or 300,000 or ....), downloading canceled and abort file.json and show error "Network failed" on downloader in browser.
Why show this error and canceled downloading?
Notice: I haven't any error in console and I downloaded about 500MB or more...So no problem in range/memory.
Server.js
var http = require('http');
var express = require('express');
var app = express();
var server = http.Server(app);
var io = require('socket.io')(server);

io.on('connection', function (socket) {
    console.log('Connection is ready!')
    socket.on('get_records', function (data) {
    var connection = new sql.Connection(config, function (err) {
        if (err) {
            console.log(err.message);
        }

        var request = new sql.Request(connection);
        request.stream = true;

        request.query("Select * from my_table");
        // ... error checks
        request.on('recordset', function (recordset) {
            // Emitted once for each recordset in a query
        });

        request.on('row', function (record) {
            // Emitted for each row in a recordset
            socket.emit('recieve_records', record); //send record by record to client
        });

        request.on('error', function (err) {
            console.log(err.message);
        });

        request.on('done', function (returnValue) {
            // Always emitted as the last one
        });
    });
});

client.js
var fileStream = streamSaver.createWriteStream('filename.json');
writer = fileStream.getWriter();
encoder = new TextEncoder();
var counter = 0;

socket.on('recieve_records', function (data) {
    var uint8array = encoder.encode(data + "\n"); // data='every things'
    writer.write(uint8array);
    counter++;
    if (counter > 100000) {
       console.log('100.000 messages downloaded');
       counter = 0;
    }
});


text:
Q: Do I need to test other unrelated classes when deploying a new class? I have updated a class in a sandbox and successfully tested it. However, when I try to deploy it to production I am getting errors of tests which are failing for other classes which this class has nothing to do with. The tests for those classes are failing, and I am then unable to deploy my class.
Is this normal ? Are all of my other classes required to have an 75% code coverage when I am deploying a new class ?
Thank you very much for your help.

A: As of Salesforce Deployment process documentation - ALL classes and triggers must compile successfully:

The deploy call completes successfully only if all of the following
  must be true:

*

*At least 75% of your Apex code must be covered by unit tests

*Every trigger must have some test coverage

*All classes and triggers must compile successfully

Read this: Understanding deploy
This means that the total code coverage of all classes must be at least 75%. Some classes can have code coverage lower than 75% (10% for example), the total amount is important here.

A: The application as a whole has to work & be somewhat stable. If some other class suddenly started to fail check if there's a relation between what you're doing and what this class is about. Maybe there's something indirect (via trigger for example)? Maybe somebody made a change on production that suddenly broke the functionality. A good example is a new validation rule or a new required / unique field.
Maybe your unit test relies on production data that changed in the meantime?
Check if the unit test of this "broken class" fails also when just run the test execution on production. If they fail you know something changed. if they pass - it's most likely something in your deployment that breaks them. Try to run it from Eclipse / Data Migration tool if possible, if not - just use web interface.
As mast0r said - you need total 75% or better across your whole codebase (classes and triggers). And of course no errors.

A: So "No" when you ask "Are all of my other classes required to have a 75% code coverage..." There is a difference between that and ALL of your classes having 75% coverage. This means in aggregate.
It is common for something to have changed resulting in a change to your code coverage so you do need to troubleshoot as suggested above and change as needed.


text:
Q: Django: How to load file not in MEDIA_ROOT correctly | FileField? In my Django project I have application in which I want to load files NOT in MEDIA_ROOT. I used storage attribute to change the place but it raise error.
I used next code but it raise error when I try to load the file. How can I fix this problem?
settings.py:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media_root')

models.py:
from django.core.files.storage import FileSystemStorage
from os import environ

PRODUCT_STORAGE = FileSystemStorage(location=environ.get('PRODUCT_STORAGE_PATH'))

def product_file_upload_path(instance, filename):
    if instance.category=="1":
        path = '/category_1/' + '/%s' % filename
        return path
    elif instance.category=="2":
        path = '/category_2/' + '%s' % filename
        return path
    else:
        path = '%s' % filename
        return path

class Product(models.Model):
    file = models.FileField(
        max_length=255,
        blank=True,
        null=True,
        validators=[validate_file_extension],
        storage=PRODUCT_STORAGE,
        upload_to=product_file_upload_path,

    )

ERROR:
The joined path (/category_1/test.pdf) is located outside of the base path component (/other_folder)

A: Removing the leading slash and use 'category_1/' and 'category_2/'.
You'll also want to remove slash from '/%s', otherwise you you'll end up with // in the path. You can use os.path.join() to prevent mistakes like this.
import os
path = os.path.join('category1', filename)


text:
Q: Sum of two dependent random variables with copula I'm trying to calculate sum of 2 random variables by using Copula Theory in R or Matlab. However, I have very limited knowledge about probability. Actually I read a lot of theoretical information about how to do it, but still I couldn't find any clear example in R or MATLAB. What I try to do is lets say I have
A = [10 10 11 11 12 12 12 12 13 13] B = [13 13 15 15 17 17 19 19 20 20]
Assuming that they have comonotonic dependence between them and I want to calculate C = A + B by using Frechet upper bound (M-Copula). Is it possible to do this calculation in R ? Can anybody help ?
Obviously C will be bounded in between 23 < c < 33, but what will be its CDF and relevant probabilities ?
Thank you.


text:
Q: Transparent Popover and black parent UIViewController I want to show transparent ViewController over the parent VC.
let sdVC = ShowDetailsViewController()
sdVC.delegate = self
sdVC.modalPresentationStyle = UIModalPresentationStyle.OverCurrentContext
self.presentViewController(sdVC, animated: true, completion: nil)

It works ok in almost all the cases except one. My parent VC is in the TabBar, and this combination of actions is broken:

*

*Tap on the button to show transparent VC. — works.

*Tap on any other tab at the TabBar. — works.

*Tap back to the tab with transparent VC — transparent VC is ok, but his parent VC is completely black.

*Close transparent VC. Parent VC is still black.

*Tap on any other tab at the TabBar and back — Parent VC is ok.

How do I avoid 3 and 4?

A: You need to use .overFullscreen not OverCurrentContext.
See my answer here: https://stackoverflow.com/a/45991501/325267


text:
Q: ResourceBundle (Java) I need the character like 'шел' in my .properties file.
It seems like ISO 8859-1 (Which seems to be the default .properties encoding) doesnt like these, and displays them as ?.
I want to support this characters, what to do?
EDIT: I made it work now, but everytime I use this it converts my file from UTF-8 to ANSI (So the file gets replaced with the same file but then in ANSI), really weird. Code: http://pastebin.com/r0h3CKXF
Any idea why this happens??

A: Unicode can be encoded with \uxxxx in property files.

A: The Oracle JDK contains a tool named native2ascii that converts property files to Latin-1. Write your .property file in UTF-8, and then call
/path/to/jdk/bin/native2ascii -encoding utf8 input.properties output.properties

You can also read UTF-8 encoded .property files. See How to use UTF-8 in resource properties with ResourceBundle for a detailed description.


text:
Q: Is "leaning" not a verb? Please see the following sentence:

Detaching itself from the main body of traffic, a lone auto-rickshaw drew up near Porus, the driver leaning out expectantly.

Looking at http://tfd.com/leaning I can see it only as a noun and an adjective but not a verb.
Is this not a verb in this sentence?

A: It's a verb, but a non-finite one, like detaching at the beginning of the sentence.


text:
Q: Azure Trace Logs working on Emulator but not working on the cloud I have a TraceManager class that basically calls the TraceEvent method from the System.Diagnostics.TraceSource class.
TraceSource source = new TraceSource("MyTraceSource");
void TraceInternal(TraceEventType eventType, string message)
{
    if (source != null)
    {
        try
        {
            source.TraceEvent(eventType, (int)eventType, message);
        }
        catch (SecurityException)
        {
            //Cannot access to file listener or cannot have
            //privileges to write in event log
            //do not propagete this :-(
        }
    }
}

public void TraceError(string message)
{
    if (String.IsNullOrEmpty(message))
        throw new ArgumentNullException("message", Messages.exception_InvalidTraceMessage);

    TraceInternal(TraceEventType.Error, message);
}

So, for tracing an error I call the TraceError method.
Well, this is the code I use in my WebRole OnStart method:
DiagnosticMonitorConfiguration dmc = DiagnosticMonitor.GetDefaultInitialConfiguration();
TimeSpan transferPeriod = TimeSpan.FromMinutes(1.0);

dmc.Logs.ScheduledTransferPeriod = transferPeriod;
dmc.Logs.ScheduledTransferLogLevelFilter = LogLevel.Verbose;

DiagnosticMonitor.Start("Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString", dmc);

This is my configuration in my web.config:
<system.diagnostics>
  <sources>
    <source name="MyTraceSource" switchName="sourceSwitch" switchType="System.Diagnostics.SourceSwitch">
      <listeners>
        <add type="Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="AzureDiagnostics">
          <filter type="" />
        </add>
      </listeners>
    </source>
  </sources>
  <switches>
    <add name="sourceSwitch" value="Verbose"/>
  </switches>
</system.diagnostics>

And these are my configuration settings for my WebRole:
<ConfigurationSettings>
  <Setting name="Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString" value="DefaultEndpointsProtocol=https;AccountName=ValidAcountName;AccountKey=ValidAcountKey" />
</ConfigurationSettings>

And finaly I have the Diagnostics Import in my ServiceDefinition:
<Imports>
  <Import moduleName="Diagnostics" />
</Imports>

When I run my application from Visual Studio under the Azure Emulators it works fine. Even I can change my ConfigurationSettings for saving my logs in the storage emulator or in my cloud storage. But when I deploy it to azure I can't see any Log.
Any ideas?

A: Could you check the properties of your Azure project if the following setting is active? If it is, try deactivating it:

Reference: http://michaelcollier.wordpress.com/2012/04/02/where-is-my-windows-azure-diagnostics-data/

A: Have you confirmed that you're defining the TRACE constant when you're building the application?  If you have a custom build script, is it possible this constant isn't being defined?
That would prevent the Trace statements from being logged.


text:
Q: Use gitlab variable in Terraform module I work for an enterprise with a number of different gitlab repositories all deploying applications using Terraform. The majority of these code bases uses a standardised module that defines certain tags for resources in our cloud provider. I am wanting to add the Gitlab project id as one of the default tags and while I know how to use pre-defined vars in Terraform by defining an env var starting with TF_VAR, I don't want to have to modify all code bases in order to set it.
What I want to do is set the project id (env var) in the module so that any codebase that consumes this module will automatically have this environment variable set for use in the gitlab pipeline.
Does anyone have any ideas how I might do this?
Thanks,
Adam


text:
Q: What is the difference between packages GCL and CLISP? In the Ubuntu repositories there are two implementations of Lisp: GCL and CLISP. Is there a fundamental difference between them? Which one is closer to the industry standard?

A: Common Lisp is actually defined in an ANSI standard. There are lots of implementations for it, both commercial and FOSS. The implementations generally comply with the standard, and provide some extensions of their own for things that are not defined in the standard (such as threads, FFI and unicode).
You should see http://www.cliki.net/Common%20Lisp%20implementation for a comparison of implementations. Which one you should use depends on your needs and preferences. For starting out you can just pick one. The language itself is going to be the same regardless, and as long as you don't use any implementation specific extensions, you can easily switch to another one if needed.
I personally prefer SBCL on Linux. It has good performance and includes extensions for threads and all. The main weakness is that programs will be very large (both disk space and memory usage). That doesn't matter much if you're building a server side app, or something so big that it outweighs the implementation anyway, but for smaller client-side tools you might want to look into CLISP. I haven't used GCL, so I can't say much about it.

A: Just to clarify: Lisp names the family of programming languages which includes (bot not limited to):

*

*ANSI Common Lisp. Packages in Ubuntu: gcl, abcl, clisp, ecl and sbcl provide different (FOSS) implementations of the standard (with different level of completeness).

*Scheme (also defined by the standard, but there exist a number of versions of the standard: R4RS, R5RS, R6RS and R7RS). Packages in Ubuntu: chicken (mostly R5RS and R6RS), gambit (R4RS), racket (dialect of Scheme and R6RS), mit-scheme (R4RS)

*Clojure is a Lisp-dialect for JVM. Ubuntu might provide the package but it is better to install it through Leiningen

*LFE, newLISP, Hy, and etc. are other (perhaps, less known) dialects of Lisp

If you would like to start with Common Lisp, probably the best choice would be to use SBCL implementation with Emacs+SLIME as an IDE.
GCL (like ECL) compiles to C. ECL is mostly used to embed Common Lisp into C-program. GCL was used (and for some project is still used) to develop algebra systems like Maxima and Axiom, but recently it seems to be get replaced by SBCL (at least in case of Maxima).
CLISP compiles into VM-code which makes it portable but slow. The project hasn't been updated for a while, and there exists a bit of a problem with CFFI in it, making it incompatible with some modern libraries.
For completeness: ABCL is Common Lisp implementation for JVM, extremely narrow niche implementation (IMHO mostly due to deficiencies of JVM).


text:
Q: Git restore files locally deleted not committed yet I'm new to Git and accidentally deleted all my physical local files on my desktop and library. Due to initiating git from wrong directory.  I have not committed it yet. How do I restore the files back ?
The current git status is :
git status

On branch master
Changes to be committed:
  (use "git reset HEAD ..." to unstage)
modified:   .DS_Store
new file:   .gitconfig
new file:   Desktop/.DS_Store

Now :
git status
On branch master
Changes to be committed:
  (use "git reset HEAD ..." to unstage)
modified:   .DS_Store
new file:   .gitconfig
new file:   Desktop/.DS_Store

How do you get the local files back.
The total files which have got deleted physically is more than 1.5gb. I don't want to commit them or push them to remote if they are in staging area. But I need to restore the files physically on the local desktop.

A: If the files you deleted had not been tracked by Git you will not be able to use Git to get them back.
This article talks about tracking files.
In the future, it's a good idea to commit early since even if you commit too frequently you can combine (squash) commits together before pushing them to a public repository.
EDIT: Per your comments it seems that after some Git operations you lost files that were already tracked by Git (meaning that they were added to a previous commit).
It also looks like the operation you performed put you in "detached HEAD" mode which means that your HEAD (where you are in the Git tree) is not pointed to by a branch.
So, probably it would be best to simply get back to the branch you were previously on. Let's say you were on the master branch. Run this command:
git checkout master

Then do a git status and make sure everything looks as it did prior to the faulty Git operations you performed.


text:
Q: Weird effect with JFrame and Graphics import javax.swing.JFrame;
import java.awt.Color;
import java.awt.Graphics;

public class Game extends JFrame {

    public Game() {
    setTitle("Worm Attack");
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(300, 300);

    }

    public void paint(Graphics g) {
        g.drawString("Welcome to Worm Attck", 75, 75);
    }
}

I have this as a code to open a JFrame and say "Welcome to Worm attack." When it opens the window, I see through, and I can see my desktop.

A: This is because the paint process was interrupted.
Try adding the super.paint call at the beginning of the paint method:
public void paint(Graphics g) {
    super.paint(g);
    g.drawString("Welcome to Worm Attck", 75, 75);
}

A: You have messed up the brackets somehow but that might just be the paste you made here (not sure so won't edit the question).
About the actual problem, you shouldn't overwrite the paint method, rather override the paintComponents() method :).
Read this on how to do painting in java : http://java.sun.com/docs/books/tutorial/uiswing/painting/index.html :)

A: Another thing, you should use setVisible after your JFrame is complete.
setTitle("Worm Attack");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);
setVisible(true);


text:
Q: Eigenvalue problem: show that it only has negative eigenvalues Consider the eigenvalue problem
$$u''-\frac{3}{4x^2}u=\lambda u, \ \ \ u(1)=0,\ u(2)=0$$
I want to show that this eigenvalue problem only has negative eigenvalues. I multiplied the equation by $u$:
$$(u')'u-\frac{3}{4x^2}u^2=\lambda u^2$$
Integrating the LHS (by parts):
$\int_1^2(u')'u-\frac{3}{4x^2}u^2dx=[u'u]_1^2-\int_1^2(u')^2dx-\frac{3}{4}\int_1^2\frac{u^2}{x^2}dx$
Now, $u(1)=u(2)=0$, so the first term equals $0$, and $-\int_1^2(u')^2dx \leq 0$ and also $\frac{3}{4}\int_1^2\frac{u^2}{x^2}dx \leq 0$ because the integrands are $\ge 0$ (because of the $(.)^2$) and we integrate from $1$ to $2$.
So, the LHS is $\leq 0$.
And the RHS: $\lambda\int_1^2u^2dx \geq 0$
Therefore $\lambda \leq 0$.
Is that correct so far?
How, do I show that $\lambda \neq 0$? I thought about solving the initial value problem
$$u''-\frac{3}{4x^2}u=0, \ \ \ u(1)=0,\ u(2)=0$$
The solution of the IVP is $u=0$ if I didnt make any mistakes. Is that any 'contradiction' which means that $\lambda$ can't be equal to $0$?


text:
Q: Lottery program that lets a user choose how many times they wish to play at once I'm trying to make a lottery program that can output results after a user inputs their numbers. But I want the option to allow the user to also be able to pick "how many weeks they play for", that being, how many times the program outputs results that are randomized. Basically use the numbers they inputted to play multiple games of lottery with the same numbers x amount of times they wish. I want to know how to make my function repeat based on how many times they wish to play.
Here's my incomplete  code.
 import random

NUMBER_OF_PICKS = 3
MINIMUM_SELECTION = 1
MAXIMUM_SELECTION = 36
MONEY_WON = 10000
OFFSETT = 4

USER = input("Please enter your name:")
print("Hi " + USER + " good luck ")
WEEKS_PLAYED = input("How many weeks do you want to play: ")

def verify(playerNumbers, winningNumbers):
    if playerNumbers == winningNumbers:
        print("Congratulations! You Win ${}!".format(MONEY_WON))
        print("Your numbers: ", playerNumbers, )
        print("The winning lottery numbers were: ", winningNumbers)

    else:

        print("Sorry, you lose...")
        print("Your numbers: ", playerNumbers)
        print("The winning lottery numbers were: ", winningNumbers)

# 'get_user_nums', gets user numbers and puts into a sorted list for x in WEEKS_PLAYED:
 def get_user_nums():
    user_nums = []
    while len(user_nums) < NUMBER_OF_PICKS:
        nums = input("Pick a number {} through {}: ".format(MINIMUM_SELECTION, MAXIMUM_SELECTION))
        try:
            nums = int(nums)
        except:
            print("Sorry your input must be an integer!")
            continue
        if MINIMUM_SELECTION <= nums <= MAXIMUM_SELECTION:
            if nums not in user_nums:
                user_nums.append(nums)
            else:
                print("Sorry, you have already inputted that number")
        else:
            print("Sorry, Your number was not in range")

    return sorted(user_nums)

# 'get_winning_nums', creates a sorted list with random nums ranging from 0-9 with a range of 3 values
def get_winning_nums():
    return sorted(random.sample(range(MINIMUM_SELECTION, MAXIMUM_SELECTION), NUMBER_OF_PICKS))

# 'menu', creates the main menu to choose game or exit program

def play_pick_n():
    user_nums = get_user_nums()
    winning_nums = get_winning_nums()
    verify(user_nums, winning_nums)

# 'main', calls the other functions
def main():
    # lottery_menu()
    while True:
        choice = input("\nPlay?: Yes or No: ")
        if choice == 'Yes':
            string = "\n[Play Pick {}]".format(NUMBER_OF_PICKS) + "selected!"
            dotted = '\n' + len(string) * "-"

            print(dotted, string, dotted)

            play_pick_n()
            break

        elif choice == 'No':
            print("Thanks for playing!\n")
            break

        print("Sorry, that is not a valid input. \nPlease enter either Yes or No")

if __name__ == '__main__':
    main()

Thanks for any help.

A: if you ant to use the same numbers for all weeks, use:
user_nums = get_user_nums()

for week in range(0, WEEKS_PLAYED):
    winning_nums = get_winning_nums()
    verify(user_nums, winning_nums)

You might want to move the question for the number of weeks inside your play_pick_n function, so the player can decide per bunch of numbers who long they should run.


text:
Q: Get Python Array Key Text I'm using Python 3.8.5 on Ubuntu & can't figure out how to get the key for from this data:
{'2020-10-31': {'intangibleAssets': 831000000, 'capitalSurplus': 5311000000, 'totalLiab': 4754000000, 'totalStockholderEquity': 4873000000, 'otherCurrentLiab': 496000000, 'totalAssets': 9627000000, 'commonStock': 3000000, 'otherCurrentAssets': 127000000, 'retainedEarnings': 81000000, 'otherLiab': 876000000, 'goodWill': 3602000000, 'treasuryStock': -522000000, 'otherAssets': 601000000, 'cash': 1441000000, 'totalCurrentLiabilities': 1467000000, 'deferredLongTermAssetCharges': 380000000, 'otherStockholderEquity': -522000000, 'propertyPlantEquipment': 1020000000, 'totalCurrentAssets': 3415000000, 'longTermInvestments': 158000000, 'netTangibleAssets': 440000000, 'netReceivables': 1127000000, 'longTermDebt': 2284000000, 'inventory': 720000000, 'accountsPayable': 354000000}}
The above data is the output from:
print(data_input)

I can print the key to standard output like this:
my_array = data_input[0]

print(*list(my_array))

The above code gives the out put that I need:
2020-10-31

But I need that in a variable. So when I try to put that into a variable it doesn't work:
my_array = data_input[0]

my_key = print(*list(my_array))

It simply prints it to the standard output.
What I want to do is have this:
print(my_key)

With the output being:
2020-10-31

I can't figure this out. Any ideas?

A: You can get a list containing the keys of a dictionary  by calling its keys() method:
dic = {"key1": "value1, "key2: "value2"}
print(dic.keys())
print(dic.keys()[0])
my_key = dic.keys()[0]
print(my_key)


text:
Q: How to open new activities in the same fragment hosted in TabLayout - Xamarin.Android I am trying to develop an application which has 3 tabs and one of the tab has a listview. I can handle the onclick events for listview items. What I need to know is how to open new activity/fragment in the same tab(without losing Tab bar)

A: You can use Android.Support.V4.App.Fragment and   SupportFragmentManager to achieve this. First add by Nuget Support.V4 package. In your Activity layout add
RelativeLayout, this layout will be keep your fragments. Add new fragments and by using fragment manager you can changing it. Using function ChangeFragment(), You will be only change view in RealitiveLayout. Try follow this sample.
main.axml
 <!-- The Main Content View -->
            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:id="@+id/SetFragment" />

main_activity.cs
    protected void ChangeFragment(int pos)
    {

        Fragment fragment = null;
        switch (pos)
        {
            case 0:
               fragment = new NotificationFragment();
               break;

            case 1:
                fragment = new SampleFragment();
                break;
        }

            SupportFragmentManager.BeginTransaction()
                .Replace(Resource.Id.SetFragment, fragment, LoadFragment)
                .Commit();
      }

sample_fragment.cs
public class SampleFragment : Fragment
{
    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View = inflater.Inflate(Resource.Layout.sampleView, container, false);

        return View;
    }
}


text:
Q: How do I restrict my AIR distribution? Is there any way through which i can restrict my AIR app to be further distribution?
Say I have make one AIR application and I give this app to my friend. Is there any way so that he can not re distribute this app to any new person?

A: There's nothing built in that will help you solve this, but two ideas come to mind.
One choice is to require a serial number on first startup. Validate the serial number against a server using HTTPS and then store it, encrypted, in the local store. You could then validate that machine's use of the serial either on the server, or by using something unique to the machine to encrypt the local store.
You could also possibly use client certificates, which would need to be installed on the user machine. The application could then validate against the certificate on startup.

A: This is a good question. A possible solution to this is certification. However i have a doubt here. Do you want your friend not to distribute this application + no secondary installation is possible with it.
Secondary installation means if your friends wants his system to format and reinstall the application. Do you want to support this?
If no then solution is easy.

A: If you restrict your AIR application from distribution, wouldn't that make it impossible for you to give the application to your friend? The only language-agnostic way I can see this be done with any application is that you have your friend come over and have a look on your computer.
If you are keen on making the AIR application "yours" you could try to sign it digitally but getting a certificate costs loads of money.


text:
Q: Why is this SQL query ordering incorrectly? I'm running the following query to "reorder" an updated table alphabetically. There's a column called nOrder that's supposed to be in sequential order. I'm updating that column as follows:
(edited: forgot to include AND @zone = zone in my question, but the same problem is occurring)
UPDATE Zones
SET nOrder = 0 WHERE stateKey = @key

DECLARE @zone INT
SET @zone = 1
DECLARE @i INT
SET @i = 1

WHILE @zone < 4
    BEGIN
        WHILE EXISTS (SELECT TOP 1 cDisplay FROM Zones WHERE stateKey = @key AND zone = @zone AND nOrder = 0)
            BEGIN
                UPDATE Zones
                SET nOrder = @i
                WHERE cDisplay = (SELECT TOP 1 cDisplay FROM Zones WHERE stateKey = @key AND zone = @zone AND nOrder = 0 ORDER BY cDisplay)
                SET @i += 1
            END
            SET @zone += 1
            set @i = 1
    END

The table then becomes:
FK zone                cDisplay                nOrder
                          .
                          .
                          .
                          .
10  3    MD: CAROLINE, DORCHESTER, KENT          40
10  3    MD: QUEEN ANNE'S                        41
10  3    MD: SOMERSET, TALBOT, WILCOMICO         42
10  3    ME: PORTLAND                            43
10  3    ME: YORK                                44
                          .
                          .
                          .
                          .
10  3    TX: COUNTIES NORTH OF HOUSTON           99
10  3    TX: DALLAS-FORT WORTH OUTER SUBURBAN   100
10  3    TX: EL PASO                            101
10  3    TX: MATAGORDA AND VICTORIA COUNTIES    102
10  3    TX: NORTHEAST COUNTIES                 103
10  3    TX: SAN ANTONIO OUTER SUBURBAN AREAS   104
10  3    TX: SOUTHERN TEXAS                      43   --???
10  3    TX: TYLER                              105
                          .
                          .
                          .
                          .

"FK" is actually "stateKey", but that doesn't fit.
why would this record be out of order? It doesn't make much sense to me that this would happen.
Does anyone have any ideas?

A: How about a much easier way to do this?  I think you want:
WITH toupdate as (
      select z.*, row_number() over (partition by zone order by cDisplay) as seqnum
      from zones z
      where stateKey = @key AND nOrder = 0
     )
UPDATE toupdate
    set nOrder = seqnum;

The variable @zone is set but not used in your code (at least, it doesn't affect the update).  I'm not sure what it should be doing -- but I suspect that is related to the problem with your code.  In any case, using a CTE and ranking function is a better way to solve this problem.

A: You MUST use an ORDER BY clause any time you use "SELECT TOP..." otherwise you get an undefined ordering that can be anything the SQL Optimizer wants.


text:
Q: typescript extends class along with implement interface I am trying to extend a third party library class mongooseJs so that I can have some custom functionality in there. I have done this in the past with Javascript, like this
const mongoose = require("mongoose");
class CustomMongoose extends mongoose.Mongoose {
    myCustomMethod() {
        console.log('this is my custom method');
    }
}

const a = new CustomMongoose();
a.model("test"); //This method does get called on parent correctly (code wouldn't work until connection is setup but you get the point)

However when I try to do similar thing in typescript, as below, it gives me an error
Type 'CustomMongoose' is missing the following properties from type 'CustomMongooseBase': pluralize, connect, createConnection, disconnect, and 39 more.

for this code
const mongoose = require("mongoose");
import { Schema, Model, Document, Mongoose } from "mongoose";

interface CustomMongooseBase extends Mongoose {
  myCustomMethod(): void;
}

class CustomMongoose extends mongoose.Mongoose implements CustomMongooseBase {
    myCustomMethod(): void {
        console.log('this is my custom method');
    }
}

//this is what I would expect to work, if this compiles fine
// const a = new CustomMongoose();
// a.myCustomMethods(); // should work
// a.model("modelName") //should also work, though this is from the base

What I am trying to do is that providing my own interface CustomMongooseBase, which in turn extends the Mongoose interface. I want the caller of my new class CustomMongoose to have my new functionality and everything else as pass through. So in the concrete implementation, I have extended mongoose.Mongoose which has implementation of all the methods Mongoose interface requires, and my custom class has implementation of new method myCustomMethod that my own interface requires, so this should be working, but it's not.
What I am doing wrong here? (New to typescript so trying to get my head around)
==== Slightly different variation with different error ====
import { Mongoose } from "mongoose";

export interface CustomMongooseBase extends Mongoose //extending at the interface level so that consumers have the full signature of mine as well as parent interface
{
  myCustomMethod(): void;
}

class CustomMongoose extends Mongoose implements CustomMongooseBase {
  myCustomMethod(): void {
    console.log("this is my custom method");
  }
}

//this is what I would expect to work, if this compiles fine
// const a = new CustomMongoose();
// a.myCustomMethods(); // should work
// a.model("modelName") //should also work, though this is from the base

and here is a different error now
Non-abstract class 'CustomMongoose' does not implement inherited abstract member 'ConnectionBase' from class 'typeof import("mongoose")'.ts(2515)

These are my package.json dependencies
"dependencies": {
    "@types/mongoose": "^5.7.36",
    "@types/node": "^14.6.4",
    "mongoose": "^5.10.3"
  }

A: I think the problem is that

*

*You have both const mongoose = require("mongoose"); and import { Schema, Model, Document, Mongoose } from "mongoose";. That's really, really odd. Normally you use either CommonJS (require) or ESM (import). You don't mix them.
And,

*You're using Mongoose on interface CustomMongooseBase extends Mongoose but you're using mongoose.Mongoose on class CustomMongoose extends mongoose.Mongoose implements CustomMongooseBase. I suspect mongoose.Mongoose isn't resolving to the same type.
I'd fix it by using just one form of module import, and being consistent about naming:
import { Schema, Model, Document, Mongoose } from "mongoose";

interface CustomMongooseBase extends Mongoose {
  myCustomMethod(): void;
}

class CustomMongoose extends Mongoose implements CustomMongooseBase {
    myCustomMethod(): void {
        console.log('this is my custom method');
    }
}

That said, there's no reason that CustomMongooseBase needs to extend Mongoose, you could just remove that bit:
interface CustomMongooseBase {
  myCustomMethod(): void;
}

class CustomMongoose extends Mongoose implements CustomMongooseBase {
    myCustomMethod(): void {
        console.log('this is my custom method');
    }
}


text:
Q: Ordering ArrayList of points to follow closest point LibGDX Java I have an ArrayList of Vector2 (Vector2 is an object that contains an x and y coordinate) that contains a bunch of vertices that make a shape when drawn. However, the way they were put into the ArrayList are out of order. For example, the starting Vector2 point is index 0 but the closest next point is of index 4. My goal is to have another ArrayList of Vector2 that orders the Vector2's in a way so that the starting point is index 0, the next closest point is index 1, next is index 2, etc. Here is an image of what is happening.
The image shows what is happening but the green arrows show what I want to happen. The green point is the starting point.

So what I need is once the new ArrayList is created and ordered, it should look like this:

So here is the code in which I thought would do it:
public Array<Vector2> orderedVertices;
private void cleanVertices(Array<Vector2> originalVertices){

    //This will be the Array containing ordered vertices
    orderedVertices = new Array<Vector2>();

    //Copy vertices of unsorted Array in a new Array
    Array<Vector2> verticesOfImage = originalVertices;

    //Add a random vertice to begin with (starting point)
    orderedVertices.add(verticesOfImage.get(1));

    //For breaking loop
    int originalArraySize = originalVertices.size;

    for(int i = 0; i < orderedVertices.size; i++){
        //Index to be compared, meaning to find closest vertice around this vertice
        int indexOfCompare = i;
        //Get a distance for reference                                                     //Random point to check
        double currentDistance = MathFactory.distance(orderedVertices.get(indexOfCompare), verticesOfImage.get(0));

        //If we found a closest vertice, add to ordered pair and remove from original
        // So we don't go backwards
        if(getClosest(verticesOfImage, indexOfCompare, currentDistance) != -1){
            orderedVertices.add(verticesOfImage.removeIndex(getClosest(verticesOfImage, indexOfCompare, currentDistance)));
        }
        //If not, then the original 'currentDistance' check was the closest vertice
        else
            orderedVertices.add(verticesOfImage.removeIndex(0));

        //Stop checks, ordered pair fully populated
        if(orderedVertices.size == originalArraySize)
            break;

    }

}

public int getClosest(Array<Vector2> vertices, int checkedIndex, double currentDistance){
    //This is used to find the closest vertice, defaulted to -1 for condition statements
    int correctIndex = -1;

    for(int k = 0; k < vertices.size; k++){
        //Make sure to not check same Vector2
        if(vertices.get(k).x == orderedVertices.get(checkedIndex).x && vertices.get(k).y == orderedVertices.get(checkedIndex).y){
            continue;
        }
        if(MathFactory.distance(orderedVertices.get(checkedIndex), vertices.get(k)) < currentDistance){
            correctIndex = k;
            currentDistance = MathFactory.distance(orderedVertices.get(checkedIndex), vertices.get(k));

        }

    }
    return correctIndex;
}

This code comes very close to working, here is an image explaining what is going wrong.

I understand the one that isn't working doesn't look as smooth, but the only real problem is the fact that the lines freak out at the end and go through the body. I can't seem to figure out why this is happening or how to fix it. Any help at all with this is hugely appreciated! Thank you!


text:
Q: PHP exec() not storing Process ID I have a PHP program which is starting a process in the background via exec() (the output of the process is being sent to /dev/null). I then use exec("echo $!", $processes[0]) because I want to store the ID of the process so I can terminate it later. However, the result of $processes[0] is an empty array.
Why is the process ID not being stored? Note that the process ID is outputted correctly if I execute my background process and then run echo $! from the terminal. An additional note is that I am using a Raspberry Pi which is Linux-based.

A: In order to record the process ID, you have to set it into a variable.  For example, to start another PHP script in the background:
$pid = exec("php mysbackgroundscript.php >/dev/null 2>&1 & echo $!");

The $pid variable should then contain the PID.


text:
Q: How to add products to a company? In my company form, I would like to be able to add products directly. Basically, a company can have many products.
class Company < ActiveRecord::Base
  has_many :company_products
  has_many :products, :through => :company_products

  accepts_nested_attributes_for :products, :reject_if => lambda { |a| a[:name].blank? }, :allow_destroy => true
end

My Form:
<%= form_for(@company) do |f| %>

      <%= f.label :company_name %>
      <%= f.text_field :company_name %>

      <%= f.collection_select :product_ids, Product.all, :id, :name, { :prompt => 'Select a product' } %>

      <%= f.collection_select :product_ids, Product.all, :id, :name, { :prompt => 'Select a product' } %>

      <%= f.collection_select :product_ids, Product.all, :id, :name, { :prompt => 'Select a product' } %>

 ....

Above, does not exactly work. Since it only adds the product that was selected in the last f.collection_select.
This is what I am trying to achieve. In console, I do:
company.update_attributes({"product_ids"=>["1", "2", "3"]})

Which would assign products with id: 1, 2 and 3 to the specified company.
What is the proper way to do this in Rails 3?
EDIT
In my form, it works with:
<%= f.collection_select :product_ids, Product.all, :id, :name, { :prompt => 'Select a product'},{ :multiple => true } %>

Is there a way to do this with select dropdown boxes instead?

A: Use nested forms for products:
<%= fields_for @company.products do |product_fields| %>
  <%= product_fields.collection_select :product_id, Product.all, :id, :name, { :prompt => 'Select a product' } %>
<% end %>


text:
Q: Is there a way for a Python program to "cd" to a folder that has a space in it? I am creating a code editor, and I am trying to create a run feature. Right now I see that the problems come when I encounter a folder with a space in its name. It works on the command line, but not with os.system().
def run(event):
    if open_status_name != False:
        directory_split = open_status_name.split("/")
        for directory in directory_split:
            if directory_split.index(directory) > 2:
                true_directory = directory.replace(" ", "\s")
                print(true_directory)
                data = os.system("cd " + directory.replace(" ", "\s"))
                print(data)

I tried to replace the space with the regex character "\s" but that also didn't work.

A: os.system runs the command in a shell. You'd have to add quotes to get the value though: os.system(f'cd "{directory}"'). But the cd would only be valid for that subshell for the brief time it exists - it would not change the directory of your python program. Use os.chdir(directory) instead.
Note - os.chdir can be risky as any relative paths you have in your code suddenly become invalid once you've done that. It may be better to manage your editor's "current path" on your own.


text:
Q: Filling missing data with different methods I have a couple of a set of data with timestamp, value and quality flag. The value and quality flag are missing for some of the timestamps, and needs to be filled with a dependence on the surrounding data. I.e.,

*

*If the quality flags on the valid data bracketing the NaN data are different, then set the value and quality flag to the same as the bracketing row with the highest quality flag. In the example below, the first set of NaNs would be replaced with qf=3 and value=3.

*If the quality flags are the same, then interpolate the value between the two valid values on either side. In the example, the second set of NaNs would be replaced by qf = 1 and v = 6 and 9.

Code:
import datetime
import pandas as pd

start = datetime.strptime("2004-01-01 00:00","%Y-%m-%d %H:%M")
end = datetime.strptime("2004-01-01 03:00","%Y-%m-%d %H:%M")
df = pd.DataFrame(\
    data = {'v' : [1,2,'NaN','NaN','NaN',3,2,1,5,3,'NaN','NaN',12,43,23,12,32,12,12],\
            'qf': [1,1,'NaN','NaN','NaN',3,1,5,1,1,'NaN','NaN',1,3,4,2,1,1,1]},\
    index = pd.date_range(start, end,freq="10min"))

I have tried to solve this by finding the NA rows and looping through them, to fix the first criteron, then using interpolate to solve the second. However, this is really slow as I am working with a large set.

A: One approach would just be to do all the possible fills and then choose among them as appropriate.  After doing df = df.astype(float) if necessary (your example uses the string "NaN"), something like this should work:
is_null = df.qf.isnull()
fill_down = df.ffill()
fill_up = df.bfill()

df.loc[is_null & (fill_down.qf > fill_up.qf)] = fill_down
df.loc[is_null & (fill_down.qf < fill_up.qf)] = fill_up
df = df.interpolate()

It does more work than is necessary, but it's easy to see what it's doing, and the work that it does do is vectorized and so happens pretty quickly.  On a version of your dataset expanded to be ~10M rows (with the same density of nulls), it takes ~6s on my old notebook.  Depending on your requirements that might suffice.


text:
Q: Как установить Lua-модуль в nginx 1.15.*? установил из коробки nginx-extras, но проблема в том, что с ним сразу идет nginx 1.10., мне бы очень сильно хотелось установить nginx 1.15. и Lua-модуль к нему же. Как это возможно? И возможно ли вообще?
ОС: Linux, Debian 9 Stretch

A: Разумеется, это возможно, однако, учтите, что по состоянию на момент ответа модуль ещё не был протестирован на совместимость с nginx 1.15, поэтому при сборке могут потребоваться какие-либо изменения в его исходный код.
Вам потребуются исходники nginx, окружение для сборки (apt-get install build-essential, а также зависимости, перечисленные в документации к серверу и модулю) и собственно модуль.
Процесс сборки модуля описан в его документации.


text:
Q: How to handle the master server going down in a master-slave log server architecture? I am building a Log service.
I have a master and some slave servers. The slave servers directly receive logs from the client. Each interval time, slaves will push the logs to the master server to store. But the problem is when the master goes down, then after some time, it wakes up, but I have already lost the logs in the interval that the master goes down.
Has anyone built a service like this? Please share your idea.

A: The common way of making a system resilient to outage is to implement a queue.  Slaves will write logs to a queue and the master server reads from the queue.  If the master goes down, the queues persist until the master recovers.
With this approach you may not need the slaves.  Each application can write directly to the logging queue with an async fire-and-forget request.


text:
Q: How to retrieve data from a post request using flask in python I am working on a rest api using flask. Currently the code for the client is as follows:
new_data = {'msg': message,
        'rec':rec_id,
        'snd':my_id}
        requests.post("http://localhost:33/api/resources/messages/all", json = new_data)

I did print out new_data and it does print fine it does print out fine

{'msg': 'This is a message', 'rec': 1, 'snd': 0}

and the code in the rest api is:
@app.route('/api/resources/messages/all', methods=['GET', 'POST'])
def api_messages():
    if request.method == "GET":
        return jsonify(messages)
    if request.method == "POST":
        sentmsg = request.json
        print (sentmsg)

changing

sentmsg = request.json

to

sentmsg = request.get_json()

did not change anything as it still results in the same error. Specifying the content type also did not result in any changes to the result.
However this code results in the error when attempting to post it.

TypeError: Object of type type is not JSON serializable

How can I change this code in order to make it so the json is passed to the rest api and can be printed out in json form.

A: The issue did not originate from the code shown in the initial post. The error originates at the start of the code where I declared two of the variables used here:
my_id = int
rec_id = int

Since these 2 variables did not have a value it was causing issues when it was called. As such it resulted in the error message "TypeError: Object of type type is not JSON serializable" (This error message itself gives a good indicator that one or more of the variables used were likely blank and held no value, thus making it unable to specify the data type in the message).
As such giving these variables an actual value caused the program to work fine. A second error that only become obvious after was that request.get_json needed to have brackets after get_json, making it request.get_json().


text:
Q: sending data and receiving data from mysql database in the same webpage I am trying to make a discussion board as my own project, right now I have a page where a user enter his comment, and another page where it confirms that his comment was posted, and then a third page where you could see all the comments. All this is done using php and mysql as the database that holds all the users information such as the users, name, comments, date ,etc.
What I am trying to do is instead of having three pages, I just want one page where the user enters his comment and he can see the comments right away in the same page. Can this be done, are there any good tutorials i can look at online?

A: You can achieve that using Ajax.


text:
Q: string-join() function throws invalid expression XPathError
message: "Invalid expression.
(string-join(/form/Data/MProcess/Process/Id/string(), ','))
I thought the problem was Process Id was not returning string so I tried string() and text() but they did not work. I can't find the solution.
Here is an example process id: aee865d1-7253-489c-8d53-2a0d580639d0

A: string-join() is an XPath 2.0 function, and many early XPath processors were never upgraded to 2.0. Check what XPath processor you are using and what language level it supports, and upgrade if you can.


text:
Q: Django ModelForm - ManyToMany nested selection I'm building a Django application and I'm facing an issue I don't know how to solve... I'll try to explain it as clear as I can.
I've got an app called "Impostazioni" which has a model called "AnniScolastici":
class AnniScolastici(models.Model):
    nome = models.CharField(max_length=50)

    class Meta:
        verbose_name = "Anno scolastico"
        verbose_name_plural = "Anni scolastici"

    def __str__(self):
        return f"{self.nome}"

I also have another app called "Attivita" which has a model called "Laboratori":
class Laboratori(models.Model):
    nome = models.CharField(max_length=25)
    durata = models.IntegerField(default=0)
    anniscolastici = models.ManyToManyField(AnniScolastici)
    note = models.TextField(null=True, blank=True)

    class Meta:
        verbose_name = "Laboratorio"
        verbose_name_plural = "Laboratori"

    def __str__(self):
        return f"{self.nome}"

I've coded up another model called "RichiesteLaboratori" which is related to different models in my Django app (and on the two above, of course):
class RichiesteLaboratori(models.Model):
    date_added = models.DateTimeField(auto_now_add=True)
    date_valid = models.DateTimeField(null=True, blank=True)
    provincia = models.ForeignKey("impostazioni.Province", related_name="richiesta_provincia", null=True, on_delete=models.CASCADE)
    istituto = models.ForeignKey("contatti.Istituto", related_name="richiesta_istituto", null=True, on_delete=models.CASCADE)
    plesso = models.ForeignKey("contatti.Plesso", related_name="richiesta_plesso", null=True, on_delete=models.CASCADE)
    classe = models.CharField(max_length=25)
    numero_studenti = models.PositiveIntegerField()
    nome_referente = models.CharField(max_length=50)
    cognome_referente = models.CharField(max_length=50)
    email = models.EmailField()
    telefono = models.CharField(max_length=20)
    termini_servizio = models.BooleanField()
    classi_attivita = models.ManyToManyField(AnniScolastici, related_name="richiesta_anniScolastici")
    laboratori = models.ManyToManyField(Laboratori)
    note = models.TextField(null=True, blank=True)
    approvato = models.BooleanField(default=False)

    class Meta:
        verbose_name = "Richiesta - Laboratorio"
        verbose_name_plural = "Richieste - Laboratorio"

    def __str__(self):
        return f"{self.pk}"

I'm populating entries of this model through a ModelForm and a view. Here is the form:
class RichiesteLaboratoriModelForm(forms.ModelForm):
    classi_attivita = forms.ModelMultipleChoiceField(
        queryset=AnniScolastici.objects.all(),
        widget=forms.CheckboxSelectMultiple,
        required=True
    )

    laboratori = forms.ModelMultipleChoiceField(
        queryset=Laboratori.objects.all(),
        widget=forms.CheckboxSelectMultiple,
        required=True
    )

    termini_servizio = forms.BooleanField(
        label = "Conferma di voler aderire al progetto con la classe indicata e di impegnarsi a rispettare le regole previste",
        required=True
    )

    class Meta:
        model = RichiesteLaboratori
        fields = (
            'provincia',
            'istituto',
            'plesso',
            'classe',
            'numero_studenti',
            'nome_referente',
            'cognome_referente',
            'email',
            'telefono',
            'classi_attivita',
            'laboratori',
            'note',
            'termini_servizio'
        )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['istituto'].queryset = Istituto.objects.none()
        self.fields['plesso'].queryset = Plesso.objects.none()

        if 'provincia' in self.data:
            try:
                id_provincia = int(self.data.get('provincia'))
                self.fields['istituto'].queryset = Istituto.objects.filter(provincia=id_provincia).order_by('nome')
            except (ValueError, TypeError):
                pass
        elif self.instance.pk:
            self.fields['istituto'].queryset = self.instance.provincia.istituto_set.order_by('nome')

        if 'istituto' in self.data:
            try:
                id_istituto = int(self.data.get('istituto'))
                self.fields['plesso'].queryset = Plesso.objects.filter(istituto=id_istituto).order_by('nome')
            except (ValueError, TypeError):
                pass
        elif self.instance.pk:
            self.fields['plesso'].queryset = self.instance.istituto.plesso_set.order_by('nome')

and here is the view:
class RichiestaLaboratorioCreateView(LoginRequiredMixin, generic.CreateView):
    template_name = "richiestalaboratorio/richiestalaboratorio_crea.html"
    form_class = RichiesteLaboratoriModelForm

    def get_success_url(self):
        return reverse("operativita:richiestalaboratorio-lista")

The view refers to a template called "richiestalaboratorio_crea.html" which render the form. Here is the code:
{% extends "base.html" %}
{% load crispy_forms_tags %}

{% block title %}
Nuova richiesta laboratorio
{% endblock title %}

{% block js-head %}

{% endblock js-head %}

{% block content %}

            Torna alle richieste di laboratorio

Aggiungi una richiesta di laboratorio

Compila il form per aggiungere una richiesta di laboratorio.

            <form method="post" id="richiestaLaboratorioForm" data-istituti-url="{% url 'operativita:ajax_carica_istituti' %}" data-plessi-url="{% url 'operativita:ajax_carica_plessi' %}">
                {% csrf_token %}
                {{ form|crispy }}
                <button type='submit' class="btn btn-primary mt-3">Aggiungi</button>
            </form>

{% endblock content %}

{% block js-footer %}

{% endblock js-footer %}

The actual result looks like this:

Now, what I'm supposed to do is to nest the ManyToMany selection in the model form. In fact, every "Laboratori" is associated with a specific "AnniScolastici". I would like to show the user a checkbox for an "AnniScolastici" entry and after that all the "Laboratori" entries associated with it.
The final result is supposed to be something like:

I'm trying to solve this but I can't find a solution... Can you help me, please?
Thanks for your time!

A: You are relying too much on Django abstraction here and will need to peel through the layers. A Model ManyToManyField in Django creates a separate table with two foreign key fields, in your case the laboratori field is a foreign key to that table. The M2M table will have a foreign key to RichiesteLaboratori and one to Laboratori.
M2M fields default form widget is a MultiChoiceSelectField, basically all you can do is choose zero or more of the records in the above mentioned M2M table. This is why you are only seeing a list of Laboratori, the other foreign key. Django doesnt have a widget for what you want to do.
You need to do this "manually" using nested formsets. See a tutorial here. You will also have to render the form fields for that yourself, I usually use widget_tweaks.

A: You can write a custom form field and widget. Is a not very portable solution, but can work for you.
In the field add customized choices, like anni_{anni.pk} and lab_{lab.pk} to differentiate the options when rendering the widget and when saving the form. In the form's save method check what options are available and save these related objects.

class MyCheckboxSelectMultiple(forms.CheckboxSelectMultiple):

    def render(self, name, value, attrs=None, renderer=None):
        """Render the widget as an HTML string."""
        context = self.get_context(name, value, attrs)
        html = ['
']
        last_lab = None
        for item in context['widget']['optgroups']:
            item = item[1][0]
            # print(item)
            value = item['value']
            if value.startswith('lab_'):
                if value != last_lab:
                    html.append('
')
            html.append(
                f'
'
                f'<input type="checkbox" name={item["name"]} value="{value}">'
                f' {item["label"]}'
                f'
'
            )
            if value.startswith('lab_'):
                if value != last_lab:
                    html.append('
')
                    last_lab = value
        html.append('
')
        return mark_safe(''.join(html))

class MyMultipleChoiceField(forms.MultipleChoiceField):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        choices = []
        for anni in AnniScolastici.objects.all():
            choices.append((f'anni_{anni.pk}', f'{anni}'))
            for lab in anni.laboratori_set.all():
                choices.append((f'lab_{lab.pk}', f'{lab}'))
        self.choices = choices

class RichiesteLaboratoriModelForm(forms.ModelForm):
    ani_laboratori = MyMultipleChoiceField(
        widget=MyCheckboxSelectMultiple
    )

    class Meta:
        model = RichiesteLaboratori
        fields = (
            'classe',
        )

    def save(self, commit=True):
        obj = forms.ModelForm.save(self, commit)

        ani_laboratori = self.cleaned_data.get('ani_laboratori')
        obj.classi_attivita.clear()
        for anni in AnniScolastici.objects.all():
            if f'anni_{anni.pk}' in ani_laboratori:
                obj.classi_attivita.add(anni)
        obj.laboratori.clear()
        for lab in Laboratori.objects.all():
            if f'lab_{lab.pk}' in ani_laboratori:
                obj.laboratori.add(lab)

        return obj

Anyway, I think thats not the bes option. I would rewrote the models, creating onte model that represents the relation betwen AnniScolastici and Laboratori (you can use it with the through argument of the ManyToManyField). Then I would replace the fields classi_attivita and laboratori with a ManyToManyField to this new model. Through this model you can access easy to the related AnniScolastici and Laboratori, without saving duplicated information in the database.


text:
Q: How to customize one column and display remaining in activeadmin I am using Active admin gem in my rails app. I added resources book which has 20 columns, now i need to customize only one column and print the remaining as it is. I tried below code
ActiveAdmin.register Book do
 index do
  column :description do
    raw "View Description"
  end
 end
end

but which hides all the columns and show only description. Any help will be useful.

A: In my case, I want only rename the one column,
I have done this way ->
index do
    column :one
    column :two
    ....
    column "View Description", :description # This will change you column label **description** to **View Description**
end

A: How about this?
ActiveAdmin.register Book do
  index do
    columns_to_exclude = ["name"]
    (Book.column_names - columns_to_exclude).each do |c|
      column c.to_sym
    end
    column :description do
      raw "View Description"
    end
   end
end

A: I was curious about this question too. Here is what I found
  index do
    column :id
    active_admin_config.resource_columns.each do |attribute|
      column attribute
    end
  end

https://github.com/activeadmin/activeadmin/blob/5dbf9b690302ecb4ba0c0ce59b2fb4735c88b35c/lib/active_admin/views/index_as_table.rb#L261

A: This also works when you want add or customize just a single column to the default list (based on an association which is for a belongs_to).
ActiveAdmin.register Book do
  index do
    column :publisher do |book|
      book.publisher.name
    end
    Book.column_names.each do |c|
      column c.to_sym
    end

  end
end

A: In General, this is quite easy..
ActiveAdmin.register Book do
  index do
    (Book.column_names - ["column_to_customize"]).each do |c|
      column c.to_sym
    end
    column :column_to_customize do
      raw "View Description"
    end
  end
end

A: If you specify an index block, you need to put all the columns that you want to show, because you are replacing the "default" behaviour.
In your case, you need to add the other 19 columns with something like:
ActiveAdmin.register Book do
 index do
  column :one
  column :two
  column :three
  column :name
  column :title
  column :pages
  column :description do
    raw "View Description"
  end
 end
end

A: This is pretty accurate to mimic original behavior in a generic way:
index do
  selectable_column

  Book.column_names.each do |c|
    # Filter foreign IDs and counter caches
    column c.to_sym unless c.ends_with?('_id') || c.ends_with?('_count')
  end

  Book.reflect_on_all_associations(:belongs_to).map(&:name).each do |association|
    column association
  end

  # Whatever custom thing you want

  actions
end


text:
Q: probability on Poisson process Three customers A, B, and C, simultaneously arrive at a bank with two tellers on duty. The two tellers were idle when the three customers arrived, and A goes directly to one teller, B goes to the other teller, and C waits until either A or B leaves before she can begin receiving service. If the service times provided by the tellers are exponentially distributed with a mean of 4 minutes, what is the probability that customer A is still in the bank after the other two customers leave

A: Hint:
Denoting the service times by $A,B,C$ you are asked to find:$$\Pr(A>B+C)=\Pr(A>B)\Pr(A-B>C\mid A>B)$$
Use symmetry to find the first factor. Exponential distribution is memoryless and this fact (again together with symmetry) can be used to find the second factor.
Other route is working out:$$\Pr(A>B+C)=\int\Pr(A>b+c)f_B(b)f_C(c)dbdc$$


text:
Q: Convenient way to create a wrapper Problem
I need to perform logic over and over on the results of several methods. The methods can have arbitrary result types. The simple use case looks like this:
A wrapper class with an execute method:
/**
 * Wrapper class which executes inner logic, processes the result of that logic and returns the processed result.
 *
 * @param <T>
 */
public abstract class Wrapper<T> {
    /**
     * Perform inner logic
     */
    public abstract T run();

    /**
     * Invoke inner logic and process it.
     */
    public T execute() {
        T result = run();
        // TODO: process result
        return result;
    }
}

And the logic in an inner class, example usage of the Wrapper:
public class WrapperDemo {
    /**
     * Simple invocation of the inner logic and then the outer logic
     */
    public static Boolean testMethod() {
        // wrap around logic and execute
        return new Wrapper<Boolean>() {
            @Override
            public Boolean run() {
                // TODO: perform logic, simply returning true for now
                return Boolean.TRUE;
            }
        }.execute();
    }

    public static void main(String[] args) {
        // demo method invocation
        Boolean result = WrapperDemo.testMethod();
        // process result
        System.out.println(result);
        System.exit(0);
    }
}

I'll have to apply this to several 100s of methods.
Question
Does anyone know a more convenient way to code this with less code for testMethod (e. g. maybe annotation)?

A: If you have Java 8, you could write the following:
public static <T> T execute(Wrapper<T> wrapper) {
  return wrapper.execute();
}

And then use it as following:
public static Boolean testMethod() {
  return execute(()-> {
    return Boolean.TRUE;
  });
}

Though I fail to see how this is better than the following:
public static <T> T wrap(T result) {
  // Process result
  return result
}

And using it like this:
public static Boolean testMethod() {
  return wrap(Boolean.TRUE);
}

A: In Java 8, by combination of lambda and default method, you can achieve similar thing without much change in your API (except you need to make Wrapper an interface instead of abstract class)
public interface Wrapper<T> {
    public T run();

    default public T execute() {
        T result = run();
        // TODO: process result
        return result;
    }
}

Then you can call it by
public static Boolean testMethod() {
    Wrapper<Boolean> w = ()-> {return Boolean.TRUE;};
    return w.execute();
}

But personally I don't think it make much sense.
If you want to add extra logic around a logic, probably what you need is a little twist:
public class ExtraAction<T> {
    Supplier<T> supplier;
    public ExtraAction(Supplier<T> supplier) {
        this.supplier = supplier;
    }
    public T execute() {
        T result = this.supplier.get();
        // some extra processsing
        return result;
    }
}

so it will be called like
Boolean result = new ExtraAction<>(()->{return Boolean.TRUE}).execute();

Even better, make your logic in Wrapper a Function<X,Y>, and make up something to chain your Supplier and Function together, so it will look like
result = Foo.forInput( ()-> { return logicToGetResult(); })
            .doExtra(ExtraAction::whateverAction).result();

A: If you want to use annotations, you should use a tool that allows such reflection to be used. Basic reflection can't be used because then you can't "intercept" the call. Java's Proxy might help, but you're constrained to use interfaces, which is not always what people want.
cglib is a library that removes all that hassle. With that, you can try the following:
@Target(METHOD)
@Retention(RUNTIME)
public @interface Wrap {
}

class Demo {
  @Wrap
  public Boolean testMethod() {
    return Boolean.TRUE;
  }
}

class Wrapper {
  public <T> T newInstance(Class<T> type) {
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(type);
    enhancer.setCallback(new InvocationHandler(){
      @Override public Object invoke(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        Object result = proxy.invokeSuper(obj, args);
        if (method.isAnnotationPresent(Wrap.class)) {
          execute(result);
        }
        return result;
      }
    });
    return enhancer.create();
  }

  public void execute(Object result) {
    // Add custom behavior to @Wrap-ped methods.
  }
}

Then you have to call the wrapper like this:
Demo demo = new Wrapper().newInstance(Demo.class);
demo.testMethod();

Other libraries exist too, like Byte Buddy or Javassist. But be careful because Java 9 is very close and forced those libraries into changing their core business very, very quick, possibly making them unstable.


text:
Q: pandas df.to_parquet write to multiple smaller files Is it possible to use Pandas' DataFrame.to_parquet functionality to split writing into multiple files of some approximate desired size?
I have a very large DataFrame (100M x 100), and am using df.to_parquet('data.snappy', engine='pyarrow', compression='snappy') to write to a file, but this results in a file that's about 4GB. I'd instead like this split into many ~100MB files.

A: One other option is to use the partition_cols option in pyarrow.parquet.write_to_dataset():
import pyarrow.parquet as pq
import numpy as np

# df is your dataframe
n_partition = 100
df["partition_idx"] = np.random.choice(range(n_partition), size=df.shape[0])
table = pq.Table.from_pandas(df, preserve_index=False)
pq.write_to_dataset(table, root_path="{path to dir}/", partition_cols=["partition_idx"])

A: Slice the dataframe and save each chunk to a folder, using just pandas api (without dask or pyarrow).
You can pass extra params to the parquet engine if you wish.
def df_to_parquet(df, target_dir, chunk_size=1000000, **parquet_wargs):
"""Writes pandas DataFrame to parquet format with pyarrow.

Args:
    df: DataFrame
    target_dir: local directory where parquet files are written to
    chunk_size: number of rows stored in one chunk of parquet file. Defaults to 1000000.
"""
for i in range(0, len(df), chunk_size):
    slc = df.iloc[i : i + chunk_size]
    chunk = int(i/chunk_size)
    fname = os.path.join(target_dir, f"part_{chunk:04d}.parquet")
    slc.to_parquet(fname, engine="pyarrow", **parquet_wargs)

A: I ended up using Dask:
import dask.dataframe as da

ddf = da.from_pandas(df, chunksize=5000000)
save_dir = '/path/to/save/'
ddf.to_parquet(save_dir)

This saves to multiple parquet files inside save_dir, where the number of rows of each sub-DataFrame is the chunksize. Depending on your dtypes and number of columns, you can adjust this to get files to the desired size.

A: Keep each parquet size small, around 128MB. To do this:
import dask.dataframe as dd

# Get number of partitions required for nominal 128MB partition size
# "+ 1" for non full partition
size128MB = int(df.memory_usage().sum()/1e6/128) + 1
# Read
ddf = dd.from_pandas(df, npartitions=size128MB)
save_dir = '/path/to/save/'
ddf.to_parquet(save_dir)

A: cunk = 200000
    i = 0
    n = 0
    while i<= len(all_df):
        j = i + cunk
        print((i, j))
        tmpdf = all_df[i:j]
        tmpdf.to_parquet(path=f"./append_data/part.{n}.parquet",engine='pyarrow', compression='snappy')
        i = j
        n = n + 1