text:
Q: Tkinter background while loop Okay I have asked this in a very specific way : https://stackoverflow.com/questions/21667119/tkinter-increment-a-varaible-while-still-running-code
But now to explain it in many less words.
I have a program running using tkinter. When a button is pressed it puts a value into a queue.
All I want is to be able to use a while loop to manipulate the data in the queue while the code still allows for more data to be added to the queue.
So basically repeated :
Check see if button pressed
if yes : add to queue
if no : do nothing
manipulate queue data.

Check the other question if you need to see code, its all in there.
I know many other posts have this but I cannot find an answer that explains it easily enough for me.
Simple code I can jar into a project please =D
thanks

A: Your tkinter program already has a "while" loop running -- mainloop. In most cases you don't need another loop inside that loop.
The pattern for using this loop is to create a function that does what you want for the body of the loop. It should do exactly one iteration of the loop. Once it is done, it needs to arrange for itself to be called again some time in the future using after. How far in the future defines how fast your loop runs.
Here's an example that checks the queue once per second:
import Tkinter as tk
import Queue as queue

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        self.queue = queue.Queue()

        buttonFrame = tk.Frame(self)
        for i in range(10):
            b = tk.Button(buttonFrame, text=str(i),
                          command=lambda button=i: self.press(button))
            b.pack(side="top", fill="x")
        self.lb = tk.Listbox(self, width=60, height=20)
        self.vsb = tk.Scrollbar(self, command=self.lb.yview)
        self.lb.configure(yscrollcommand=self.vsb.set)

        buttonFrame.pack(side="left", fill="y")
        self.vsb.pack(side="right", fill="y")
        self.lb.pack(side="left", fill="both", expand=True)

        self.manage_queue()

    def press(self, i):
        '''Add a button to the queue'''
        item = "Button %s" % i
        self.queue.put(item)
        self.log("push", item)

    def log(self, action, item):
        '''Display an action in the listbox'''
        message = "pushed to queue" if action == "push" else "popped from queue"
        message += " '%s' (queue size %s)" % (item, self.queue.qsize())
        self.lb.insert("end", message)
        self.lb.see("end")

    def manage_queue(self):
        '''pull an item off the queue and act on it'''
        try:
            item = self.queue.get_nowait()
            self.log("pop", item)
        except queue.Empty:
            pass

        # repeat again in 1 second
        self.after(1000, self.manage_queue)

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()


text:
Q: Custom JTable cell editor using my own component I am creating an inventory type program, I have to customize JTable inside a Commande class.
The Table have 4 columns and 10 empty rows. For the first column I want to set a custom components of type fournisseurUi witch is a JFrame derived class (Constains many components).
When the user start editing, I want an editable JComboBox to appear, after that an instance of fournisseurUi needs to Popup in the position of Table cell left corner, and I must not to be movable.
Here is an image that illustrated what I want to achieve.

(source: gulfup.com)
Her is my code so far,
package VIEW.dataManager;

import VIEW.FournisseurUi;
import VIEW.SearchFounisseurUi;
import VIEW.SearchProduitUi;
import java.awt.Color;
import java.awt.Component;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.table.TableCellEditor;

public class myTableCellEditor extends DefaultCellEditor
    implements TableCellEditor ,ActionListener{

    private SearchFounisseurUi Popup;
    private JButton editorComponent;
    private String value ="debut";

    public myTableCellEditor(JComboBox jcb) {
        super(jcb);
        editorComponent = new JButton();
        editorComponent.setActionCommand("change");
        editorComponent.setBackground(Color.yellow);
        Popup = SearchFounisseurUi.getInstance();
    }

    @Override
    public Component getTableCellEditorComponent(JTable jtable, Object o, boolean bln, int i, int i1) {

        value = "editor";
        return Popup;

    }

    public void actionPerformed(ActionEvent e) {
        if ("change".equals(e.getActionCommand())) {
            Popup.setVisible(true);
            System.out.println("preformed");
            fireEditingStopped();
        }
     }

}

In the Main class, I have used the custom Editor:
bonDachatTable.setDefaultEditor(String.class, new myTableCellEditor(new JComboBox()));

I got this little error:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: adding a window to a container
    at java.awt.Container.checkNotAWindow(Container.java:488)
    at java.awt.Container.addImpl(Container.java:1089)
    at java.awt.Container.add(Container.java:415)
    at javax.swing.JTable.editCellAt(JTable.java:3520)
    at javax.swing.plaf.basic.BasicTableUI$Handler.adjustSelection(BasicTableUI.java:1108)
    at javax.swing.plaf.basic.BasicTableUI$Handler.mousePressed(BasicTableUI.java:1038)
    at java.awt.AWTEventMulticaster.mousePressed(AWTEventMulticaster.java:280)
    at java.awt.Component.processMouseEvent(Component.java:6524)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
    at java.awt.Component.processEvent(Component.java:6292)
    at java.awt.Container.processEvent(Container.java:2234)
    at java.awt.Component.dispatchEventImpl(Component.java:4883)
    at java.awt.Container.dispatchEventImpl(Container.java:2292)
    at java.awt.Component.dispatchEvent(Component.java:4705)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4530)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
    at java.awt.Container.dispatchEventImpl(Container.java:2278)
    at java.awt.Window.dispatchEventImpl(Window.java:2739)
    at java.awt.Component.dispatchEvent(Component.java:4705)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:746)
    at java.awt.EventQueue.access$400(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:697)
    at java.awt.EventQueue$3.run(EventQueue.java:691)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.awt.EventQueue$4.run(EventQueue.java:719)
    at java.awt.EventQueue$4.run(EventQueue.java:717)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:716)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: adding a window to a container
    at java.awt.Container.checkNotAWindow(Container.java:488)
    at java.awt.Container.addImpl(Container.java:1089)
    at java.awt.Container.add(Container.java:415)
    at javax.swing.JTable.editCellAt(JTable.java:3520)
    at javax.swing.plaf.basic.BasicTableUI$Handler.adjustSelection(BasicTableUI.java:1108)
    at javax.swing.plaf.basic.BasicTableUI$Handler.mousePressed(BasicTableUI.java:1038)
    at java.awt.AWTEventMulticaster.mousePressed(AWTEventMulticaster.java:280)
    at java.awt.Component.processMouseEvent(Component.java:6524)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
    at java.awt.Component.processEvent(Component.java:6292)
    at java.awt.Container.processEvent(Container.java:2234)
    at java.awt.Component.dispatchEventImpl(Component.java:4883)
    at java.awt.Container.dispatchEventImpl(Container.java:2292)
    at java.awt.Component.dispatchEvent(Component.java:4705)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4530)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
    at java.awt.Container.dispatchEventImpl(Container.java:2278)
    at java.awt.Window.dispatchEventImpl(Window.java:2739)
    at java.awt.Component.dispatchEvent(Component.java:4705)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:746)
    at java.awt.EventQueue.access$400(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:697)
    at java.awt.EventQueue$3.run(EventQueue.java:691)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.awt.EventQueue$4.run(EventQueue.java:719)
    at java.awt.EventQueue$4.run(EventQueue.java:717)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:716)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

A:
after that an instance of fournisseurUi needs to Popup in the position of Table cell left corner, and I must not to be movable.

Not sure if this will help. It shows an example of popping up a JDialog with a JTextArea as an editor for the cell. It doesn't do exactly what you want since you want to display a combo box first, but maybe it will give you some more ideas:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;

/*
 * The editor button that brings up the dialog.
 */
//public class TablePopupEditor extends AbstractCellEditor
public class TablePopupEditor extends DefaultCellEditor
    implements TableCellEditor
{
    private PopupDialog popup;
    private String currentText = "";
    private JButton editorComponent;

    public TablePopupEditor()
    {
        super(new JTextField());

        setClickCountToStart(1);

        //  Use a JButton as the editor component

        editorComponent = new JButton();
        editorComponent.setBackground(Color.white);
        editorComponent.setBorderPainted(false);
        editorComponent.setContentAreaFilled( false );

        // Make sure focus goes back to the table when the dialog is closed
        editorComponent.setFocusable( false );

        //  Set up the dialog where we do the actual editing

        popup = new PopupDialog();
    }

    public Object getCellEditorValue()
    {
        return currentText;
    }

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

        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                popup.setText( currentText );
//              popup.setLocationRelativeTo( editorComponent );
                Point p = editorComponent.getLocationOnScreen();
                popup.setLocation(p.x, p.y + editorComponent.getSize().height);
                popup.show();
                fireEditingStopped();
            }
        });

        currentText = value.toString();
        editorComponent.setText( currentText );
        return editorComponent;
    }

    /*
    *   Simple dialog containing the actual editing component
    */
    class PopupDialog extends JDialog implements ActionListener
    {
        private JTextArea textArea;

        public PopupDialog()
        {
            super((Frame)null, "Change Description", true);

            textArea = new JTextArea(5, 20);
            textArea.setLineWrap( true );
            textArea.setWrapStyleWord( true );
            KeyStroke keyStroke = KeyStroke.getKeyStroke("ENTER");
            textArea.getInputMap().put(keyStroke, "none");
            JScrollPane scrollPane = new JScrollPane( textArea );
            getContentPane().add( scrollPane );

            JButton cancel = new JButton("Cancel");
            cancel.addActionListener( this );
            JButton ok = new JButton("Ok");
            ok.setPreferredSize( cancel.getPreferredSize() );
            ok.addActionListener( this );

            JPanel buttons = new JPanel();
            buttons.add( ok );
            buttons.add( cancel );
            getContentPane().add(buttons, BorderLayout.SOUTH);
            pack();

            getRootPane().setDefaultButton( ok );
        }

        public void setText(String text)
        {
            textArea.setText( text );
        }

        /*
        *   Save the changed text before hiding the popup
        */
        public void actionPerformed(ActionEvent e)
        {
            if ("Ok".equals( e.getActionCommand() ) )
            {
                currentText = textArea.getText();
            }

            textArea.requestFocusInWindow();
            setVisible( false );
        }
    }

    private static void createAndShowUI()
    {
        String[] columnNames = {"Item", "Description"};
        Object[][] data =
        {
            {"Item 1", "Description of Item 1"},
            {"Item 2", "Description of Item 2"},
            {"Item 3", "Description of Item 3"}
        };

        JTable table = new JTable(data, columnNames);
        table.getColumnModel().getColumn(1).setPreferredWidth(300);
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);

        // Use the popup editor on the second column

        TablePopupEditor popupEditor = new TablePopupEditor();
        table.getColumnModel().getColumn(1).setCellEditor( popupEditor );

        JFrame frame = new JFrame("Popup Editor Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new JTextField(), BorderLayout.NORTH);
        frame.add( scrollPane );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Javascript output issue with setTimeout and IIFI I am running

for (var i = 0; i < 3; i++) {
  setTimeout(function() {
    console.log(i);
  }(i), 4000);
}

Above code not waiting for 4 sec, it instantly prints 0, 1, 2.
Can somebody explain the reason for this output?
Thanks!


text:
Q: What is this probability notation? I came across a conditional probability function that looks like this.
$p(y|x; \{ \sigma + \tau \})$
But I can't seem to find what the notation after the ; and inside the {} is.
What is it?


text:
Q: how to display data based on specific id in laravel? I am new to laravel. I want to send data as id of existing data. Id comes from products.blade I send via href tag as shown below to gallery page. I have tried to find a way through other sites but it still doesn't work
id }}">

then i create a route like this
Route::resource('/dashboard/galleries', DashboardGalleryController::class)->middleware('admin')->shallow();

in the controller gallery, I made like this
public function index($id)
    {
        $gallery = Gallery::where('products_id', $id)->get();
        return view('dashboard.galleries.index', compact('gallery'));

    }

then inside the gallery page, I want to display a table to add images based on that id.
dashboard/galleries/index.blade.php

{{ $gallery->id }}

should i add data inside foreach or outside?

A: A restful resource controller sets up some default routes for you and even names them.
and ur case the logic should be inside show() function not index()
check this issue it will help u same issue solved here


text:
Q: Mockito Mocks don't reset after a Test or with `clearInvocations(...)` (JUnit, Spring Boot) I'm trying to Test a Method where I call a method from three different other Classes (adapterX, adapterY, adapterZ). I want to verify that only one of these Methods is getting executed with the verify(...) method from Mockito.
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {MessageValidationImplTest.TestConfig.class})
class MessageValidationImplTest {

    @TestConfiguration
    public static class TestConfig {
        // Creation of other Beans messageValidation depends on
    }

    @MockBean
    private AdapterY adapterY;

    @MockBean
    private AdapterX adapterX;

    @MockBean
    private AdapterZ adapterZ;

    @Test
    void testJsonPayload() {
        // Arrange
        //...

        //Act
        this.messageValidation.messageValidation(message, parameter);

        //Assert
        verify(this.adapterX).sendMessage(messageDto);
        verifyNoInteractions(this.adapterY);
        verifyNoInteractions(this.adapterZ);
    }

    @Test
    void testCsvPayload() {
        // Arrange
        // ...

        //Act
        this.messageValidation.messageValidation(message, parameter);

        //Assert
        verifyNoInteractions(this.adapterX);
        verify(this.adapterY).sendMessage(messageDto);
        verifyNoInteractions(this.adapterZ);
    }
}

I am creating the mocks via @MockBean from Spring.
When running the Tests I get this error message in the Logs (I get the same Error for the other Adapter in the second Test):
org.mockito.exceptions.verification.NoInteractionsWanted:
No interactions wanted here:
-> at com.acme.example.moduletest.core.impl.MessageValidationImplTest.testJsonPayload(MessageValidationImplTest.java:155)
But found these interactions on mock 'com.acme.example.y.AdapterY#0 bean':
-> at com.acme.example.core.impl.MessageValidationImpl.validateMessage(MessageValidationImpl.java:61)
Actually, above is the only interaction with this mock.

I've already tried manually resetting the Mocks with clearInvocations(adapterX, adapterY, adapterZ) but that doesn't make any difference.


text:
Q: Как отсортировать обьект в JS? Есть обьект :
[{
        "id": "1",
        "name": "300A"

    },
 {
        "id": "2",
        "name": "400"

    },

 {
        "id": "3",
        "name": "400b"

    },

{
        "id": "4",
        "name": "200"

    }]

Нужно отсортировать по имени, по цифрам,т.е.
200,300,300А,400,400b

A: https://ru.stackoverflow.com/a/432370/178988

console.log([
  { "id": "1",   "name": "300A" },
  { "id": "2",   "name": "400"  },
  { "id": "3",   "name": "400b" },
  { "id": "4",   "name": "200"  },
].sort(
  (x, y) => parseInt(x.name) - parseInt(y.name) || (x.name > y.name) - (x.name < y.name)
))
.as-console-wrapper.as-console-wrapper { max-height: 100vh }

A:

var a = [
  { "id": "1", "name": "300A" },
  { "id": "2", "name": "400" },
  { "id": "3", "name": "400b" },
  { "id": "4", "name": "200" },
  { "id": "5", "name": "400a" }
];

a.sort((a, b) => {
  var res = parseInt(a.name) - parseInt(b.name);
  if (res == 0 && a.name != b.name) {
    res = (a.name < b.name)? -1 : 1;
  }
  return res;
});
console.log(a);


text:
Q: How to produce a print-ready report based on Google Spreadsheet I have a Google Spreadsheet which stores data filtered from another Spreadsheet which in turn is a sorage of Google Froms questionnaire.
I'd like to produce a print-ready report on a filtered data, retreiving certain data columns and laying it out with some titles, decorations etc.
How can I produce such a report using Google tools?

A: In this article it explains pretty well how to: Google Apps Script to create PDF.
It made a predefined template of a Google Docs, copyed it and replaced predefined places with the info in the current line of the Spreadsheet, then convert to PDF. If you don't have a predefined length of elements, you can append new info on the documents with the body element.

A: Take a look at the AutoCrat add-on or Yet Another Mail Merge add-on.


text:
Q: jQuery button fire not working if put before PHP For some reason, my jQuery code is ignoring the button generated by PHP (IF the php is done inline).
This is the code that does not work (the jQuery click is not firing):
$('button').click(function(){
alert("CLICKED");

var btnNum = $(this).attr('value');
$(this).attr('disabled', 'disabled');

$.post("../update_rsvp.php", {id : btnNum}).done(function( data ) {
    var spanId = "#rsvpd-"+btnNum;
    $(spanId).html("YES");

  });

});

Well, technically the code works. However, ONLY if I generate my button BEFORE my html headers. If i generate it after the headers, then it does not work. This is he php code:
        <?php
        if( $cnt > 0 )
        {
            $where = array(
                "code" => $code
            );

            $what = array('inv_id','first_name', 'last_name', 'rsvpd');

            $count = $db->count($where, 'invited');
            $result = $db->select_where($where, 'invited' , $what);

            echo '
';
            echo '
';
            echo "You have $count invitations:
";
            echo "
";
            echo "";
            while($row = $result->fetch_assoc())
            {
                if($row['rsvpd'] == 1)
                {
                    $rsvpd = 'YES';
                    $disabled = 'disabled';

                }else{
                    $rsvpd = 'NO';
                    $disabled = '';
                }
                echo "

".$row['first_name']."

".$row['last_name']."

".$rsvpd."

                    <button value='".$row['inv_id']."' $disabled >RSVP</button>

";
            }
            echo "
";

        }
        else
        {

            echo "You have NO invitations!";

        }

        ?>

Any help/suggestion is truly appreciated!

A: Try using event delegation in this context,
$(document).on('click','button',function(){
  //your code here.
});

Please read here to know more about event delegation.

A: Where is your JS relative to your button?
Try it after your button, or wrap your script in a call to:
// Shorthand for $( document ).ready()
$(function(){
    // your js
});


text:
Q: Weird binary search behavior in Ruby I am trying to implement a recursive binary search in Ruby from scratch.
This is my code:
class Searcher

    def get_limits(array)
        [0, array.length - 1]
    end

    def binary_search_recursive(array, key)

        low, high = get_limits(array)

        mid = (low + high) / 2

        return -1 if low > high

        return binary_search_recursive(array[low, mid-1], key) if (array[mid] > key)

        return binary_search_recursive(array[mid+1, high], key) if (array[mid] < key)

        return mid if (array[mid] == key)

    end

end

arr = [1,3,4,12,16,21,34,45,55,76,99,101]
key = 34
s = BinarySearch.new
index = s.binary_search_recursive(arr, key)
puts index

When I put 'key' as 21, it weirdly gives me the right intended answer, the index 5. Arguably, I also get the right answer when 'key' = 3, but I suspect it's by chance.
You see, whenever 'key' != 21 or 3, I get either -1, 0, 1 or 2 for every element of the array.
What in the world am I doing wrong?
I've tried several different recursive binary search versions found online, this is just the most recent one. I feel like I get the same issue every time?

A: This is what you ask for after I edited my question. Problem with the code was you were splitting into new array so 34 was the only element at that array at the end therefore index was 0.
class Searcher
    def binary_search(array, val, low=0, high=(length - 1))
        return nil if high < low
        mid = (low + high) >> 1
        case val <=> array[mid]
          when -1
            binary_search(array, val, low, mid - 1)
          when 1
            binary_search(array, val, mid + 1, high)
          else mid
        end
     end
end

arr = [1,3,4,12,16,21,34,45,55,76,99,101]
key = 34
s = Searcher.new
index = s.binary_search(arr, key, 0, arr.length)
puts index


text:
Q: SDL2, gpg::GameServices and multi windows I'm using the C++ SDK for Google Play Game Services in a native application built on top of SDL2. The native part is a .so file loaded at runtime.
Everything works just fine as long as I use the application in a standard manner. On the other hand, I'm experiencing problems with gpg::GameServices when it comes to working with multi windows.
When the application switches to the multi windows mode, the native part leaves the main function and re-enters it by design. I don't know if the main function is abandoned because of an user that is terminating the application or because of a switch to the multi windows mode, therefore at the end of the function I reset the pointer to the gpg::GameServices object as suggested in the documentation. It is then re-initialized at the beginning of the same function.
However, it looks like something goes wrong and the application just freezes doing this for a while with the following message:

V/GamesNativeSDK: GameServices cleanup took longer than 15 seconds or returned an error. Destroying object while GameServicesImpl may still be active.

After 20 seconds the application starts again as expected but this freeze is quite annoying and I cannot understand what the reason.
As a side note, calling Flush or FlusBlocking doesn't solve the issue for obvious reasons (I did it just to check if it was the case).
Is there any issue terminating a gpg::GameServices even though the application isn't properly closed? I mean, when the activity is destroyed but the .so isn't discarded, instead a new activity is created and the main function invoked again immediately after?


text:
Q: vsftp "Access is denied" when writing as an authenticated user I have set up vsftpd for private FTP. Only authenticated users in the ftp group can login.
Also, every user is chrooted to its home directory (/home/username)
chroot_local_user=YES

I can log in, browse, download, but I'm not allowed to upload files. I get 550 Access is denied message from Windows Explorer
In order to tweak I did the following:
I made sure that the directory is user-writable (chmod g-rwx o-rwx u+w -R /home/username), I chose to do g-rwx otherwise it could be accessible via SSH by people in the users group that don't get chrooted. I made sure that directory and children elements are owned by user (forced chown -R as root) but they didn't help.
I found no useful thing in /var/log/messages file. I believed that vsftpd runs as the logged in user and I found confirmation running htop.
What kind of permission problem could cause this behaviour? If I go with SFTP with the same user I can do everything I want!
Thank you

A: There should be an option named write_enable in the configuration file.
As stated in the manpage:
write_enable
   This controls whether any FTP commands which change the filesystem are allowed or not. These commands
   are: STOR, DELE, RNFR, RNTO, MKD, RMD, APPE and SITE.

   Default: NO

it defaults to NO, so that might be the cause.


text:
Q: If-Else for getIntent - Android I have 2 activies. In first code, you see 2 rows and their click listeners. When first row clicked, I want to send "0" index to 2nd activity. As same, when I clicked second row, I want to send "1". So like that.
How can I do that?
Sender Side:
TableRow tricepsRow1;
    tricepsRow1=(TableRow) findViewById(R.id.arm_exercise_1);
    tricepsRow1.setClickable(true);
    tricepsRow1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
             indexValueStandart=0;
            Intent tricepsRowIntent = new Intent(getApplicationContext(),exercise_arm_triceps.class);
            tricepsRowIntent.putExtra("extra_arm_triceps",indexValueStandart);
            startActivity(tricepsRowIntent);
        }
    });

    TableRow tricepsRow2;
    tricepsRow2=(TableRow) findViewById(R.id.arm_exercise_2);
    tricepsRow2.setClickable(true);
    tricepsRow2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
             indexValueStandart=1;
            Intent tricepsRowIntent = new Intent(getApplicationContext(),exercise_arm_triceps.class);
            tricepsRowIntent.putExtra("extra_arm_triceps2",indexValueStandart);
            startActivity(tricepsRowIntent);
        }
    });

Receiver Side:
int getVIndexValue= getIntent().getIntExtra("extra_arm_triceps",0);
deneme.setText(String.valueOf(getVIndexValue));

A: try this:
int value = getIntent().getExtras().getInt("extra_arm_triceps");


text:
Q: how to get element from custom list using setonitemclicklistener I have done a simple task of getting data from database and then inflate it on listview.but i am facing problem when i click on listrow it is not selected and when i click on text which i put down on list from database then it perform selection(setonitemclicklistenr works)....and i also want to pass that particular listrow_text to other activity to edit that text....i have tried one way to perform   clicklistener on view in getview() but its not accepting startActivity(intent) command
and how do i get that text if i use setonitemclicklistener in the activity class...
I am a beginner and facing problem in understanding code which i searched for my problems....
list class where i use custom adapter
package com.example.smarttext2;

     import android.app.Activity;
     import android.content.Intent;
     import android.database.Cursor;
     import android.os.Bundle;
     import android.view.View;
     import android.widget.AdapterView;
     import android.widget.AdapterView.OnItemClickListener;
     import android.widget.ListView;
     import android.widget.Toast;

   public class dialoglist extends Activity {
        ListView list;
        Cursor cursor;
int count;
String[] str;
dialogadapter adapter;
database demo2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.dialoglist);

    demo2 = new database(getApplicationContext());

    list = (ListView)findViewById(R.id.listView1);

    cursor = demo2.fetch();
    count = cursor.getCount();
    str = new String[count];

    cursor.moveToFirst();
    for(int i=0;i<count;i++)
    {
        str[i]=cursor.getString(0);
        cursor.moveToNext();
    }
    adapter = new dialogadapter(this, str);
    list.setAdapter(adapter);

    list.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adapview, View view, int position,
                long pos_id) {
            // TODO Auto-generated method stub
            String pos = view.toString();//this line gives some value like          android.widget.linearlayout473y5834434....
            //Toast.makeText(getApplicationContext(), pos, Toast.LENGTH_LONG).show();
            Intent intent = new Intent(dialoglist.this,third.class);
            intent.putExtra("key",pos);
            startActivity(intent);
        }
    });

}

}
adapter class
      package com.example.smarttext2;

    public class dialogadapter extends BaseAdapter {
           Context context;
           String[] str1;
           LayoutInflater inflater;

  public dialogadapter(Context con,String[] st1) {
    // TODO Auto-generated constructor stub
     context = con;
     str1 = st1;
     inflater = ((Activity)con).getLayoutInflater();
}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return str1.length;
}

@Override
public Object getItem(int arg0) {
    // TODO Auto-generated method stub
    return arg0;
}

@Override
public long getItemId(int arg0) {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public View getView(final int position, View v, ViewGroup parent) {
    // TODO Auto-generated method stub
    v = inflater.inflate(R.layout.dialoglistitem, null);
    final TextView text = (TextView)v.findViewById(R.id.textView1);
    text.setText(str1[position]);

    return v;
}

}
activity where i want to send my data
 package com.example.smarttext2;

    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;

    public class third extends Activity {
        EditText et1;
        Button btn1;
        database demo;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.third);
    Intent intent = getIntent();
    String str1 = intent.getStringExtra("key");

    et1 =(EditText)findViewById(R.id.editText1);
    btn1 = (Button)findViewById(R.id.button1);

    et1.setText(str1);

    demo = new database(getApplicationContext());

    btn1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            demo.add(et1.getText().toString());
            finish();
        }
    });

}

}

A:   list.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View v, int arg2,
                final long arg3) {
            // TODO Auto-generated method stub
            TextView text = (TextView) v.findViewById(R.id.textView1);
            String string = text.getText().toString();
            Toast.makeText(getApplicationContext(), string, 3000).show();
            Intent intent = new Intent(dialoglist.this,third.class);
            intent.putExtra("key", string);
            startActivity(intent);

        }
    });


text:
Q: Any other way to write this statement I'm trying to write this statement in some other way.
True if 'sessionid' in request.cookies else False

Please help me with this.

A: Maybe you are looking for something like this:
if 'sessionid' in request.cookies:
    return True
else:
    reutrn False

of just
return ('sessionid' in request.cookies)

Also you can assign it to a variable instead of returning it.


text:
Q: Derivatives and double roots in $\mathbb{Z}/p^n\mathbb{Z}$ Is there a notion of double roots of polynomials in the ring $\mathbb{Z}/p^n\mathbb{Z}$? By that I mean if for a polynomial $P(x)$ we have that $p^n|P(a) $ and $p^n|P'(a)$, then $(x-a)^2$ divides $P(x)$ in $\mathbb{Z}/p^n\mathbb{Z}[X]$.
To be specific, I wanted to show that if a prime power $>3$ divides $(n^2+n+1)^2$ for $6|n-1$, then it divides $(n+1)^{n+1}-n^n$.
I wanted to prove it by showing that if a prime power $p^n$ divides $n^2+n+1$, then $n$ is a double root of $(x+1)^{n+1}-x^n$ in $\mathbb{Z}/p^n\mathbb{Z}$.
I tried this because if we have what I claim, then since $6|n-1$, we have that $(x+1)^{n+1}-x^n=(x^2+x+1)Q(x)$ for some $Q(x)$ belonging to $\mathbb{Z}[X]$, and the fact that $(x-n)^2 $ cannot divide $x^2+x+1$ in $\mathbb{Z}/p^n\mathbb{Z}$, we would have that due to the double root, $p^n|Q(n)$, which would give the desired.

A: If $f(x)\in \Bbb{Z}[x]$ and $f(a)\equiv f'(a)\equiv  0\bmod p^k$ then let $g(x) = f(x+a)=\sum_{n=0}^N c_n x^n$ so that $c_0= f(a)\equiv 0 \bmod p^k,c_1= f'(a)\equiv 0\bmod p^k$ ie. $g(x)=x^2 h(x)+p^k j(x)$ with $j\in \Bbb{Z}[x]$ and $f(x)=(x-a)^2 h(x-a)+p^k j(x-a)$.


text:
Q: last digit of four consecutive primes Since two consecutive primes ending in the same last digit has a probability less than mere chance, then four consecutive primes ending in the digits $1,3,7,9$
in any order will be greater than chance.  Examples of four primes ending in
the four different digits are $11,13,17,19$ and $23,29,31,37.$  Probability is
$\frac{4!}{4^4}=\frac{3}{32}$.  There can be two consecutive  sets of four each ending with the
same four digits: $47,53,59,61$ and $53,59,61,67$ with probability $\frac{3}{128}$.  There
can be three consecutive sets as in $1061,1063,1069,1087$ and $1063,1069,1087,1091 $ and $1069,1087,1091,1093$ with probability $\frac{3}{512}$.
Does anyone want to run through the first few thousand primes to see how the
results are better than mere chance four one set, two sets, three sets... having
this last digit property?  What's the largest string of consecutive primes
having the most sets of four moving from left to right?  Has anyone wondered if there are more groups of four like 11,13,17,19 with difference of first to last is eight than there are with a difference of greater than eight, as in 3331,3343,3347,3359?  What is the most common difference of such groups of four?


text:
Q: How to hit YouTube upload video api in command line ubuntu I want to upload multiple videos to Youtube through YouTube Data API v3.Well i have created the script and it runs smoothly through browser.
But i want to hit the YouTube Data API v3 through command line is there any way of doing that.
Here is main script.
<?php
    set_include_path(get_include_path() . PATH_SEPARATOR . 'YoutubeAPI');
    //require_once 'GoogleClientApi/src/Google/autoload.php';
    require_once 'Google/Client.php';
    require_once 'Google/Service/YouTube.php';
    session_start();

    $OAUTH2_CLIENT_ID = 'My Client ID';
    $OAUTH2_CLIENT_SECRET = 'Client Secret';

    $client = new Google_Client();
    $client->setClientId($OAUTH2_CLIENT_ID);
    $client->setClientSecret($OAUTH2_CLIENT_SECRET);
    $client->setScopes('https://www.googleapis.com/auth/youtube');
    $redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'], FILTER_SANITIZE_URL);
    $client->setRedirectUri($redirect);

    // Define an object that will be used to make all API requests.
    $youtube = new Google_Service_YouTube($client);

    if (isset($_GET['code'])) {
        if (strval($_SESSION['state']) !== strval($_GET['state'])) {
            die('The session state did not match.');
        }
        $client->authenticate($_GET['code']);
        $_SESSION['token'] = $client->getAccessToken();
        header('Location: ' . $redirect);
    }
    if (isset($_SESSION['token'])) {
        $client->setAccessToken($_SESSION['token']);
    }

    // Check to ensure that the access token was successfully acquired.
    if ($client->getAccessToken()) {
        try {
            // REPLACE this value with the path to the file you are uploading.
            $videoPath = "Video/naat.mp4";

            // Create a snippet with title, description, tags and category ID
            // Create an asset resource and set its snippet metadata and type.
            // This example sets the video's title, description, keyword tags, and
            // video category.
            $snippet = new Google_Service_YouTube_VideoSnippet();
            $snippet->setTitle("Test title");
            $snippet->setDescription("Test description");
            $snippet->setTags(array("tag1", "tag2"));

            // Numeric video category. See
            // https://developers.google.com/youtube/v3/docs/videoCategories/list
            $snippet->setCategoryId("22");

            // Set the video's status to "public". Valid statuses are "public",
            // "private" and "unlisted".
            $status = new Google_Service_YouTube_VideoStatus();
            $status->privacyStatus = "public";

            // Associate the snippet and status objects with a new video resource.
            $video = new Google_Service_YouTube_Video();
            $video->setSnippet($snippet);
            $video->setStatus($status);

            // Specify the size of each chunk of data, in bytes. Set a higher value for
            // reliable connection as fewer chunks lead to faster uploads. Set a lower
            // value for better recovery on less reliable connections.
            $chunkSizeBytes = 1 * 1024 * 1024;

            // Setting the defer flag to true tells the client to return a request which can be called
            // with ->execute(); instead of making the API call immediately.
            $client->setDefer(true);

            // Create a request for the API's videos.insert method to create and upload the video.
            $insertRequest = $youtube->videos->insert("status,snippet", $video);

            // Create a MediaFileUpload object for resumable uploads.
            $media = new Google_Http_MediaFileUpload(
                    $client, $insertRequest, 'video/*', null, true, $chunkSizeBytes
            );
            $media->setFileSize(filesize($videoPath));

            // Read the media file and upload it chunk by chunk.
            $status = false;
            $handle = fopen($videoPath, "rb");
            while (!$status && !feof($handle)) {
                $chunk = fread($handle, $chunkSizeBytes);
                $status = $media->nextChunk($chunk);
            }

            fclose($handle);

            // If you want to make other calls after the file upload, set setDefer back to false
            $client->setDefer(false);

            $htmlBody .= "
Video Uploaded

";
            $htmlBody .= sprintf('
%s (%s)
', $status['snippet']['title'], $status['id']);

            $htmlBody .= '
';
        } catch (Google_Service_Exception $e) {
            $htmlBody .= sprintf('
A service error occurred: %s
', htmlspecialchars($e->getMessage()));
        } catch (Google_Exception $e) {
            $htmlBody .= sprintf('
An client error occurred: %s
', htmlspecialchars($e->getMessage()));
        }

        $_SESSION['token'] = $client->getAccessToken();
    } else {
        // If the user hasn't authorized the app, initiate the OAuth flow
        $state = mt_rand();
        $client->setState($state);
        $_SESSION['state'] = $state;

        $authUrl = $client->createAuthUrl();
        $htmlBody = <<<END

Authorization Required

You need to authorize access before proceeding.

    END;
    }
    ?>

    <!doctype html>

            <title>Video Uploaded</title>

    <?= $htmlBody ?>


text:
Q: Skydrive for desktop not showing icon in notification area NEWEST UPDATE HAS ADDED THIS FEATURE. NEW NAME: ONEDRIVE

is this normal behavior? I'm concerned that some files will not be transferred. For example. I need to be sure that its safe to put my laptop to sleep so that later when I'm on my desktop I wont have to open up my laptop and sync again if I closed it too early. It doesn't even appear when I THINK it is syncing.
Thanks for any help in advance.
edit 1:
Yeah I know the app isn't required or even offered anymore, but what I was wondering was if they had some way to tell if it's syncing or not. The old desktop app had an icon in the notification area which had a animation for when it was syncing, but now there isn't anything there. Although when I try to go in and make it appear it says the application isn't active and the icon will show the next time it is. Its version is 17.0.2015.0811
Is it possible to force the icon to show in the notification area if it isn't designed to show up there at all? I basically just want the same functionality of Skydrive on windows 8.

A: In Windows 8.1 SkyDrive doesn't sync all files by default. It only downloads the files that you edit or explicitly made offline. This is called mart files
Here is a blog post to show the diffs between ealier SkyDrive client and the 8.1 way.

A: If you run the windows 8.1 Skydrive App (the metro/modern version) you will see in the upper right corner "uploading x items" this is how I know if any unsynced files are present on the machine I'm using. I wait for this to complete before I shut down.

A: I also found it annoying that I couldn't see which files in my local skydrive folder were syncing with the cloud in Win 8.1
Accidently I ran into a workaround that works for me.

*

*Open your webbrowser ( I used Firefox), go to skydrive.com and login.

*Go to your mail.

*Make a new mail.

*Go to 'Insert' → 'Files as attachments'  (or something like that, I'm doing this in Dutch).

*Go to the local Skydrive folder and open it.

*The files and folders that are synced have two blue arrows in their icons. (At least, with me they have...)

A: The ONEDRIVE update has fixed this issue. There is now an icon in the notification area.


text:
Q: How to use math symbols below an underbrace? I'm trying to use \alpha below an underbrace but it doesn't appear, in fact it also breaks the rest of the pdf. Especifically I'm doing this:
\underbrace{x^3}_\text{ \alpha }

What is the correct way to do that?

A: \alpha is not \text. Just use \underbrace{x^3}_{\alpha}.


text:
Q: Download and extract gz file using javascript [ClientSide] I'd like to download a database compressed as a .gz file in a cordova application and extract it to create a local WEBSQL database.
Is this posible?
I have the need to do this because my app needs to work offline, besides that this database I have to sync is so big that is unthinkable to download it uncompressed.
This sync only happens one time in my app. So after that is not a big deal.
Thanks in advance!
PD: I'm currently downloading each table separately but it takes too long, the code is a mess with all the callbacks and stuff. A compressed file with all data would be much more helpful.

A: You can find gz uncompressors for JavaScript in this question: JavaScript implementation of Gzip


text:
Q: Trouble with 301 redirect when www is not specified in url in some browsers I can't seem to find an answer to this specific question so sorry if it's answered.
Here's the redirect we have in .htaccess
Redirect 301 /product-name /products/product-name/

Problem:
If the www is left off then the redirect changes the path and no longer works. e.g. if this is entered into the browser window:
domain.com/product-name

Then the redirect creates this url in the browser window which obviously doesn't go anywhere:
www.domain.comproduct-name

Not sure what I'm doing wrong sorry - I should also mention that we have a non-www redirect at the bottom of the virtual host file like this:
<VirtualHost *:80>
    ServerName domain.com
    Redirect permanent / http://www.domain.com
</VirtualHost>

A: Add a / after .com in your redirect from non-www to www:
Redirect permanent / http://www.domain.com/

A: You need to add a trailing / in your Redirect rule:
Redirect permanent / http://www.domain.com/

The documentation for that directive states:

Additional path information beyond the matched URL-path will be appended to the target URL.

The matched URL-path is /, so anything "beyond" that will be appended. In http://domain.com/product-name, the part beyond the matched / is product-name, so appending that to http://www.domain.com (without putting a / back in) will give you http://www.domain.comproduct-name, as you observed.


text:
Q: Can I write scala code in netbeans6.9.1? Is it possible to write and compile Scala code in netbeans6.9.1?  I am a beginner to Scala programming, and am very much confused about this.

A: Yes, check out the Netbeans wiki; Scala modules are experimental and under active development, so check the nightly builds. Also check out ErlyBird; it's an Erlang/Scala IDE based on NetBeans.

A: I've never actually tried to write Scala in Netbeans personally but according to Dick Wall the support for Scala in Netbeans is pretty much the best of breed among the main 3 IDEs (IntelliJ, Eclipse, and Netbeans).  I know that's just anecdotal but it's from a pretty trusted source who literally inserted a whole new section into his Java Posse podcast just so he can geek out over Scala.
This looks like a fantastic place to get you started. http://wiki.netbeans.org/Scala

A: I have successfully used Scala with Netbeans 6.8. I tried using 6.9, but could not get it to work.
If you can manage with NB 6.8, then you are in luck.
Note that even with 6.8, refactoring is not available. However, code completion works very nicely and that is sufficient for me. I hope that there is a more usable Netbeans plugin for Scala in the near future.
Of course, you need to install the Scala plugin after installing NB 6.8 to get anything to work. Instructions here: http://wiki.netbeans.org/Scala68v1


text:
Q: How can I prevent my newly created conda environment from containing pip packages inherited from `pip` from the conda default environment? To save a conda environment and re-create it, I use:
# Save the environment
conda env export > my_conda_env.yml

# Re-create the environment
conda env create --file my_conda_env.yml

# Reactivate the environment
conda activate pytorch

However, when I do so, in the new environment the pip freeze lists some python packages that were not specified in the my_conda_env.yml but instead comes from the pip from the conda default environment. How can I prevent my newly created conda environment from containing pip packages inherited from pip from the conda default environment?
I notice that my_conda_env.yml contains prefix: /home/franck/anaconda3/envs/pytorch on the last line. What's the point of it?

> echo $PYTHONPATH
/home/code-base/runtime/app:/home/code-base/runtime/app/python:/home/code-base/runtime/app/python/dev:/app/python:/app/plugins:/app/plugins/jupyterlab-zip
> echo $PATH
/opt/conda/bin:/opt/conda/condabin:/opt/conda/bin:/app/python/bin:/opt/conda/bin:/usr/local/mpi/bin:/usr/local/nvidia/bin:/usr/local/cuda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin


text:
Q: How to convert this text file into R data.frame This is the text file.
y <- read.table("https://afltables.com/afl/stats/biglists/bg2.txt", skip = 1, header = T, sep = ' ')

Error in scan(file = file, what = what, sep = sep, quote = quote, dec = dec,  :
  line 3 did not have 30 elements

A: You can try this.
y <- read.fwf("https://afltables.com/afl/stats/biglists/bg2.txt", skip = 3, widths=c(6, 9, 30, 2), col.names = c("Rank","Games","Player","Teams" ))


text:
Q: To count total entry to a "string" in R I have created a df of 50 rows. I have labelled value >0.5 as fraud and rest as not fraud.
For the rows labelled as not fraud, i actually place them under another group called iffraud.
num = runif(50)
class_df = data.frame(num)
print(class_df)

class_df$type = ifelse(class_df$num > 0.5, 'fraud',"not fraud")
print(class_df)

iffraud = class_df[class_df["type"] == "not fraud"]

How should i count how many values stored in iffraud?

A: This could be done by using table like this:
set.seed(1)
num = runif(50)
class_df = data.frame(num)
print(class_df)
class_df$type = ifelse(class_df$num > 0.5, 'fraud',"not fraud")
print(class_df)
#>           num      type
#> 1  0.26550866 not fraud
#> 2  0.37212390 not fraud
#> 3  0.57285336     fraud
#> 4  0.90820779     fraud
#> 5  0.20168193 not fraud
#> 6  0.89838968     fraud
#> 7  0.94467527     fraud
#> 8  0.66079779     fraud
#> 9  0.62911404     fraud
#> 10 0.06178627 not fraud
#> 11 0.20597457 not fraud
#> 12 0.17655675 not fraud
#> 13 0.68702285     fraud
#> 14 0.38410372 not fraud
#> 15 0.76984142     fraud
#> 16 0.49769924 not fraud
#> 17 0.71761851     fraud
#> 18 0.99190609     fraud
#> 19 0.38003518 not fraud
#> 20 0.77744522     fraud
#> 21 0.93470523     fraud
#> 22 0.21214252 not fraud
#> 23 0.65167377     fraud
#> 24 0.12555510 not fraud
#> 25 0.26722067 not fraud
#> 26 0.38611409 not fraud
#> 27 0.01339033 not fraud
#> 28 0.38238796 not fraud
#> 29 0.86969085     fraud
#> 30 0.34034900 not fraud
#> 31 0.48208012 not fraud
#> 32 0.59956583     fraud
#> 33 0.49354131 not fraud
#> 34 0.18621760 not fraud
#> 35 0.82737332     fraud
#> 36 0.66846674     fraud
#> 37 0.79423986     fraud
#> 38 0.10794363 not fraud
#> 39 0.72371095     fraud
#> 40 0.41127443 not fraud
#> 41 0.82094629     fraud
#> 42 0.64706019     fraud
#> 43 0.78293276     fraud
#> 44 0.55303631     fraud
#> 45 0.52971958     fraud
#> 46 0.78935623     fraud
#> 47 0.02333120 not fraud
#> 48 0.47723007 not fraud
#> 49 0.73231374     fraud
#> 50 0.69273156     fraud
iffraud = class_df[class_df["type"] == "not fraud"]
a <- table(iffraud)
a
#> iffraud
#> 0.01339033 0.02333120 0.06178627 0.10794363 0.12555510 0.17655675 0.18621760
#>          1          1          1          1          1          1          1
#> 0.20168193 0.20597457 0.21214252 0.26550866 0.26722067 0.34034900 0.37212390
#>          1          1          1          1          1          1          1
#> 0.38003518 0.38238796 0.38410372 0.38611409 0.41127443 0.47723007 0.48208012
#>          1          1          1          1          1          1          1
#> 0.49354131 0.49769924  not fraud
#>          1          1         23
a[names(a)=="not fraud"]
#> not fraud
#>        23

Created on 2022-07-12 by the reprex package (v2.0.1)

A: Using boolean operations only:
sum(class_df["type"] == "not fraud")
23


text:
Q: How to repeat the rows n times I want to repeat the rows of a table n number of times.
suppose i have a table as below
Tab1
A B C
-----
1 2 3
2 3 4

and n =9
i want to get the result as below
1 2 3
2 3 4
1 2 3
2 3 4
1 2 3
2 3 4
1 2 3
2 3 4
1 2 3

I tried with connect by level and not getting the result as expected.

A: Like this?
SQL> with test (a, b, c) as
  2    (select 1, 2, 3 from dual union all
  3     select 2, 3, 4 from dual
  4    ),
  5  temp as
  6    (select a, b, c,
  7       row_number() over (order by column_value, a) rn
  8     from test cross join table(cast(multiset(select level from dual
  9                                              connect by level <= 9
 10                                             ) as sys.odcinumberlist))
 11    )
 12  select a, b, c
 13  from temp
 14  where rn <= 9
 15  order by rn  ;

         A          B          C
---------- ---------- ----------
         1          2          3
         2          3          4
         1          2          3
         2          3          4
         1          2          3
         2          3          4
         1          2          3
         2          3          4
         1          2          3

9 rows selected.

SQL>

What does it do?

*

*lines #1 - 4 represent your sample data

*CTE temp (lines #5 - 11) created all those rows; row_number is used to "rank" them, ordered by column_value (think of it as of a level pseudocolumn, if it is closer to you) and the a column value (why? Your sample output suggests so)

*final query (lines #12 - 15) selects the result for rn <= 9 (as you wanted to get 9 rows)

A: One approach is a recursive query. If you want 9 records, then:
with cte(a, b, c, rn, cnt, lvl) as (
    select a, b, c, row_number() over(order by a, b, c) rn, count(*) over() cnt, 0 lvl from mytable
    union all
    select a, b, c, rn, cnt, lvl + 1 from cte where lvl * cnt + rn < 8
)
select a, b, c from cte order by lvl, rn

The idea is to enumerate the original rows with row_number() and count them. Then we generate new rows, and stop as soon as the target number of rows is reached. This is somehow more efficient than generating more rows than needed, then filtering.
Demo on DB Fiddle:

 A |  B |  C
-: | -: | -:
 1 |  2 |  3
 2 |  3 |  4
 1 |  2 |  3
 2 |  3 |  4
 1 |  2 |  3
 2 |  3 |  4
 1 |  2 |  3
 2 |  3 |  4
 1 |  2 |  3


text:
Q: How can I start Tango & Cash There is a quest in the junk yard called Tango & Cash where you are supposed to try and break the record at mob killing the two dogs have. The first step says to go to the barriers and prepare. I have spent over an hour now walking around the area. I know where the barriers are but the quest never progresses. I thought maybe the quest It takes two to Tango was holding it up some how so I went and did that one, but still no luck.. The 'Regular' attacks do not appear to be that regular.
What am I doing wrong?

A: This mission is meant to be done in tandem with Edgar's Scrapyard Defense mission, which is what triggers the attacks. If you've already completed that one before, remember you can repeat any mission after 24 hours. Alternatively you can wait for someone else to do them and help them out - you both get kill credit that way and they might appreciate the assistance.


text:
Q: php pconnect vs connect If I have a script which inserts data then exits,
the script will be opened by 100 users at the same time or within 2 mins.
(Actually I'm doing email tracking.)
So pconnect is better, or connect is better to reduce the resource?
I have close when after insert.

A: mysql_pconnect() drops the open connection into a pool that can be used by any other request to the same process. As such, each worker keeps the connection open until it dies. This can be acceptable if you keep the number of workers low, but as soon as you raise the number of workers then you're better off switching to mysql_connect(). It will take slightly longer per request since the connection has to be made each time, but you will only create as many connections as there are requests, not workers.

A: connect uses fewer resources (idle instances of the web server don't need to keep a database connection open), but pconnect is slightly faster (don't have to open a new connection, it's already there).

A: You can also check this page for more info
http://php.net/manual/en/function.mysql-pconnect.php
Napoleon

A: If you use pconnect , you will have a lot of connections on SLEEP mode with this kind of script that runs 100 times in 2 minutes and your mysql will die.
You can use mysql_connect() , mysql_close()

A: mysql_pconnect() : is permanent connection with database. you cant lose your connection while such kind of operation.
mysql_connect() : is for connect database with normal way using some time due to large number of operation you might lose your connection.
I suggest mysql_pconnect() for database connection.


text:
Q: React List Keys row edit PNPJS dropdown & People Picker I am trying to enable row edit for a particular array of People Picker and Dropdown controls. Below is what I have so far,

              Division
              Assignee
              Added by

            {this.state.ListItems.reverse().map(function(item,key){
              return(

<Stack tokens={stackTokens}><Dropdown required={true}
                  onChange={this._getDropdownItem1}
                  placeholder="Select a Division"
                  options={this.state.DivisionListItems}
                  selectedKey={item.Division}
                  styles={dropdownStyles}
                  disabled={this.state.isEdit}/>
                  </Stack>

<PeoplePicker context={this.props.context}
                  personSelectionLimit={3}
                  groupName={""}
                  showtooltip={true}
                  tooltipMessage="Select multiple users for assigning the item"
                  isRequired={true}
                  disabled={this.state.isEdit}
                  ensureUser={true}
                  selectedItems={item.Assignee.map(assigne=>assigne.Title)}
                  showHiddenInUI={false}
                  principalTypes={[PrincipalType.User]}
                  defaultSelectedUsers={item.Assignee}
                  resolveDelay={1000} />

{item.Author.Title}

<DefaultButton className={styles.button} onClick={()=>{this.handleEdit(item,key)}} iconProps={{iconName:'Edit'}}></DefaultButton><DefaultButton className={styles.button} onClick={()=> { if (window.confirm('Are you sure you wish to delete this item?')){this.handleDelete(item.Id)}  this.onCancel(item) }} iconProps={{iconName:'Delete'}}></DefaultButton>

                 );
            }.bind(this))}

Handle edit function below

@autobind
public handleEdit(Division,Users){
  let selectedUsers = [];
   for (let item in Users) {
     selectedUsers.push(Users[item].Title);
   }
  this.setState({editusers:selectedUsers,Dropdownvalue:Division,isEdit:false });
  console.log("event is" + event);
}

How do I give unique id to dropdown control and people picker to be able to edit and perform operations only for that row in the array map? I have already given a key for each div which is the unique item.id.
Below is the rendering : Edit is editing the entire dropdown rows instead of that selected one.

A: In general, rather than trying to reference the control, it is better to have your controls reference unique values in State so that you just need to call setState when you want to change the way it is rendering.
I would suggest removing the isEdit State value, and adding a value such as editingItemId to your state, possibly defaulted in your constructor to zero (0) or negative one (-1).
Then, in your <Dropdown> and <PeoplePicker> control rendering, instead of setting the disabled attribute to {this.state.isEdit}, set the it with a conditional expression
disabled={item.Id === this.state.editingItemId}

You will then need to modify the setState() in your handleEdit to set editingItemId instead of isEdit. In fact, since you are already using an arrow function to pass the values, you probably no longer need a separate function, just modify the the onClick attribute in your <DefaultButton> control to the following:
onClick={()=>{this.setState({editingItemId:item.Id })}}

You haven't posted what your _getDropdownItem1 looks like, but I suspect you are going to need it to also accept the current item to know which item's value to change.
onChanged={selectedOption => { this._getDropdownItem1(item, selectedOption) }}

You'll want to do something similar when the value of your <PeoplePicker> changes.


text:
Q: How to extract particular text from Image From the following image, I want to extract number below text Arzt-Nr (654321161).
I've used OCR reader but it is extracting texts randomly not in a sequence, making it difficult to add a logic to extract no below "Arzt-Nr".
I've used following code but texts are not in sequence.
Is there any way to achieve this?
 String text = "";
            for (int i = 0; i < detectedItems.size(); i++) {
                TextBlock item = detectedItems.valueAt(i);
                String detectedText = item.getValue();
                List<Line> lines = (List<Line>) item.getComponents();
                for (Line line : lines) {
                    List<Element> elements = (List<Element>) line.getComponents();
                    for (Element element : elements) {
                        String word = element.getValue();
                        text = text + " " + word;

                    }
                    text += "\n";
                }
            }

A: Try to check a fixed length to the words after "Arzt-Nr" position, try also to check the pattern of the word founded.. for example if you need only numbers ecc...

A: Extract tsv output of image using tesseract and find the nearest text below the location of keyword. Also have a look at page segmentation modes of tesseract.
Link to Generating tsv
Link to use page segmentation


text:
Q: Matrix Calculation in MATLAB Could someone help me solve this problem in Matlab..
Suppose I have this Matriks
 A=[2-x 5
    2   3-x ]

where det(A)=0;
So, it can be written as : (to alculate the detrminant)
   (2-x * 3-x)-(5*2)=0

But In matlab I cannot put x before I define it..
There will be an error :
 Undefined function or variable 'x'.

Please help me!!
I'm not allowed to use det function from Matlab!!!

A: You have to say matlab that x is a symbolic variable:
syms x;
A=[2-x, 5; 2, 3-x];
solve(det(A) == 0)


text:
Q: R curl fetch connection problem: time out reached I've got some problem with the network connection of R.
library(curl)
req <- curl_fetch_memory("https://eu.httpbin.org/get?foo=123")
Error in curl_fetch_memory("https://eu.httpbin.org/get?foo=123") :
  Timeout was reached: [eu.httpbin.org] Operation timed out after 10002 milliseconds with 0 out of 0 bytes received

I've got no problem when directly access the URL above in Microsoft edge.
httr::GET("http://cran.r-project.org/Rlogo.jpg", config = httr::config(connecttimeout = 60))

And when I specifically set the timeout to be 60 seconds as above, the code ran forever and I had to manually call it back.
> sessionInfo()
R version 4.0.3 (2020-10-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19042)

Matrix products: default

locale:
[1] LC_COLLATE=Chinese (Simplified)_China.936
[2] LC_CTYPE=Chinese (Simplified)_China.936
[3] LC_MONETARY=Chinese (Simplified)_China.936
[4] LC_NUMERIC=C
[5] LC_TIME=Chinese (Simplified)_China.936

attached base packages:
[1] stats     graphics  grDevices utils     datasets
[6] methods   base

other attached packages:
[1] curl_4.3

loaded via a namespace (and not attached):
[1] compiler_4.0.3 tools_4.0.3
> curl_version()
$version
[1] "7.64.1"

$ssl_version
[1] "(OpenSSL/1.1.1a) Schannel"

$libz_version
[1] "1.2.11"

$libssh_version
[1] "libssh2/1.8.2"

$libidn_version
[1] NA

$host
[1] "x86_64-w64-mingw32"

$protocols
 [1] "dict"   "file"   "ftp"    "ftps"   "gopher"
 [6] "http"   "https"  "imap"   "imaps"  "ldap"
[11] "ldaps"  "pop3"   "pop3s"  "rtsp"   "scp"
[16] "sftp"   "smtp"   "smtps"  "telnet" "tftp"

$ipv6
[1] TRUE

$http2
[1] FALSE

$idn
[1] TRUE

I've already manually set my DNS to 8.8.8.8.
I'm in mainland China and I use VPN to bypass the GFW.

A: I've solved this problem with reference to this article and by adding :(mylocalhostaddress) to the end of the proxy. Hope it helps somebody in the future. Thank you, guys.


text:
Q: VS2013 Update 2/3 typescript crash when debugging MVC app - any suggestions? VS2013 Update 2/3 typescript crash when debugging MVC app - any suggestions?
Application: devenv.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.NullReferenceException
Stack:
at    TypeScriptDebugEngine.DebugMonitor.ScriptDocumentNotifications.Microsoft.VisualStudio.Debugger.ComponentInterfaces.IDkmScriptDocumentTreeNodeUnloadNotification.OnScriptDocumentTreeNodeUnload(Microsoft.VisualStudio.Debugger.Script.DkmScriptDocumentTreeNode, Microsoft.VisualStudio.Debugger.DkmEventDescriptor)
at Microsoft.VisualStudio.Debugger.EntryPoint.IDkmScriptDocumentTreeNodeUnloadNotification_OnScriptDocumentTreeNodeUnload(IntPtr, IntPtr, IntPtr)

A: I see this has been addressed for VS2013 Update 3 RTW
https://typescript.codeplex.com/workitem/2568

A: You could run devenv /log and then look in %appdata%\Microsoft\VisualStudio\12.0\ActivityLog.xml to see if there are more detailed explanations.  The file is usually large so if you don't know but can find the relevant block, you can post it up and we can try to assist.


text:
Q: flash drive imaging I would like to write an application that will create an 'image' of a flash drive.  This includes the total topography of the drive, not just the files.  So if the drive is 4GB you get a 4GB file.  Is this possible, and if so, could someone point me in the direction of information on how this may be accomplished?

A: It is possible.  I did it for an internal app, so I can't just paste the source for it, but I can give you some hints.  You will have to P/Invoke some things.
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "CreateFileW", SetLastError = true)]
public static extern IntPtr CreateFile(string name, int access, int share, byte[] attributes, int create, int flags, IntPtr template);

[DllImport("kernel32.dll", SetLastError = true)]
public static extern int CloseHandle(IntPtr handle);

[DllImport("kernel32.dll", SetLastError = true)]
public static extern int DeviceIoControl(IntPtr handle, DiskIoctl ioctl, byte[] inBuffer, int inBufferSize, byte[] outBuffer, int outBufferSize, ref int bytesReturned, IntPtr overlapped);

[DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "GetLogicalDriveStringsW", SetLastError = true)]
public static extern int GetLogicalDriveStrings(int bufferLength, byte[] buffer);

public enum DiskIoctl
{
    ScsiPassThrough = 315396,

    Lock = 589848,

    Unlock = 589852,

    Dismount = 589856,

    UpdateProperties = 459072,

    GetDiskLayout = 475148,

    SetDiskLayout = 507920
}

public enum ScsiOp
{
    ReadCapacity = 0x25,

    Read = 0x28,

    Write = 0x2A
}

A: Have you tried simply opening the drive as a file and copying it?


text:
Q: Getting name of the token with one alternative Right now, ANTLR does not return Lexer token name if the token contains only one alternative, e.g. for token SUZY : 'Suzy'; 'Suzy' will be encoded in the parse tree.
Now, I use token names to encode some useful information, e.g. SUZY_GENDER_FEMALE : 'Suzy';.
I have found two solutions so far to get the token name even if the token contains only one alternative:

*

*Repeat the same alternative in the token: SUZY_GENDER_FEMALE : 'Suzy' | 'Suzy';

*Use fragment keyword:

SUZY_GENDER_FEMALE : SUZY_FRAGMENT;
fragment SUZY_FRAGMENT : 'Suzy';

Both of these solutions work but are not ideal. I was looking into ANTLR implementation to change the behavior of tokens with one alternative in a way that their names will be returned but the code is quite complex and it will take some time eventhough the change might be quite easy.
Would someone know where to look in the code? (maybe it is as easy as adding one line at the proper place) Or perhaps I am misusing the token names and I should use a different ANTLR mechanism to get the information I want?

A: Your lexer has a static VOCABULARY. Try this on it:
Token token = ...
String tokenName = YourLexer.VOCABULARY.getSymbolicName(token.getType());


text:
Q: How to get correct order at y axis (matplotlob (P 2.7) correct I want to know why the order of the y axis is random (see screenshot). I'm plotting just x and y values from a text file with value pairs and want to have the y axis starting from minimum and ending with maximum value. In my case there is the smallest number (3) in the middle of the y axis plot. How can I correct this misorder?
txt-file:
1,5
2,3
3,5
4,3
5,7
6,3
7,5
8,3
9,5
10,3

Code:
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style

style.use('fivethirtyeight')

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)

def animate(i):
    graph_data = open('example.txt','r').read()
    lines = graph_data.split('\n')
    xs = []
    ys = []
    for line in lines:
        if len(line) > 1:
            x, y = line.split(',')
            xs.append(x)
            ys.append(y)
    ax1.clear()
    ax1.plot(xs, ys)

ani = animation.FuncAnimation(fig, animate, interval=1000)  # 1000 ms = 1 sec (updating)
plt.show()

I found out that editing the following two lines of code helps !!!
Before:
xs.append(x)
ys.append(y)
After:
xs.append(float(x))
ys.append(float(y))

A: You specified a FiveThirtyEight style on the line
style.use('fivethirtyeight')

Just remove it to use the normal plotting style.


text:
Q: Display NavigationController from AppDelegate when Push Notification Arrives
This is the current Setup I've for the Display of the Chat Conversation.
1): Push Notification Arrives
2): didRecieveRemoteNotification: Gets the Payload and Performs a NSNotification Post to the Root View Controller ( Initial View ) Which is a UITabBarController
3): UITabBarController Receives the NSNotification. Observer and executes a function that performs (  [self setSelectedIndex:2]; ) And sends the same payload using NSNotification
4): NavigationController Recieves the NSNotification Payload using a Observer Executes the function and performs the Push Segue to the Chat conversation Viewcontroller Embedded on the UINavigationController
This steps works for me except is a long way to pass the data many times until arrives to the final destination, not to mention that this  causes problems when making many pushes causing corrupted NavigationController.
What I would like to achieve is from the AppDelegate show Chat Conversation ViewController with it's NavigationController and don't cause the same corrupt navigationController when making the same Display over and Over again. And at the same time pass it the PayLoad from the Push Notification.
Here is my AppDelegate didRecieveRemoteNotification:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {

    if([[userInfo objectForKey:@"viewController"]  isEqual: @"chat_controller"]){

        if ( application.applicationState == UIApplicationStateInactive || application.applicationState == UIApplicationStateBackground  )
        {
            NSDictionary *userDictionary = @{@"nick_from" : [userInfo objectForKey:@"nick_from"],@"nick_to" : [userInfo objectForKey:@"nick_to"]};

            [self pushChatNotification:userDictionary];
        }
        else {

            NSString *message = [NSString stringWithFormat:@"%@ sent you a message want to reply?",[userInfo objectForKey:@"nick_from"]];

            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"New message"
                                                                message:message
                                                               delegate:self
                                                      cancelButtonTitle:@"Reply"
                                                      otherButtonTitles:@"Cancel", nil];
            [alertView show];

        }

    }

}

-(void)pushChatNotification:(NSDictionary *)userDictionary {

    [[NSNotificationCenter defaultCenter] postNotificationName:@"conversationParameters"
                                                        object:nil
                                                      userInfo:userDictionary];

}


text:
Q: I'd prefer it won't/it didn't Let's say that there is an event scheduled to take place in the near future and I would like to express that I think that it really shouldn't. Which one is correct:
A: I wonder whether it'll take place. I'd prefer it didn't, because of the virus.
B: I wonder whether it'll take place. I'd prefer it won't, because of the virus.
Based on my gut feel and this question I'd say that A is correct.
Are there any circumstances in which B would be correct? If I was talking about past event instead, I'd say "I'd prefer it hadn't happened"?

A: It's a counter-factual clause, so it uses the past didn't.


text:
Q: Show the error position in Jenkins How can I get the script error or the position of the error in the script in Jenkins console output?
I use Eclipse, Selenium Webdriver, Testng... for integration test, it's a Java project.

A: I would suggest you use the BFA plugin, you can define the error pattern firstly, if the error message hits the pattern, you will get a link in the Jenkins report to point out the line that error happened.


text:
Q: Grab files, published on a web page, programmatically I want to programmatically get a list of published zip files from one web site, unpack them and get a folder with some kind of text files on my desktop folder.
It is a list of dictionaries in XDXF format, published here http://dicto.org.ru/xdxf.html and downloaded eventually from SourceForge.
I am a beginner in web technologies, but good at Objective-C. I seek for any recommendations, which approach should I use, which languages and which articles can I read on this topic. I will not abuse that web sites, I just want to automate downloading of about 100 files and unzipping them. I do not want to do this manually. I have heard that some kind of this task is possible using Python.
As far, as I know, I can get a list of links to automatic download from that page. What is the best method to get them? Using regular expressions?

A: You can use modules like Mechanize to retrieve and scrap web pages, as well as files.  For unzipping, you can use the standard module zipfile.


text:
Q: How do I find the Firefox binary path? I have Firefox in the start menu, but there are no "properties" like in Windows.
How do I find out were Firefox is installed and how do I check the path of link of a menu item?

A: (I suppose you still don't use Unity but Gnome 2.)
That's a bit annoying in Gnome. What I do is, I click right and choose Add launcher to desktop. Then you have the launcher on your desktop and there is a context menu entry Properties (so again click right on the new file on your desktop and then Properties). This dialog will present most of the available information from the launcher.
An alternative would be to right click the application menu and choose edit. There you see all entries and you can also select Properties.
If you really want to find out the whole path for firefox, this shell command might be useful:
which firefox

This returns the full path to the file, which is executed when only firefox is called. whereis is a similar command which locates source/binary and manuals sections for specified files.
Note that a launcher file is just a text file with the ending .desktop. You can drag and drop it to any text editor if the property dialog doesn't provide enough information.

A: If you want to find all the places where your firefox is installed, including executables, libs, user settings, use
whereis firefox


text:
Q: changing json output when using serializer i want to ask, when i clicked the button and then println the json data appear like that picture..

i want to ask if it possible to change the output like this

{"telur" : "4" , "roti" : "4"}
       {"softball" : "60" , "senam" : "60"}

in the other way, i want to make it one bracket and erase type and amount in it, I'm using jsonserializer though..
the code like this..
menu.swift
class Nutritiondata
{
    var type = "type"
    var amount = 0
    //var date = "Date"
    init (type: String, amount: Int)
    {
        self.type = type
        self.amount = amount
        //self.date = date
    }
}

class Activitiesdata
{
    var type = "type"
    var amount = 0
    //var date = "Date"
    init (type: String, amount: Int)
    {
        self.type = type
        self.amount = amount
        //self.date = date
    }
}

table view
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell: CustomCell = tableView.dequeueReusableCellWithIdentifier("cell") as! CustomCell
        let menu = arrayOfMenu[indexPath.row]
        cell.setCell(menu.type, rightlabeltext: menu.unit, imagename: menu.image)
        var data = Nutritiondata(type: menu.type, amount: String(cell.value ).toInt()!)
        var json = JSONSerializer.toJson(data)
        JSONNutrisi.jsondata = json
        return cell
    }

var data = Nutritiondata(type: leftlabel.text!, amount: qtytext.text.toInt()!)
        var temp:Nutritiondata
        temp = data
        var idx = 0
        if(temp.amount-1 > 0) {
            temp.amount -= 1
        }
        data = Nutritiondata(type: leftlabel.text!, amount: qtytext.text.toInt()!)
        var json = JSONSerializer.toJson(data)
        var tempJson = JSONSerializer.toJson(temp)
        for(var i = 0; i < Nutritionmenu.data.count; i++){
            if(Nutritionmenu.data[i] == tempJson){
                self.check = true
                self.idx = i
            }
        }

A: First of all make one struct function which have type and amount
struct Nutritiondata {

    let type :String
    let amount : Int

    func Dict(age : Int) -> Nutritiondata
    {
        return Nutritiondata(type: type, amount: amount)
    }
}

Now take one array and store the data in it. here I am store static data but you store the data from response
let alldata = [Nutritiondata(type: "telur", amount: 4),Nutritiondata(type: "roti", amount: 4),Nutritiondata(type: "softball", amount: 60),Nutritiondata(type: "seman", amount: 60)]

Now you can use the data as below.
alldata[0].type   // telur

alldata[0].amount // 4

use this alldata in your cellForRowAtIndexPath delegate method.
let nutrition = alldata[indexPath.row]

you can display in tableview using below code
nutrition.type
nutrition.amount


text:
Q: How to change a cod from FOR to WHILE? (code in the body) i have a code that search into 2 chains, and give the bigest chain we can get from the both of them, print it and get how mane characters it have.
example: if i put 'paris' and 'sarix', we will get ari=3
Now, i need to know how to do it in while or other loops, but i really don't know how to do it, so if you could help me i would apreciate it.
CREATE OR REPLACE PACKAGE calc_cadena AS
    FUNCTION FNC_CALCULASUB (cadena1 VARCHAR2, cadena2 VARCHAR2)
    RETURN varchar2;
END;

CREATE OR REPLACE PACKAGE BODY calc_cadena AS
    var_ejemplo number;
    FUNCTION FNC_CALCULASUB (cadena1 VARCHAR2, cadena2 VARCHAR2)
    RETURN varchar2
    IS
    caden varchar2(1000);
    conta number(5);
    BEGIN
         conta:=0;
         caden:='';
         for I in 1..length(cadena2) loop
             for J in I..length(cadena2) loop
                 if UPPER(instr(cadena1,substr(cadena2,I,J-I+1)))>0 then
                    if length(substr(cadena2,I,J-I+1))>conta then
                        conta:=length(substr(cadena2,I,J-I+1));
                        caden:=substr(cadena2,I,J-I+1);
                    end if;
                 end if;
             end loop;
         end loop;

        return caden||'='||to_char(length(caden));
    end;
end;

SELECT calc_cadena.FNC_CALCULASUB('paris','sarix')
FROM    DUAL;

trying my best btw.


text:
Q: Set border for table cell with odfpy I created a Libre Office spreadsheet with odfpy and want some cells to have a border, but cannot figure out how to do that. I know that I can add style to a table cell and I know that TableCellProperties has an attribute called 'border'. I tried to set border=True, but that does not do anything. Can anyone please help me?
from odf.opendocument import OpenDocumentSpreadsheet
from odf.table import Table, TableRow, TableCell
from odf.style import Style, TableCellProperties

document = OpenDocumentSpreadsheet()
table = Table(name="Table1")
document.spreadsheet.addElement(table)

some_style = Style(name="some style", family="table-cell")
some_style.addElement(TableCellProperties(border=True))
document.style.addElement(some_style)

tr = TableRow()
table.addElement(tr)
cell = TableCell(stylename="some style")
tr.addElement(cell)

document.save("file.ods")

A: After 2 hours of searching I now found a solution:
some_style = Style(name="some style", family="table-cell")
some_style.addElement(TableCellProperties(border="0.74pt solid #808080"))
document.style.addElement(some_style)


text:
Q: LocalStack Kinesis Lambda sets StartingPosition to LATEST no matter what I have a simple localstack pipeline:

*

*Kinesis with a single shard

*Single lambda function reading the data

When setting the lambda function event_source_mapping the StartingPosition is always being set to LATEST regardless of what was input.
I have tried with awscli and boto3 with the same results. Am I doing something incorrectly?
No matter what I put in the --starting-position argument it always returns with LATEST selected.
I have tried with awscli and boto3 with the same results.
Am I doing something incorrectly?
Example awscli code:
aws --endpoint-url=http://localhost:4566 lambda create-event-source-mapping --function-name lambda_2_db --event-source arn:aws:kinesis:us-east-1:000000000000:stream/polling_single_shard --batch-size 100 --starting-position TRIM_HORIZON

Console output:


text:
Q: Error while passing a value from view to controller method in codeigniter I have tried the following code to pass the value from my_view.php(view) to myproject/delete (controller method) in codeigniter.
 $val=$my_records['roll_no']

up to here, there is no error and the roll no is stored in value and when i print that value, it is printed. But when I passed the $val to the method delete of controller class, it showed an error message

"The URI you submitted has disallowed characters.".

The portion of my code is:: echo site_url('myproject/update/$val')
there is a method update in my controller myproject.php and it takes $roll_no as argument.
How to fix it?

A: Use double quotes for your parameter. Single quotes prevent the variable from being parsed as PHP considers the $ to be a string literal.
<a href ="<?php echo site_url("myproject/update/$val ")?>">Edit

A: <a href="<?php echo base_url?>myproject/edit/<?php echo $my_records['roll_no']?>">Edit

and your roll_no (and uri) regex must be:
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';

You can edit it in config/config.php.
* I'm trying to learn English so i speak not well.


text:
Q: How to set Serial Number in Mat-table angular 5 I have used a mat-table in my angular app and have populated it successfully, but the original id's of the data are not serial wise and datas are filtered and only some data are to be displayed. Is there a way to add an auto incrementing serial no. My Html for the code:
    <mat-table #table2 [dataSource]="dataSource2" matSort>

  <ng-container matColumnDef="sn">
    <mat-header-cell *matHeaderCellDef mat-sort-header> SN. </mat-header-cell>
    <mat-cell *matCellDef="let item">{{ index + 1 }}</mat-cell>
  </ng-container>

  <ng-container matColumnDef="description">
    <mat-header-cell *matHeaderCellDef mat-sort-header> Description </mat-header-cell>
    <mat-cell *matCellDef="let item"> {{item.description}} </mat-cell>
  </ng-container>

  <ng-container matColumnDef="start_time">
    <mat-header-cell *matHeaderCellDef mat-sort-header> Start Time </mat-header-cell>
    <mat-cell *matCellDef="let item"> {{item.start_time}} </mat-cell>
  </ng-container>

  <ng-container matColumnDef="end_time">
    <mat-header-cell *matHeaderCellDef mat-sort-header> End Time </mat-header-cell>
    <mat-cell *matCellDef="let item"> {{item.end_time}} </mat-cell>
  </ng-container>

  <ng-container matColumnDef="total_pins">
    <mat-header-cell *matHeaderCellDef mat-sort-header> Total Pins </mat-header-cell>
    <mat-cell *matCellDef="let item"> {{item.total_pins}} </mat-cell>
  </ng-container>

  <ng-container matColumnDef="total_cards">
    <mat-header-cell *matHeaderCellDef mat-sort-header> Total Cards </mat-header-cell>
    <mat-cell *matCellDef="let item"> {{item.total_cards}} </mat-cell>
  </ng-container>

  <ng-container matColumnDef="remarks">
    <mat-header-cell *matHeaderCellDef mat-sort-header> Remarks </mat-header-cell>
    <mat-cell *matCellDef="let item"> {{item.remarks}} </mat-cell>
  </ng-container>

  <mat-header-row *matHeaderRowDef="displayedColumns2"></mat-header-row>
  <mat-row *matRowDef="let row; columns: displayedColumns2;"></mat-row>
</mat-table>

A: if you are using paginator from angular then
<td mat-cell *matCellDef="let item; let i = index">
    {{ (paginatorRef.pageIndex * paginatorRef.pageSize) + (i + 1) }}
 </td>

<mat-paginator
    #paginatorRef>
</mat-paginator>

if you are not using paginator and the whole table is in one page then
<td mat-cell *matCellDef="let element; let i = index;"> {{i+1}} </td>

A: Just use this code in a row to get index -
<td mat-cell *matCellDef="let element; let i = index;"> {{i+1}} </td>

Here is
forked working example

A: To get auto increment index value to the next pages.
([Page Index] * [Page Size] + [row Index + 1])
Table's td cell loop source code
<ng-container matColumnDef="id">
 <th mat-header-cell *matHeaderCellDef mat-sort-header> No.</th>
 <td mat-cell *matCellDef="let item; let i = index">
    {{ (paginatorRef.pageIndex * paginatorRef.pageSize) + (i + 1) }}
 </td>
</ng-container>

mat-paginator source code
<mat-paginator
    fxFlex="100"
    #paginatorRef
    [length]="5"
    [pageSize]="5"
    [pageSizeOptions]="[5, 10, 25, 100]">
</mat-paginator>

[ Note: Add local reference as #paginatorRef into your
mat-paginator code ]

A: You can add an incremental serial number within ngFor loop i.e.
<meta-table *ngFor="let item of items; let i = index;">
  <ng-container matColumnDef="sn">
    <mat-header-cell *matHeaderCellDef mat-sort-header> SN. </mat-header-cell>
    <mat-cell *matCellDef="let item">{{ i + 1 }}</mat-cell>
  </ng-container>
</meta-table>


text:
Q: Javascript - How to show escape characters in a string? Very simple question, but for some reason I can't find the answer anywhere after 10 minutes of Googling. How can I show escape characters when printing in Javascript?
Example:
str = "Hello\nWorld";
console.log(str);

Gives:
Hello
World

When I want it to give:
Hello\nWorld

A: JavaScript uses the \ (backslash) as an escape characters for:

*

*\' single quote

*\" double quote

*\ backslash

*\n new line

*\r carriage return

*\t tab

*\b backspace

*\f form feed

*\v vertical tab (IE < 9 treats '\v' as 'v' instead of a vertical tab ('\x0B'). If cross-browser compatibility is a concern, use \x0B instead of \v.)

*\0 null character (U+0000 NULL) (only if the next character is not a decimal digit; else it's an octal escape sequence)

Note that the \v and \0 escapes are not allowed in JSON strings.

A: You have to escape the backslash, so try this:
str = "Hello\\nWorld";

Here are more escaped characters in Javascript.

A: If your goal is to have
str = "Hello\nWorld";

and output what it contains in string literal form, you can use JSON.stringify:
console.log(JSON.stringify(str)); // ""Hello\nWorld""

const str = "Hello\nWorld";
const json = JSON.stringify(str);
console.log(json); // ""Hello\nWorld""
for (let i = 0; i < json.length; ++i) {
    console.log(`${i}: ${json.charAt(i)} (0x${json.charCodeAt(i).toString(16).toUpperCase().padStart(4, "0")})`);
}
.as-console-wrapper {
    max-height: 100% !important;
}

console.log adds the outer quotes (at least in Chrome's implementation), but the content within them is a string literal (yes, that's somewhat confusing).
JSON.stringify takes what you give it (in this case, a string) and returns a string containing valid JSON for that value. So for the above, it returns an opening quote ("), the word Hello, a backslash (\), the letter n, the word World, and the closing quote ("). The linefeed in the string is escaped in the output as a \ and an n because that's how you encode a linefeed in JSON. Other escape sequences are similarly encoded.


text:
Q: 1px difference in absolute positioning (Chrome/FF) A website I'm working on (URL in the comments) has a problem with the menu. It looks OK in Chrome if the bottom property of #nav is set to 2px, but looks bad in FF and IE. If I set it to 3px, it looks OK in FF and IE, but bad in Chrome.
Why does this happen? How can I fix it?

A: for Chrome/safari use hack
@media screen and (-webkit-min-device-pixel-ratio:0) {
#nav { bottom: 2px !important; }
}

will work for you

A: Browser @media hacks are one solution, but when you need cross-browser compatibility, you should use CSS reset, because all browsers have their default styles.  This have to be put in your style.css file before all your custom styles or include the cssreset.css file before your own styles.
You can find css reset here:  http://meyerweb.com/eric/tools/css/reset/

A: u can use browser detection using jquery and set the bottom value.and keep default value as 3px.
if ($.browser.webkit) {
    $("#nav").css('bottom','2px');
  }


text:
Q: Accessing objects in several forms in C#
Possible Duplicate:
Using and instance of a class on two forms

As I am pretty new to OOP - especially with Visual C# - I have a problem understanding the following:
A Windows Forms application has several forms. They all shall have access to a object Client (for communicating with a server) created in one of the forms. But how do I make exactly this object instance available in the other forms?

A: You can make the Client public static in the form parent form and access it from other forms. You have to make it thread safe if access synchronously.
Public will make it available to other forms where as make a single instance for all forms. To make it public static.
public static Client client.

To access it from other forms, assuming client is in Form1 and being accessed from other form.
Client client1 = Form1.client;


text:
Q: How do I stop agent presentations from appearing in GIS Map? I'm developing a model with a GIS map. I want the presentation of certain agents -- namely, custom library objects I am developing -- to appear outside the GIS map. When I move them outside of the map while I am developing the model, they are invisible; at runtime, they correctly appear where they should. I have explicitly excluded the agents from the GIS environment. What might I be doing wrong?

A: Try going into the agent and clicking on the graphical representation of it which is a picture in most cases. Then in the properties window check if "Icon" is checked like in the picture below.
This will replace the default icon used by AnyLogic (the red circle with a human shape in it) with the selected presentation and as a result you can place the agent outside of the GIS map while developing.


text:
Q: How to show multiline text with custom text ending regardless of text overflow? I have a description text and a date text. I want to show them together on a page. The description text can be as long as 3 lines at max. This is how it should look:
A description text that
can be as long as it can
be but not... * 17 Jan, 2002

In the above example, the description text gets cut because it overflows and shows an ellipsis, but date text is displayed completely. Here are other examples:
A not so long description *
 17 Jan, 2002

A not so long description but
long enough * 17 Jan, 2002

A not so long description but
long enough to be called long
* 17 Jan, 2002

A not so long description but
long enough to be called long
because it ... * 17 Jan, 2002

I have found an issue on Flutter Github, but I don't know if it will help me anyhow.

Add TextOverflow "ellipsisStart" , "ellipsisMiddle" and "ellipsisEnd" #45336

I, also, tried using library extended_text but, I couldn't achieve what I have described above. Here's what this library does with ellipsis

A:
Please check the below code
Center(
        child: RichText(
      text: TextSpan(
        text: 'A description text that can be as long as it can be but not ' * 10,
        style: DefaultTextStyle.of(context).style,
        children: <TextSpan>[
          TextSpan(
              text: '* 17 Jan, 2002', style: TextStyle(fontWeight: FontWeight.bold)),
        ],
      ),
    ));

A: Use your package or use this one: https://pub.dev/packages/readmore
Put your description in main text content, and you can add date as Show More or Show Less prefix. By using this your content will get ellipsis (...) and date will show full as you wanted.
You can do like this:
ReadMoreText(
    'Flutter is Google's mobile UI open source framework to build high quality native (super fast) interfaces for iOS and Android apps with the unified codebase.',
    trimLines: 2,
    colorClickableText: Colors.pink,
    trimMode: TrimMode.Line,
    trimCollapsedText: '17 Jan, 2002. Show more',
    trimExpandedText: '17 Jan, 2002. Show less',
    moreStyle: TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
);


text:
Q: Print without space in python 3 I'm new to Python, and I'm wondering how to print multiple values without having the extra space added in between. I want the output ab rather than a b without having to call print twice:
print("a", end="")
print("b")

Also, I have the following code:
a = 42
b = 84

and I want to print their values as a = 42, b = 84, yet if I do
print("a = ", a, ", ", b = ", b)

extra spaces are added (it outputs a =  42 , b =  84)
Whereas the Java style,
print("a = " + a + ", b = " + b)

raises a TypeError.

A: You can use the sep parameter to get rid of the spaces:
>>> print("a","b","c")
a b c
>>> print("a","b","c",sep="")
abc

I don't know what you mean by "Java style"; in Python you can't add strings to (say) integers that way, although if a and b are strings it'll work.  You have several other options, of course:
>>> print("a = ", a, ", b = ", b, sep="")
a = 2, b = 3
>>> print("a = " + str(a) + ", b = " + str(b))
a = 2, b = 3
>>> print("a = {}, b = {}".format(a,b))
a = 2, b = 3
>>> print(f"a = {a}, b = {b}")
a = 2, b = 3

The last one requires Python 3.6 or later. For earlier versions, you can simulate the same effect (although I don't recommend this in general, it comes in handy sometimes and there's no point pretending otherwise):
>>> print("a = {a}, b = {b}".format(**locals()))
a = 2, b = 3
>>> print("b = {b}, a = {a}".format(**locals()))
b = 3, a = 2

A: The actual syntax of the print() function is
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

You can see it has an arg sep with default value ' '. That's why space gets inserted in between.
print("United","States")            #Output: United States
print("United","States",sep="")     #Output: UnitedStates

A: You can also use
print("%d%d" %(a,b))

to print a and b not seperated by spaces in form of a formatted string. This is similar to the one in c.

A: To separate the strings or values you can use sep parameter in print()
print(a,b,sep='')

A: print() will automatically make spaces between arguments.
>>> print("a", "b", "c")
a b c

To have more control over spacing, you could use string formatting:
>>> v0, v1, v2 = "a", "b", "c"
>>> print("%s%s%s" % (v0, v1, v2))
abc
>>> print("%s%s%s".format(v0, v1, v2)
abc
>>> print(f"{v0}{v1}{v2}")
abc

I like this guide on the subject: https://realpython.com/python-f-strings/

A: On this page the answer is to print your normal text and at the end to use
sep="".
So the command
print("Hole", hole, "Par", par, sep="")

will give
"Hole1Par4"

assuming that hole==1 and par==4.