text:
Q: validating a text entry on tkinter I'm creating a program that allows the user to select a category and enter a value to calculate a charge. I would like to validate the text entry using my own validation file. However, when I run the program and enter nothing in the text entry, the error window keeps popping up over and over again. In addition, when I run the program and enter a valid number in the entry field, the charge comes out to 0.0, even though I have defined the calculation for the total charge.
Here is the program:
import tkinter
import tkinter.messagebox
import ValidationFile

validationObject = ValidationFile.ValidationClass ()

class MyGUI:
    def __init__ (self):
        self.main_window = tkinter.Tk ()

        self.top_frame = tkinter.Frame (self.main_window)
        self.middle_frame = tkinter.Frame (self.main_window)
        self.bottom_frame = tkinter.Frame (self.main_window)

        self.phone_var = tkinter.IntVar ()

        self.phone_var.set (1)

        self.pb1 = tkinter.Radiobutton (self.top_frame, \
                    text = 'Daytime (6:00 AM - 5:59 PM)', variable = self.phone_var, \
                    value = 0.12)
        self.pb2 = tkinter.Radiobutton (self.top_frame, \
                    text = 'Evening (6:00 PM - 11:59 PM)', variable = self.phone_var, \
                    value = 0.07)
        self.pb3 = tkinter.Radiobutton (self.top_frame, \
                    text = 'Off-Peak (Midnight - 5:50 AM)', variable = self.phone_var, \
                    value = 0.05)

        #pack phone buttons
        self.pb1.pack ()
        self.pb2.pack ()
        self.pb3.pack ()

        #create input and output buttons
        self.txtInput = tkinter.Entry (self.middle_frame, \
                                       width = 10)
        self.value = tkinter.StringVar ()

        self.lblOutput = tkinter.Label (self.middle_frame, \
                                        width = 10, textvariable = self.value)

        self.txtInput.pack()
        self.lblOutput.pack ()

        #create OK buton and QUIT button
        self.ok_button = tkinter.Button (self.bottom_frame, \
                        text = 'OK', command = self.show_choice)
        self.quit_button = tkinter.Button (self.bottom_frame, \
                        text = 'QUIT', command = self.main_window.destroy)

        #pack the buttons
        self.ok_button.pack (side = 'left')
        self.quit_button.pack (side = 'left')

        #pack the frames
        self.top_frame.pack ()
        self.middle_frame.pack ()
        self.bottom_frame.pack ()

        #start the mainloop
        tkinter.mainloop ()

    def show_choice (self):
        choice = self.phone_var.get ()
        value = -1
        while value == -1:
            valueEntry = self.txtInput.get()
            if valueEntry == '':
                value = -1
                tkinter.messagebox.showinfo (title = 'ERROR', \
                                             message = 'Please enter a valid number.')
            else:
                value = validationObject.checkFloat (valueEntry)

        total = choice * value
        self.value.set (total)

#create instance of MyGUI class
my_GUI = MyGUI ()

Here is the validation file:
#create validation class
class ValidationClass:

    def checkFloat (self, inputString):

        try:
            result = float (inputString)
        except Exception:
            return -1

        if result < 0:
            return -1
        else:
            return result

    def checkInteger (self, inputString):

        try:
            result = int (inputString)
        except Exception:
            return -1

        if result < 0:
            return -1
        else:
            return result

A: You made an infinite loop with while value == -1:. Nowhere in that loop do you pause to allow the user to try again. You don't need the loop at all:
def show_choice (self):
    valueEntry = self.txtInput.get()
    value = validationObject.checkFloat(valueEntry)
    if value == -1:
        tkinter.messagebox.showinfo (title = 'ERROR', \
                                         message = 'Please enter a valid number.')
    else:
        choice = self.phone_var.get()
        total = choice * value
        self.value.set (total)

Once you fix that you will have another problem: you use float values in your options but the variable is an IntVar, which can only handle integers. So "choice" will always be 0. You need to use DoubleVar instead.


text:
Q: How to export table contents to csv using java? Here I need to get the values from table instead of manual values like display name, age.
And I don't need to generate csv file in location. Instead, it should show me a popup that I can download the csv file. How to achieve this?
So far I tried this to export data to csv using java.
I used some manual values like display name, age. But I need the values to get from the table. For example

--datas--

Java Code:
import java.io.FileWriter;
import java.io.IOException;

public class test
{
   public static void main(String [] args)
   {
       generateCsvFile("D:/test.csv");
   }

   private static void generateCsvFile(String sFileName)
   {
    try
    {
        FileWriter writer = new FileWriter(sFileName);

        writer.append("DisplayName");
        writer.append(',');
        writer.append("Age");
        writer.append('\n');

        writer.append("Dinesh");
        writer.append(',');
        writer.append("23");
        writer.append('\n');

        writer.append("Kumar");
        writer.append(',');
        writer.append("29");
        writer.append('\n');

        //generate whatever data you want

        writer.flush();
        writer.close();
    }
    catch(IOException e)
    {
         e.printStackTrace();
    }
    }
}

A: I'm assuming you are generating your table dynamically and using httpSession, you can set the table in session like so:
HttpSession.setAttribute("Data", ArrayList<Object> data);

Then get the table from there when generating:
 ArrayList<Object> data = this.context.getSession().getAttribute("Data");

A: Suppose you have a jsp page with the table. While submitting the jsp page you can form the comma separated table value string from javascript by reading the table.
eg
//gets table
var table= document.getElementById('table1');

//gets rows of table
var rowLen = table.rows.length;

//loops through rows
for (i = 0; i < rowLen; i++){
   var oCells = table.rows.item(i).cells;
   var cellLen = oCells.length;
   for(var j = 0; j < cellLen; j++){
      /* get your cell info here */
      /* var cellVal = oCells.item(j).innerHTML; */
   }
}

and once you have the string of comma separated values, you can pass it to the action handling the submitted request.

A: Simple solution:

*

*Use RegEx to extract only the inner part of the table (between the

 tags)

*Use RegEx to remove all newlines between

 and those tags
themselves (rows)

*Use RegEx to replace "	" with ","

*Use RegEx to remove remaining tags

redpajama_set_name: RedPajamaStackExchange


text:
Q: JPA CriteriaBuilder and Substring I have a CriteriaBuilder where I am trying to get characters starting from 0 to 10. However I am not able to get the desired output.
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Emp> cq = cb.createQuery(Emp.class);
    Root<Emp> c = cq.from(Emp.class);
    cb.substring(c.<String>get("projDesc"), 0, 10);
    cq.orderBy(cb.desc(c.get("salary")));
    Query query = em.createQuery(cq);
    .....

What could be the reason for this?

A: From the javadoc

Create an expression for substring extraction. Extracts a substring of
  given length starting at the specified position. First position is 1.

Try doing cb.substring(c.<String>get("projDesc"), 1, 10);

I think you're forgetting to select the Expression<E>
Try cq.select(cb.substring(c.<String>get("projDesc"), 1, 10))
It will return List<String> if you need to Return the Emp you can use the
cb.construct(Emp.class, e.get("prop1"), e.get("prop2"), cb.substring(c.<String>get("projDesc"), 1, 10)));

A: I also, faced same problem in which I have to substring first three char and fetch all accounts starting from 107 which is number. for that I have used CriteriaBuilder and substring method like below.
Predicate accountNumber = criteriaBuilder.equal(criteriaBuilder.substring(from.get("accountNumber").as(String.class), 0, 3), cwipAcc);

but unfortunately it is not working for CriteriaBuilder and substring. so I have used like query to resolve this issue by given code below.
Predicate accountNumber = criteriaBuilder.like(from.get("accountNumber").as(String.class), String.valueOf(cwipAcc) + "%");

here, I have just fetched all the records which is starting from 107 and so on.
Example:
public List<GLCharts> findAccountForCWIP(Long cwipAcc, Long glInfo) {
        Map<String, Object> data = new HashMap();
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery<GLCharts> criteriaQuery = criteriaBuilder.createQuery(GLCharts.class);
        Root<GLCharts> from = criteriaQuery.from(GLCharts.class);

        Predicate accountNumber = criteriaBuilder.like(from.get("accountNumber").as(String.class), String.valueOf(cwipAcc) + "%");
        Predicate glCompanyInfo = criteriaBuilder.equal(from.join("gLCompanyInfo").get("id"), glInfo);

        Predicate finalPredicate = criteriaBuilder.and(accountNumber, glCompanyInfo);

        criteriaQuery.select(from).where(finalPredicate).orderBy(Stream.of(criteriaBuilder.asc(from.get("accountNumber"))).collect(Collectors.toList()));
        List<GLCharts> glChartsList = entityManager.createQuery(criteriaQuery).getResultList();

        return glChartsList;
    }

A: I faced the problem because my requirement was to use a number into substr. Following is the sample code.
 @Override
    public List<SampleProfile> findNonSampleProfileBySequence(Long SampleNo) {
        List<SampleProfile> profiles = new ArrayList<>();
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery<SampleProfile> criteriaQuery = criteriaBuilder.createQuery(SampleProfile.class);
        Root<SampleProfile> SampleProfileRoot = criteriaQuery.from(SampleProfile.class);
        List<Predicate> predicates = new ArrayList<Predicate>();
        if (SampleUtil.isValidLong(SampleNo)) {
            String SampleStr = Long.toString(SampleNo);
            if (StringUtils.isNotBlank(SampleStr) && SampleStr.length() > 5) {
                String SampleSequence = SampleStr.substring(5);
                predicates.add(criteriaBuilder.equal(criteriaBuilder.substring(SampleProfileRoot.get(SampleProfile_.id).as(String.class), 6), SampleSequence));
                predicates.add(criteriaBuilder.equal(SampleProfileRoot.get(SampleProfile_.address).get(Address_.department), SampleStr.substring(0,3)));
            }
        }
        if (!CollectionUtils.isEmpty(predicates)) {
            criteriaQuery.where(criteriaBuilder.and(Iterables.toArray(predicates, Predicate.class)));
            profiles = entityManager.createQuery(criteriaQuery).setMaxResults(AbstractJpaDAO.MAX_ROW_LIMIT).getResultList();
        }
        return profiles;
    }

Also note that for performance benefits you have to create an index on the same.
The Cast Keyword is important as Hibernate Dialect will create query like this, thus, it has to match with your index.
CREATE INDEX MY_SCHEMA_OWNER.IDX_SUBSTR_SMP_CODE ON MY_SCHEMA_OWNER.SMP_PROFILE (SUBSTR(**CAST**(SMP_CODE AS VARCHAR2(255 CHAR)),6));


text:
Q: Array element search I am new to java and have been trying to write how to search multidimensional arrays. My code works for elements found but when I enter an element that does not match, it does not printout anything. Please tell me what's wrong with my code.
import java.util.Scanner;
public class ArraySearch {
public static void main (String[] args){
    Scanner input = new Scanner(System.in);

    //lets create the array
    int [] [] arrayOfInts = {{1, 2,3,4}, {5,6,7,8},{9,10,11,12}};

    //create search variables
    System.out.println("Enter the key number to search for in the array: ");
    int key = input.nextInt();
    boolean foundIt;

    //perform search using a for loop
    for (int i = 0; i <arrayOfInts.length; i++){
        for (int j = 0; j <arrayOfInts[i].length; j++){
            if (arrayOfInts[i][j] == key) {
                foundIt = true;

                if (foundIt) {
                    System.out.println("found " + key + " at row " +i+ " column " +j);

                } else {
                    System.out.println(key + "is not in the array");
                }
            }
        }
    }
}
}

A: You should initialize your boolean to false, since local variables must be initialized before being used :
boolean foundIt = false;

Otherwise, if the key wasn't found, foundIt would be uninitialized when you access it in your if condition.
Not initializing foundIt should have given you a compliation error (The local variable foundIt may not have been initialized), but you have another error that hid this error. Your if statement that prints the output should be outside the for loops. Now it's inside the condition that finds a match, so it would only be evaluated if you found a match.

A: Your bracketing is wrong. The if - else statement
if (foundIt) {
    System.out.println("found " + key + " at row " +i+ " column " +j);

} else
        {System.out.println(key + "is not in the array");
}

Is inside the check of the for loop.
if (arrayOfInts[i][j] == key) {

You probably want to have it inside of the for loop to show the message for each match. But then you should just put a println message inside the if statement in the for loop
if (arrayOfInts[i][j] == key) {
  System.out.println("found " + key + " at row " +i+ " column " +j);

And to print the other message when the key was never found, but this has to be done at the end. Make sure you initialize the boolean in the beginning!
boolean foundIt = false;
...
//at the end
if(!foundIt) {
  System.out.println("found " + key + " at row " +i+ " column " +j);
}

A: You can change your code to following. There are many issues in your code. You have to make correct order of {}, If you do so you needs to initialize foundIt
    Scanner input = new Scanner(System.in);
    //lets create the array
    int[][] arrayOfInts = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
    //create search variables
    System.out.println("Enter the key number to search for in the array: ");
    int key = input.nextInt();
    boolean foundIt = false;
    for (int i = 0; i < arrayOfInts.length; i++) {
       for (int j = 0; j < arrayOfInts[i].length; j++) {
          if (arrayOfInts[i][j] == key) {
            System.out.println("found " + key + " at row " + i + " column " + j);
            // if found it will change the foundIt to true
            foundIt = true;
            }
        }
    }
    if (!foundIt) {
        System.out.println(key + "is not in the array");
    }

A: // perform search using a for loop
    for (int i = 0; i < arrayOfInts.length; i++) {
        for (int j = 0; j < arrayOfInts[i].length; j++) {
            if (arrayOfInts[i][j] == key) {
                    System.out.println("found " + key + " at row " + i + " column "
                            + j);
                    return;
            }
        }
    }
    System.out.println(key + "is not in the array");

I just added a return on finding the desired element and cut/paste the else branch to the end of the loop.

A: Your System.out is only inside this if-block
if (arrayOfInts[i][j] == key)

so if you don't find something the is no printout
I would do it in this way:
...
for (int i = 0; i <arrayOfInts.length; i++){
    for (int j = 0; j <arrayOfInts[i].length; j++){
        if (arrayOfInts[i][j] == key) {
            foundIt = true;
            // Tell where you found it
            System.out.println("found " + key + " at row " +i+ " column " +j);
        }
    }
}
// After all check whether you found something anytime
if(!foundIt){
    System.out.println(key + "is not in the array");
}
...

A: It's because your print statements the if (foundIt) ... else block is within the if (arrayOfInts[i][j] == key) block. This means that if the int is not found, the code never enters that inner if check where you print.
You can move the "not found" to the end.
For example:
    boolean foundIt = false;
    // perform search using a for loop
    for (int i = 0; i < arrayOfInts.length; i++)
    {
        for (int j = 0; j < arrayOfInts[i].length; j++)
        {
            if (arrayOfInts[i][j] == key)
            {
                foundIt = true;
                System.out.println("found " + key + " at row " + i + " column " + j);
            }

        }
    }
    if (!foundIt)
    {
        System.out.println(key + "is not in the array");
    }

Don't forget to initialize the foundIt to false first.

A: My Suggested Solution is :
bool foundit=false;

for (int i = 0; i <arrayOfInts.length; i++){
        for (int j = 0; j <arrayOfInts[i].length; j++){
            if (arrayOfInts[i][j] == key)
            {
            foundIt = true;
            break;
            System.out.println("found " + key + " at row " +i+ " column " +j);
           }
      }
}

if(!foundit)
{
system.out.println("Key not found in the array.")
}

A: This works:
import java.util.Scanner;
public class ArraySearch {
public static void main (String[] args){
    Scanner input = new Scanner(System.in);

    //lets create the array
    int [] [] arrayOfInts = {{1, 2,3,4}, {5,6,7,8},{9,10,11,12}};

    //create search variables
    System.out.println("Enter the key number to search for in the array: ");
    int key = input.nextInt();

    //perform search using a for loop
    for (int i = 0; i <arrayOfInts.length; i++){
        for (int j = 0; j <arrayOfInts[i].length; j++){
            if (arrayOfInts[i][j] == key) {
                System.out.println("found " + key + " at row " +i+ " column " +j);
                return;
            }
        }
    }
    System.out.println(key + " is not in the array");
}
}

Why:
commands in operatorif (arrayOfInts[i][j] == key) {} executing only if the element is found in array, so it is no need to use your boolean foundIt;. Use return to end executing the class, cos we have found what we wanted. The line System.out.println(key + " is not in the array"); should be after the two cycles so it will work only if we've checked each element of the two-dimensional array before.


text:
Q: Wordpress - Maintain "active" class on parent menu item I am implementing a theme in Wordpress. This theme has a top navigation menu with horizontal sub menus under each parent item. It puts an "active" class on current parent items currently been viewed (otherwise it won't show it's children sub menu items). I have somehow managed to maintain "active" class on current parent items by using these two function in functions.php.
/**
 * Wp Nav Menu Customizer.
 */
function special_nav_class($classes, $item){
     if( in_array('current-menu-item', $classes) ){
             $classes[] = 'active ';
     }
     return $classes;
}
add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);

class SH_Last_Walker extends Walker_Nav_Menu{

   function display_element( $element, &$children_elements, $max_depth, $depth=0, $args, &$output ) {

        $id_field = $this->db_fields['id'];

       //If the current element has children, add class 'sub-menu'
       if( isset($children_elements[$element->$id_field]) ) {
            $classes = empty( $element->classes ) ? array() : (array) $element->classes;
            $classes[] = 'has-sub-menu';
            $element->classes =$classes;
       }
        // We don't want to do anything at the 'top level'.
        if( 0 == $depth )
            return parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );

        //Get the siblings of the current element
        $parent_id_field = $this->db_fields['parent'];
        $parent_id = $element->$parent_id_field;
        $siblings = $children_elements[ $parent_id ] ;

        //No Siblings??
        if( ! is_array($siblings) )
            return parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );

        //Get the 'last' of the siblings.
        $last_child = array_pop($siblings);
        $id_field = $this->db_fields['id'];

            //If current element is the last of the siblings, add class 'last'
        if( $element->$id_field == $last_child->$id_field ){
            $classes = empty( $element->classes ) ? array() : (array) $element->classes;
            $classes[] = 'last';
            $element->classes =$classes;
        }

        return parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
    }
}

But now my problem is that when i click on sub menu or child of any parent menu item it successfully takes me to the child page but removes "active" class from parent and puts it on children (because it is the currently viewed page). I don't want it to put this class to children, i want it to be there (on parent item) whenever it's children are being viewed.
Any help would be much appreciated.

A: if you want to the dropdown grand-grand parent to be active when child menu item is active, then you can check for current-menu-ancestor or current-page-ancestor.. in your case, i think current-menu-ancestor check is most favorable.
function special_nav_class($classes, $item){
     if( in_array('current-menu-item', $classes) || in_array('current-menu-ancestor', $classes) ){
             $classes[] = 'active ';
     }
     return $classes;
}

I hope this would help, have a nice day :)

A: If all you want is to add some style or other properties by targeting the parent element then WordPress Provides you built-in classes for it for example:
when you are on a child page you can see classes like current-menu-parent current-page-parent current_page_parent current_page_ancestor these added to the parent page by WordPress you can choose any of these to target the parent element.

A: When you click on sub menu item WordPress will add .current-menu-item class to that sub menu item and .current-menu-parent class to the parent menu item of that sub menu item. You can style those specific classes according to your needs.


text:
Q: Specific Reference? Noncommutative topology and C^* algebras I stumbled across this "dictionary for noncommutative topology" http://planetmath.org/noncommutativetopology
and I would be very interested in learning more on the subject, particularly I'd like to see why these results are true.
What is the reference to the results in section 3 of the above linked page?

A: Dixmier's book is a fine, if dated, introduction to C*-algebra, but really not the right place to learn about noncommutative topology. The place you want to go is Alain Connes' Noncommutative Geometry.
Edit: in response to Yemon's comment I might refer to my own book Mathematical Quantization. Most of the correspondences mentioned are covered in Section 5.1, and many others can be found throughout the book.

A: Les C$^*$-algèbres et leurs représentations (answers most of these).
Find it here. That "dictionary" can also be found here.

A: K-Theory and C*-Algebras: A Friendly Approach (Oxford Science Publications)
by N.E. Wegge-Olsen.


text:
Q: How to get `useEffect` code reuse with custom hook that uses refs? I need to provide some custom functionality after render that uses refs.
It seems to be a perfect use case for useEffect, but it needs to be in a custom hook so that it can be reused.
Unfortunately, passing either a ref or its current to a custom hook that does useEffect appears to result in different behaviour than calling useEffect directly.
A working example looks like this:
 const useCustomHookWithUseEffect = (el1, el2) => {
      React.useEffect(() => {
    console.log("CUSTOM Use effect...");
    console.log("firstRef element defined", !!el1);
    console.log("secondRef element", !!el2);
  }, [el1, el2]);
}

const RefDemo = () => {
    const [vis, setVis] = React.useState(false);

  const firstRef = React.useRef(null);
  const secondRef = React.useRef(null);

  useCustomHookWithUseEffect(firstRef.current, secondRef.current);

  React.useEffect(() => {
    console.log("Standard Use effect...");
    console.log("firstRef element defined", !!firstRef.current);
    console.log("secondRef element ", !!secondRef.current);
    }, [firstRef.current, secondRef.current]);

  console.log("At RefDemo render", !!firstRef.current , !!secondRef.current);

    return (

        My ref is created in the initial render

 setVis(true)}>
        click me

      {vis &&

boo (second ref must surely be valid now?)

      }

    )
}

After the first render, the custom hook does not have the defined value of firstRef, but the in-line useEffect does.
After clicking the click-me, once again the custom hook does not get the most-recent update (though now it has the firstRef value).
Is this expected?
How could I achieve the goal: be able to re-usably supply useEffect-based code that uses refs?
https://jsfiddle.net/GreenAsJade/na1Lstwu/34/

Here's the console log:
"At RefDemo render", false, false
"CUSTOM Use effect..."
"firstRef element defined", false
"secondRef element", false
"Standard Use effect..."
"firstRef element defined", true
"secondRef element ", false

Now I click the clickme

"At RefDemo render", true, false
"CUSTOM Use effect..."
"firstRef element defined", true
"secondRef element", false
"Standard Use effect..."
"firstRef element defined", true
"secondRef element ", true

A: The problem is that you pass the ref.current while rendering to the custom hook. Now when you change the state of vis, the component is executed from top to bottom again (effects are read, not yet executed). But in this rerender at the point you call the custom hook, your ref has not yet updated (since we have not yet actually rerendered and therefore assigned the ref to the second div). And since you specifically pass the value of the ref, it won`t show the actual updated ref value but the value you passed at the time of the function call (null). When the effect is then run later on, you only have access to the explicit value you passed, unlike if you would pass the ref itself, whose value will always be up to date. This code sandbox should illustrate the issue.

A: I realised that I asked two questions.   This is the answer I found to "how should I achieve side effects from refs?"
The answer is "do not use refs in useEffect".   Of course, there are situations where it might be fine, but it is certainly asking for trouble.
Instead, use a ref callback to achieve the side effect of the ref being created and destroyed.
The semantics of ref callback are much simpler to understand: you get a call when the node when it is created and another when it is destroyed.


text:
Q: "ERROR: sql.h not found" when installing ruby-odbc gem with Apple M1 homebrew Context: on Apple M1, homebrew's location is /opt/homebrew' (not the usual /usr/local`)
macOS Intel: /usr/local
macOS ARM: /opt/homebrew

When I install ruby-odbc gem I'm getting the error ERROR: sql.h not found
If I pass in commandline arguments, I can get it to install...
gem install ruby-odbc -- --with-odbc-dir=/opt/homebrew/Cellar/unixodbc/2.3.9_1/
However, we are using bundler. I don't remember the best way to put this into a Gemfile and I'm convinced there must be a better way to solve this.
How do I tell gem, bundler, or my macOS that it should look in /opt/homebrew when compiling ruby-odbc?
I see that ruby-odbc uses mkmf.rb's have_header in core ruby. Perhaps a newer ruby would work too?

A: bundle config set build.ruby-odbc --with-odbc-dir=/opt/homebrew/Cellar/unixodbc/2.3.9_1


text:
Q: how to use primitives with iterator How do I use an iterator to get back a stack of ints?  My code works with for a statement if i use Objects but not int. If i use a for statement with Objects it work. Does it have something to do with Integer autoboxing?
public class Simulator {

    public static void main(String[] args) {
        Stack<Integer> s = new Stack<Integer>();
        s.insert(15);
        s.insert(25);
        s.insert(7);

        for ( int t : s) {
            System.out.println(t);
        }
    }
}

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package stack;

import java.util.Iterator;

/**
 *
 * @author
 */
public class Stack<Item> implements Iterable {

    /**
     * @param args the command line arguments
     */
    private Item[] arr;
    private int n;

    public Stack() {
        System.out.println("Stack initialized");
        arr = (Item[]) new Object[1];
        n = 0;
    }

    public void insert(Item element) {
        if (n == arr.length) {
            resize(arr.length * 2);
        }
        arr[n++] = element;
    }

    @Override
    public Iterator iterator() {
        return new ListIterator();
    }

    private class ListIterator implements Iterator<Item> {

        private int i = n;

        @Override
        public boolean hasNext() {
           return i > 0;
        }

        @Override
        public Item next() {
            return arr[--i];
        }

        @Override
        public void remove() {
        }
    }

    // resize the underlying array holding the elements
    private void resize(int capacity) {
        assert capacity >= n;
        Item[] temp = (Item[]) new Object[capacity];
        for (int i = 0; i < n; i++) {
            temp[i] = arr[i];
        }
        arr = temp;
    }
}

A: The first problem is with your Stack class. It just implements the raw Iterable type. It should implement Iterable<Item> instead. Read more about raw types in the Java Generics FAQ.
You still wouldn't be able to create a Stack<int>, but the code using Stack<Integer> and iterating with an int iteration variable would be fine.
Once you've changed the class declaration to:
class Stack<Item> implements Iterable<Item>

and changed the iterator method to:
@Override
public Iterator<Item> iterator() {
    return new ListIterator();
}

... you'll still get lint warnings due to your array casts (which aren't actually checking anything) but the rest should be okay.


text:
Q: Export to PDF with String and Cell Value I need to export excel sheet as PDF named with String and Cell Value for Example XXXY - Cell Value
Note: i do not need codes that uses path location for the saving file
I tried the following code
Sub IVI_Formatting_Export_Two_PDF ()

Dim strFilename As String

Dim srn As String Dim SWPDF As Worksheet

Set SWPDF = ThisWorkbook.Sheets ("BSS CPES MainPage")

srn = "CPE Main-Page"

strFilename = SWPDF.Range ("F7").Value

Create File name with Warehouse Name

Export2PDF

SWPDF.ExportAsFixedFormat

Type:=xlTypePDF,

Filename:=strFilename & srn,

Quality:=xl QualityStandard,

IncludeDocProperties:=False,

IgnorePrintAreas:=False,

From:=1,

To:=1,

OpenAfterPublish:=True

End Sub

A: You must specify a path to export PDF. Without path where it will be saved? You can use variable to specify path. Currently I have used same as file path. Your problem was in filename parameter. Try below sub.
Sub IVI_Formatting_Export_Two_PDF()
Dim strFilename As String
Dim srn As String
Dim SWPDF As Worksheet

Set SWPDF = ThisWorkbook.Sheets("BSS CPES MainPage")

srn = "CPE Main-Page"
strFilename = SWPDF.Range("F7").Value

'Create File name with Warehouse Name
'Export2PDF

    SWPDF.ExportAsFixedFormat Type:=xlTypePDF, _
    Filename:=ThisWorkbook.Path & "\" & strFilename & "_" & srn & ".pdf", _
    Quality:=xlQualityStandard, _
    IncludeDocProperties:=False, _
    IgnorePrintAreas:=False, _
    From:=1, _
    To:=1, _
    OpenAfterPublish:=True

'Clear memory
Set SWPDF = Nothing
End Sub

Here Filename:=ThisWorkbook.Path & "\" & strFilename & "_" & srn & ".pdf" will export the PDF to same folder where your workbook is located. Also you must include .pdf extension to export excel sheet as pdf.


text:
Q: Win10 doesn't respect pagefile settings for other disks than C: I tried to move my pagefile off from C: to another disk, D:. I set my preferences in Start > Advanced System Settings > Advanced > Performance > Advanced > Virtual Memory. I have set
C:  100-1000MB   (They advice to leave at least minimal page file on C:.)
D:  100-16000MB

However, Win10 doesn't create pagefile.sys on D:, which often results in apps crashing because of out-of-memory. (It rarely does create it, but mostly it doesn't.)
This used to work in the past. Has anything changed in this regard in the last Win10 updates? Could this be caused by Group policy? If this should work, how can I determine the cause of the problem? In the Event Viewer I found nothing suspicious.
Configuration: Win10 Enterprise, version 20H2 (10.0.19042), there is plenty of space on the disks.

A: You don't need to have a page file on C at all, you can have it on just D with no problems. Since you have it set to only 1GB on C, I recommend just removing it from C and have D handle the page file. I have my system setup that way. I have 2 SSDs, OS is installed on 1 and the paging file on 2. However, it should be able to do fine using both, you may be getting that out-of-memory crash because it does use up all the available memory on both C & D, you should have it set to a System Managed size on one of the drives to ensure you never hit a cap, short of running out of drive space.


text:
Q: AngularJS/Cordova/Phonegap Ipad 3 and Iphone 4s not fast enough? I own an AngularJS app (angular v1.2.19) that I converted into iOS app using Cordova/PhoneGap.
However, it seems that the resolve property (see below) is taking into account but the associated page is displayed BEFORE the promise is resolved, leading to some ugly flickering.
Flickering in this case is:  the form only displays fieldset and legend + buttons for 1 second, and then the whole data (input etc..) are displayed.
 $routeProvider
        .when('/page/meetings/123/edit',
        {
          templateUrl: "edit.html",
          controller: "EditCtrl"
          resolve: {
              activities: ['Activities', function (Activities) {
                    return Activities.getList().then(function(response) {
                        return response.data;
                    });
                }]
            }
          }
        }
      )
//page is displayed before activities are fully loaded.

Does a known bug regarding resolve property exist with Cordova? Or a configuration I should add?
It works well in a browser, but in the iOS app, I don't manage to make Angular resolve the promise before the page is rendered.
I don't figure out why this only occurs with iOS app and not web browser.
When I remove the resolve section, the page displays without flickering, although I don't have activities populated.
Maybe just a performance reason? Indeed, I tested the path /page/meetings/123/edit in my Ipad 3 (named "new Ipad") from a page where there isn't a lot of content, and it shows the page AFTER promises are resolved => fine.
The strange thing is that when I put the same link on a heavy page..listing several items, the targeted page (edit page) still flickers, displaying no form for about 1 second and then displays the whole.
To make things more strange, the exact same code on Iphone 4s involve flickers no matter where is the /page/meetings/123/edit link (heavy or light page).
On the contrary, web mobile version (Safari) on the iPhone 4s and Ipad is perfect. Really don't figure out why.

A: After some...hours of search, I found the reason.
In the edit page's controller, I initially did this:
$anchorScroll(); //scrolling to the top

It seems that it conflicts with the display of elements.
That explains why when I come from a page that needed scrolling (like 20 items in the list page), the conflict appears.
So the solution I choose is to do this, in order to delay the scrolling with the most minimal amount of time:
$timeout(
    function(){
       $anchorScroll();
    },
0);

The whole now works well with PhoneGap/Cordova for iOS app.


text:
Q: Insert query for linked tables Why does my insert query insert 9 records when I just have 3 records?
Here is my table structure:
SubjectTable
SubjectID   (Autonumber)    Primary Key
MasterID    (Number)        Foreign Key
Description (Text)

MasterTable
MasterID    (Autonumber)    Primary Key
StatusID    (Number)        Foreign Key
StudentID   (Text)
Description (Text)

StatusTable
StatusID    (Autonumber)    Primary Key
Description (Text)

Table Relationships:
MasterTable (One) --> (Many) SubjectTable
StatusTable (One) --> (Many) MasterTable

Data from Table1 to be inserted in MasterTable:
StudentID Description
JP121     Description 1
SP223     Description 2
JK111     Description 3

Insert Query:
INSERT INTO Master ( StudentID )
SELECT Table1.StudentID
FROM Table1;

A: Are you running the INSERT query programmatically? Perhaps its being executed multiple times.
EDIT: Just a silly query issue.


text:
Q: How to show a notification icon in android studio I am building an android application where I am letting the users to sign in using google also. When they sign in using google and do not register themselves using the registration page then there are certain information which are left out.I also have a screen which updates the profile information of the user.
I want to set an icon on the home screen(kind of a bell icon) which displays that there are some notification and when the user click on that the button it tells that some information are left to be added and it redirects them to the update profile page.
The icon I want is like the notification icon(bell) in youtube.
Is there any way I can do this?
EDIT :
activity_main:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/grdnt"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/welcome_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Welcome"
        android:textColor="#2AF598"
        android:textSize="50dp"
        android:layout_alignParentTop="true"
        android:layout_marginTop="80dp"
        android:gravity="center"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/provide_food"
        android:layout_width="270dp"
        android:layout_height="60dp"
        android:layout_below="@+id/welcome_text"
        android:layout_marginTop="100dp"
        android:layout_marginLeft="80dp"
        android:gravity="center"
        android:text="Do you have Food"
        android:textSize="20dp"
        android:background="@drawable/custombutton"
        />

    <Button
        android:id="@+id/need_food"
        android:layout_width="270dp"
        android:layout_height="60dp"
        android:layout_below="@+id/provide_food"
        android:layout_marginTop="50dp"
        android:layout_marginLeft="80dp"
        android:gravity="center"
        android:text="Do you need Food"
        android:textSize="20dp"
        android:background="@drawable/custombutton"
        />

    <Button
        android:id="@+id/deliver_food"
        android:layout_width="270dp"
        android:layout_height="60dp"
        android:layout_below="@+id/need_food"
        android:layout_marginTop="50dp"
        android:layout_marginLeft="80dp"
        android:gravity="center"
        android:text="Do you want to Deliver Food"
        android:textSize="20dp"
        android:background="@drawable/custombutton"
        />

</RelativeLayout>

MainActivity.java:
package com.example.helping_hands_individual;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    Button provide, need,deliver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        provide = (Button)findViewById(R.id.provide_food);
        need = (Button)findViewById(R.id.need_food);
        deliver = (Button)findViewById(R.id.deliver_food);

        provide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, Provide_food.class);
                startActivity(intent);
            }
        });

    }
}

Note: I am not using any custom toolbar, neither am I using any toolbar, my theme for the application is: NoActionBar

A: There are three ways to get that notification icon depending upon the theme you are using in your Activity.
1. No.ActionBar Theme: If you're not using any ActionBar or toolbar in your activity then you can create a View(ImageView or Button) in your Activity's layout file with Height and Width as same as the notification icon which is around 28dp and then position it at the top right corner of the screen. You can change the background image of the view according to the state you want.
2. Create your own toolbar: You can create your own toolbar and set the menu item in it. While creating the menu item make sure that you select showAsAction="always" this way your icon is always visible. here is a link for the reference
3.ActionBar Theme: If you're using the action bar theme then you can create a menu file with one item like in Option 2 and then override the onCreateOptionsMenu and inflate then inflate your menu in it.

A:   Notification notification  = new Notification.Builder(this)
            .setContentTitle(title)
            .setContentText(text)
            .setSmallIcon(R.drawable.ic_notification)
            .setContentIntent(pIntent)
            .setDefaults(Notification.DEFAULT_SOUND|Notification.DEFAULT_LIGHTS|Notification.DEFAULT_VIBRATE)
            .setAutoCancel(true)
            .build();


text:
Q: adding pause functionality to google speech to text api Hey guys I'm doing a project that requires google speech to text api and I got the code from
 www.androidhive.info/2014/07/android-speech-to-text-tutorial/
But I would like to add some funcgiomalities such as pausing it and adding an icon to go to voice settings
Thanks in advance :)


text:
Q: Remove a row based on two empty columns in python pandas I want to be able to remove rows that are empty in column NymexPlus and NymexMinus
right now the code I have is
df.dropna(subset=['NymexPlus'], inplace=True)

The thing about this code is that it will also delete rows in the column NymexMinus which I don't want to happen.
Is there an If/AND statement that will work in terms of only getting rid of empty cells for both of the columns?

A: Use a list as subset parameter and how='all':
df.dropna(subset=['NymexPlus', 'NymexMinus'], how='all', inplace=True)


text:
Q: How can I fix a 'The resource body includes fields which are not directly writable' warning from Google Drive API? I'm using an example from Google API Docs v3 (This is a live example to see the error). When trying to update a file permission, the following error appears :

The resource body includes fields which are not directly writable.

The file permission needs to be updated to allow access to the URL for anyone, so we can use the 'uploaded' file as a sharing tool. If you remove the 'type' option the script runs. Read other questions regarding this, including this, but not helped solve this issue. Overall, the goal is to make a file the user selects from the google drive picker shareable. Any pointers would be great.
Code below (Same as URL above).
<script src="https://apis.google.com/js/api.js"></script>
<script>
  /**
   * Sample JavaScript code for drive.permissions.update
   * See instructions for running APIs Explorer code samples locally:
   * https://developers.google.com/explorer-help/guides/code_samples#javascript
   */

  function authenticate() {
    return gapi.auth2.getAuthInstance()
        .signIn({scope: "https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.file"})
        .then(function() { console.log("Sign-in successful"); },
              function(err) { console.error("Error signing in", err); });
  }
  function loadClient() {
    return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/drive/v3/rest")
        .then(function() { console.log("GAPI client loaded for API"); },
              function(err) { console.error("Error loading GAPI client for API", err); });
  }
  // Make sure the client is loaded and sign-in is complete before calling this method.
  function execute() {
    return gapi.client.drive.permissions.update({
      "fileId": "xxxxxx",
      "permissionId": "xxxxxx",
      "removeExpiration": false,
      "supportsTeamDrives": true,
      "transferOwnership": true,
      "resource": {
        "type": "anyone",
        "role": "owner"
      }
    })
        .then(function(response) {
                // Handle the results here (response.result has the parsed body).
                console.log("Response", response);
              },
              function(err) { console.error("Execute error", err); });
  }
  gapi.load("client:auth2", function() {
    gapi.auth2.init({client_id: YOUR_CLIENT_ID});
  });
</script>
<button onclick="authenticate().then(loadClient)">authorize and load</button>
<button onclick="execute()">execute</button>

To summarise, I have attempted to update the user role/type with the below, but even though there are no errors, the current fields do not update.
<script src="https://apis.google.com/js/api.js"></script>
<script>
  /**
   * Sample JavaScript code for drive.permissions.list
   * See instructions for running APIs Explorer code samples locally:
   * https://developers.google.com/explorer-help/guides/code_samples#javascript
   */

  function authenticate() {
    return gapi.auth2.getAuthInstance()
        .signIn({scope: "https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/drive.metadata https://www.googleapis.com/auth/drive.metadata.readonly https://www.googleapis.com/auth/drive.photos.readonly https://www.googleapis.com/auth/drive.readonly"})
        .then(function() { console.log("Sign-in successful"); },
              function(err) { console.error("Error signing in", err); });
  }
  function loadClient() {
    return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/drive/v3/rest")
        .then(function() { console.log("GAPI client loaded for API"); },
              function(err) { console.error("Error loading GAPI client for API", err); });
  }
  // Make sure the client is loaded and sign-in is complete before calling this method.

function updatePermission(fileId, permissionId, newRole) {
  var newRole = "owner";
  // First retrieve the permission from the API.
  var request = gapi.client.drive.permissions.get({
    "fileId": "xxxxx",
    'permissionId': "xxxxx",
  });

  request.execute(function(resp) {
    resp.role = newRole;
    var updateRequest = gapi.client.drive.permissions.update({
      'fileId': "xxxxx",
      'permissionId': "xxxxx",
      'resource': resp
    });
    updateRequest.execute(function(resp) {
    });
  });
}

  gapi.load("client:auth2", function() {
    gapi.auth2.init({client_id: "xxx"});
  });
</script>
<button onclick="authenticate().then(loadClient)">authorize and load</button>
<button onclick="updatePermission()">execute</button>

This now runs, but isn't actually updating the information when you check it against this

A: If you check the documentation for permission update post body. You will notice that there are only two fields that are writable

You are trying to update some columns which are not writable.
  "removeExpiration": false,
  "supportsTeamDrives": true,
  "transferOwnership": true,

Try doing:
 /**
 * Update a permission's role.
 *
 * @param {String} fileId ID of the file to update permission for.
 * @param {String} permissionId ID of the permission to update.
 * @param {String} newRole The value "owner", "writer" or "reader".
 */
function updatePermission(fileId, permissionId, newRole) {
  // First retrieve the permission from the API.
  var request = gapi.client.drive.permissions.get({
    'fileId': fileId,
    'permissionId': permissionId
  });
  request.execute(function(resp) {
    resp.role = newRole;
    var updateRequest = gapi.client.drive.permissions.update({
      'fileId': fileId,
      'permissionId': permissionId,
      'resource': resp
    });
    updateRequest.execute(function(resp) { });
  });
}


text:
Q: arduino: loop until int gets value assigned to it
I am trying to get a value from serial input. The rest of the programm behaves different if the value changes. This value gest assigned once in the ```void setup()``` function.
My goal is to let the program run an infinite loop or something similar until a value (type int) is recived, and only then resume the flow.
I know about ```Serial.parseInt()``` and tried to implement it ``` while (variable == null) variable = Serial.parseInt() ``` but I got an error that 'null' was not declared in this scope.
Any suggestions?

A: Oke, i was kinda dumb.
There is an easy way, simply check
while (!variable)
  variable = Serial.parseInt()

This worked for me and should work for you as well


text:
Q: Migrating from TableServiceContext to CloudTable I am migrating my Azure code from using TableServiceContext to CloudTable, due to the following warning (migrating to the latest Azure SDK from an older version)
'Microsoft.WindowsAzure.Storage.Table.DataServices.TableServiceEntity' is obsolete: 'Support for accessing Windows Azure Tables via WCF Data Services is now obsolete. It's recommended that you use the Microsoft.WindowsAzure.Storage.Table namespace for working with tables.'
One of the problems is that in TableServiceContext I used the following
_tableServiceContext.MergeOption = MergeOption.NoTracking;
_tableServiceContext.SaveChangesDefaultOptions =      SaveChangesOptions.ReplaceOnUpdate;
_tableServiceContext.IgnoreResourceNotFoundException = true;
_tableServiceContext.Format.UseAtom();
_tableServiceContext.WritingEntity += JobRepository_WritingEntity;

Whats the equivalent in the new SDK?

A: These properties are specific to the behavior of the ServiceContext, and do not apply to using the CloudTable class.


text:
Q: supported method for transitioning to new object I have a save event set up with my post creation route.
App.PostsNewRoute = Ember.Route.extend({
  model: function(){
    return App.Post.createRecord();
  },
  exit: function() {
    this._super();
    this.get('currentModel.transaction').rollback();
  },
  setupController: function(controller, model){
    controller.set('content', model);
  },
  events: {
    save: function(post){
      post.one('didCreate', this, function(){

        this.transitionTo('posts.show', post);
      });
      post.get('transaction').commit();
    },
    cancel: function(){
      this.transitionTo('posts.index');
    }
  }
});

Here is my post model.
App.Post = DS.Model.extend({
  body: DS.attr('string'),
  headline: DS.attr('string')
});

As you can see, it transitions to the show route after the post is created.  I'm running into an issue where since the id of the post is undefined (it's defined after creation of the object in the database) the transition changes the url to /null .  This seems logical, but obviously not ideal.
What is the best way to transition to the id of the new post?  I return the whole object after it's created (with the ID included).  Seems like Ember doesn't see the new object I'm returning.

A: I was running into this.  https://github.com/emberjs/data/issues/405 Looks like the didCreate event is firing before the object is updated.  The workaround I used was just setting up an observer for the id in question.  Then didCreate would fire, and when the id was updated, my observer fired, and within that observer I did the transition to the show route.


text:
Q: Brunch installed with phoenix app doesn't work with bower assets I have created Phoenix 1.0.4 (Elixir) application. After I had added some logic in application I wanted to switch my work for front-end part. On page http://www.jonathanbirkholz.com/how-to-use-font-awesome-on-phoenix/ I read that for 3rd assets I should use Bower. Unfortunately  with font-awesome or bootstrap-sass from Bower and with command brunch build I always receive:
/.../my_app/node_modules/acorn/dist/acorn.js:1747
  throw err;
  ^

SyntaxError: Unexpected token (2:10)
  at Parser.pp.raise (/.../my_app/node_modules/acorn/dist/acorn.js:1745:13)
  at Parser.pp.unexpected (/.../my_app/node_modules/acorn/dist/acorn.js:2264:8)
  at Parser.pp.semicolon (/.../my_app/node_modules/acorn/dist/acorn.js:2243:59)
  at Parser.pp.parseExpressionStatement (/.../my_app/node_modules/acorn/dist/acorn.js:2677:8)
  at Parser.pp.parseStatement (/.../my_app/node_modules/acorn/dist/acorn.js:2462:160)
  at Parser.pp.parseBlock (/.../my_app/node_modules/acorn/dist/acorn.js:2692:21)
  at Parser.pp.parseStatement (/.../my_app/node_modules/acorn/dist/acorn.js:2443:19)
  at Parser.pp.parseTopLevel (/.../my_app/node_modules/acorn/dist/acorn.js:2379:21)
  at Object.parse (/.../my_app/node_modules/acorn/dist/acorn.js:101:12)
  at parse (/.../my_app/node_modules/detective/index.js:9:18)
  at Function.exports.find (/.../my_app/node_modules/detective/index.js:44:15)
  at module.exports (/.../my_app/node_modules/detective/index.js:23:20)
  at /.../my_app/node_modules/deppack/index.js:83:12
  at tryToString (fs.js:414:3)
  at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:401:12)

I found that problem is caused by acorn - JavaScript library, so I check dependency tree for Node modules:
├─┬ brunch@2.0.4
│ ├─┬ deppack@0.1.5
│ │ └─┬ detective@4.3.1
│ │   ├── acorn@1.2.2

Brunch 2.0.4 (The newest released) use dependencies for old acorn library. There are newer acorn versions, but detective library allows to use acorn 1.x.x versions.z

A: Probably I found what was wrong. Bower must be installed globally and shouldn't exist locally (in node_modules).

A: I had a similar issue.
Try using Node > 5 and NPM 3, clean your cache and install the node_modules again (delete first).


text:
Q: Ordinal Hinge Loss Derivative? According to This paper, the ordinal hinge loss can be defined as follows in (4). I believe that 'a' is the true value and 'u' is the predicted one.
My question is if it is possible to re-write this so that the second derivative of the function with respect to 'u' is not zero?


text:
Q: SwiftUI passing data into ViewModel I am trying to put the data that I am passing into the view into the ViewModel.
I see lots of tutorial about retrieving data from outside sources like Json or Firebase but nothing about using my data passed from the previous page.
I have to do a lot of calculations on the data to get my final output.
here I need to get 'entry' into the ShowViewModel.
struct ShowView: View {

    @ObservedObject var entry:EntryData

    var showVM = ShowViewModel()

    var body: some View {

       Text("\(entrybeg)")

    }
}

I am just playing with a blank ViewModel here for testing.
class ShowViewModel: ObservableObject {

    @Published var test = "something"
    @Published var m:Month = Month()

}

A: You may try the following:
struct ShowView: View {
    @ObservedObject var entry: EntryData

    @ObservedObject var showVM: ShowViewModel // declare only (@ObservedObject optionally)

    init(entry: EntryData) {
        self.entry = entry
        self.showVM = ShowViewModel(entry: entry)
    }

    var body: some View {
        Text("\(entrybeg)")
    }
}

class ShowViewModel: ObservableObject {
    @Published var test = "something"
    @Published var m: Month = Month()

    private var entry: EntryData

    init(entry: EntryData) {
        self.entry = entry
    }
}

Now when you create your view you need to pass EntryData to it:
ShowView(entry: EntryData())

A: SwiftUI doesn't use the View Model pattern, you have to learn something new. SwiftUI uses lightweight data structs (badly named as Views) that are created super fast, tell the system how to create the actual views shown on screen and then are thrown away immediately and if you follow Apple's tutorials they state that the "Views are very cheap, we encourage you to make them your primary encapsulation mechanism" (20:50 Data Essentials) . You can also group related properties into their own custom struct so that a change to any property is detected as a change to the struct itself, this is called value semantics which is a feature of structs you cannot get with objects like view model objects. Define a struct var with @State in parent View and reference it in child view using @Binding passing it in using the $ syntax.  These property wrappers allow the struct to behave like an object reference. SwiftUI does dependency tracking and if any @State or @Binding that is referenced by the body method, body will be called whenever these properties change.
struct ShowViewConfig {
    var test = "something"
    var m:Month = Month()

    // you can even put a method in to update it
    mutating func fetch(name:String, ascending: Bool){
    }
}

Then create it in your ContentView like:
struct ContentView {
    @State var config = ShowViewConfig()
     var body: some View {
          ...
          ShowView(config:$config)

Then use it in your ShowView like:
struct ShowView: View {
    @Binding var config : ShowViewConfig
    var body: some View {
       Text("\(config.test)")
    }
}

You can see this pattern at 8:44 in Data Essentials in SwiftUI WWDC 2020

If you have a model object, i.e. that is being monitored by @ObservableObject then your job is to convert from the rich data types to simple data types in a View struct somewhere in the hierarchy, using formatters if necessary. You can learn more about this in WWDC 2020 Structure your app for SwiftUI previews @ 11:22. So as you can see if you tried to do this in a View Model object instead of the View structs then that is the wrong approach.

It's also fine to use @ObservableObject for a loader or fetcher (20:14 Data Essentials).

A: I'm assuming here, that you have a class which has done a calculation. Furthermore, that calculation its result is required for the ShowViewModel. I'd do something as follows:
class EntryData: ObservableObject {
    @Published var calculation = 42
}

struct ShowView: View {
    @ObservedObject var showVM: ShowViewModel

    var body: some View {
        Text("\(showVM.m.daysRequired)")
    }

    init(entryData: EntryData) {
        let month = ShowViewModel.Month(daysRequired: entryData.calculation)
        self.showVM = ShowViewModel(month: month)
    }
}

class ShowViewModel: ObservableObject {
    struct Month {
        let daysRequired: Int
    }

    @Published var test = "something"
    @Published var m: Month

    init(month: Month) {
        self.m = month
    }
}

struct ContentView: View {
    var body: some View {
        ShowView(entryData: EntryData())
    }
}


text:
Q: spring mvc hibernate performance issues We are working on a spring mvc project with hibernate.
When we execute the following code:
try {
    HibernateTemplate ht = new HibernateTemplate(sf);
    List<Route> r = ht.findByNamedParam("select r from Route r inner join r.carPoolers as carPooler where (( r.owner.id  = :userid ) or ( carPooler.user.id = :userid )) AND r.id =:routeID", new String[]{"userid", "routeID"} , new Object[]{ u.getId() , id});
    if (r.size() == 1) {
        return r.get(0);
    } else {
        return null;
    }
} catch (DataAccessException ex) {
    LogFactory.getLog(RouteRepository.class).fatal(ex);
    return null;
}

this is the result:
SELECT ROUTE0_.ID AS ID4_, ROUTE0_.ARRIVALTIME AS ARRIVALT2_4_,
    ROUTE0_.CAR_ID AS CAR13_4_, ROUTE0_.DATE AS DATE4_,
    ROUTE0_.DAYOFWEEK AS DAYOFWEEK4_, ROUTE0_.DEPARTURETIME AS
    DEPARTUR5_4_, ROUTE0_.ENDDATE AS ENDDATE4_, ROUTE0_.MESSAGEID
    AS MESSAGEID4_, ROUTE0_.OPENSEATS AS OPENSEATS4_,
    ROUTE0_.OWNER_ID AS OWNER14_4_, ROUTE0_.ROUTECACHE_ID AS
    ROUTECACHE11_4_, ROUTE0_.ROUTEOPTIMIZED AS ROUTEOPT9_4_,
    ROUTE0_.START_ID AS START12_4_, ROUTE0_.STOP_ID AS STOP10_4_
FROM ROUTE ROUTE0_ INNER JOIN CARPOOLER CARPOOLERS1_ ON
    ROUTE0_.ID=CARPOOLERS1_.ROUTEID
WHERE (route0_.owner_id=? or carpoolers1_.user_id=?) and route0_.id=?

    SELECT CAR0_.ID AS ID5_3_, CAR0_.BRAND_ID AS BRAND8_5_3_, CAR0_.CARNAME
        AS CARNAME5_3_, CAR0_.CARTYPE AS CARTYPE5_3_, CAR0_.IMAGEURL AS
        IMAGEURL5_3_, CAR0_.PRICEKM AS PRICEKM5_3_, CAR0_.SEATS AS
        SEATS5_3_, CAR0_.USER_ID AS USER7_5_3_, BRAND1_.ID AS ID6_0_,
        BRAND1_.BRANDNAME AS BRANDNAME6_0_, USER2_.ID AS ID0_1_,
        USER2_.EMAIL AS EMAIL0_1_, USER2_.FACEBOOKID AS FACEBOOKID0_1_,
        USER2_.FIRSTNAME AS FIRSTNAME0_1_, USER2_.GENDER AS GENDER0_1_,
        USER2_.IMAGEURL AS IMAGEURL0_1_, USER2_.LANGUAGE_ID AS
        LANGUAGE12_0_1_, USER2_.LASTNAME AS LASTNAME0_1_,
        USER2_.MOBILEPHONE AS MOBILEPH8_0_1_, USER2_.PASSWORD AS
        PASSWORD0_1_, USER2_.SMOKER AS SMOKER0_1_, USER2_.TELEPHONE AS
        TELEPHONE0_1_, LANGUAGE3_.ID AS ID9_2_, LANGUAGE3_.LANGUAGE AS
        LANGUAGE9_2_, LANGUAGE3_.LANGUAGECODE AS LANGUAGE3_9_2_
    FROM CAR CAR0_ LEFT OUTER JOIN BRAND BRAND1_ ON
        CAR0_.BRAND_ID=BRAND1_.ID LEFT OUTER JOIN USER USER2_ ON
        CAR0_.USER_ID=USER2_.ID LEFT OUTER JOIN LANGUAGE LANGUAGE3_ ON
        USER2_.LANGUAGE_ID=LANGUAGE3_.ID
    WHERE car0_.id=?

    SELECT USER0_.ID AS ID0_1_, USER0_.EMAIL AS EMAIL0_1_,
        USER0_.FACEBOOKID AS FACEBOOKID0_1_, USER0_.FIRSTNAME AS
        FIRSTNAME0_1_, USER0_.GENDER AS GENDER0_1_, USER0_.IMAGEURL AS
        IMAGEURL0_1_, USER0_.LANGUAGE_ID AS LANGUAGE12_0_1_,
        USER0_.LASTNAME AS LASTNAME0_1_, USER0_.MOBILEPHONE AS
        MOBILEPH8_0_1_, USER0_.PASSWORD AS PASSWORD0_1_, USER0_.SMOKER
        AS SMOKER0_1_, USER0_.TELEPHONE AS TELEPHONE0_1_, LANGUAGE1_.ID
        AS ID9_0_, LANGUAGE1_.LANGUAGE AS LANGUAGE9_0_,
        LANGUAGE1_.LANGUAGECODE AS LANGUAGE3_9_0_
    FROM USER USER0_ LEFT OUTER JOIN LANGUAGE LANGUAGE1_ ON
        USER0_.LANGUAGE_ID=LANGUAGE1_.ID
    WHERE user0_.id=?

    SELECT ROUTECACHE0_.ID AS ID7_2_, ROUTECACHE0_.AANTALM AS AANTALM7_2_,
        ROUTECACHE0_.AANTALMIN AS AANTALMIN7_2_, ROUTECACHE0_.ACTIVE AS
        ACTIVE7_2_, ROUTECACHE0_.JSON AS JSON7_2_,
        ROUTECACHE0_.LOCATIONS AS LOCATIONS7_2_,
        ROUTECACHE0_.LOCATIONSOPTIMIZED AS LOCATION7_7_2_,
        ROUTECACHE0_.ROUTEOPTIMIZED AS ROUTEOPT8_7_2_,
        ROUTECACHE0_.START_ID AS START10_7_2_, ROUTECACHE0_.STOP_ID AS
        STOP9_7_2_, LOCATION1_.ID AS ID2_0_, LOCATION1_.LANG AS
        LANG2_0_, LOCATION1_.LAT AS LAT2_0_, LOCATION1_.NUMBER AS
        NUMBER2_0_, LOCATION1_.STREET AS STREET2_0_, LOCATION1_.ZIPCODE
        AS ZIPCODE2_0_, LOCATION2_.ID AS ID2_1_, LOCATION2_.LANG AS
        LANG2_1_, LOCATION2_.LAT AS LAT2_1_, LOCATION2_.NUMBER AS
        NUMBER2_1_, LOCATION2_.STREET AS STREET2_1_, LOCATION2_.ZIPCODE
        AS ZIPCODE2_1_
    FROM ROUTECACHE ROUTECACHE0_ LEFT OUTER JOIN LOCATION LOCATION1_ ON
        ROUTECACHE0_.START_ID=LOCATION1_.ID LEFT OUTER JOIN LOCATION
        LOCATION2_ ON ROUTECACHE0_.STOP_ID=LOCATION2_.ID
    WHERE routecache0_.id=?

     SELECT ROUTECACHE0_.ROUTECACHESPUNTENTUSSEN_ID AS ROUTECAC1_1_,
        ROUTECACHE0_.ROUTECACHETUSSENPUNTEN_ID AS ROUTECAC2_1_,
        LOCATION1_.ID AS ID2_0_, LOCATION1_.LANG AS LANG2_0_,
        LOCATION1_.LAT AS LAT2_0_, LOCATION1_.NUMBER AS NUMBER2_0_,
        LOCATION1_.STREET AS STREET2_0_, LOCATION1_.ZIPCODE AS
        ZIPCODE2_0_
    FROM ROUTECACHE_LOCATION_PUNTEN ROUTECACHE0_ LEFT OUTER JOIN LOCATION
        LOCATION1_ ON
        ROUTECACHE0_.ROUTECACHETUSSENPUNTEN_ID=LOCATION1_.ID
    WHERE routecache0_.routecachesPuntenTussen_id=?

     SELECT CARPOOLERS0_.ROUTEID AS ROUTEID5_, CARPOOLERS0_.ID AS ID5_,
        CARPOOLERS0_.ID AS ID3_4_, CARPOOLERS0_.APPROVED AS
        APPROVED3_4_, CARPOOLERS0_.ONETIME AS ONETIME3_4_,
        CARPOOLERS0_.ROUTEID AS ROUTEID3_4_, CARPOOLERS0_.START_ID AS
        START5_3_4_, CARPOOLERS0_.STOP_ID AS STOP7_3_4_,
        CARPOOLERS0_.USER_ID AS USER6_3_4_, LOCATION1_.ID AS ID2_0_,
        LOCATION1_.LANG AS LANG2_0_, LOCATION1_.LAT AS LAT2_0_,
        LOCATION1_.NUMBER AS NUMBER2_0_, LOCATION1_.STREET AS
        STREET2_0_, LOCATION1_.ZIPCODE AS ZIPCODE2_0_, LOCATION2_.ID AS
        ID2_1_, LOCATION2_.LANG AS LANG2_1_, LOCATION2_.LAT AS LAT2_1_,
        LOCATION2_.NUMBER AS NUMBER2_1_, LOCATION2_.STREET AS
        STREET2_1_, LOCATION2_.ZIPCODE AS ZIPCODE2_1_, USER3_.ID AS
        ID0_2_, USER3_.EMAIL AS EMAIL0_2_, USER3_.FACEBOOKID AS
        FACEBOOKID0_2_, USER3_.FIRSTNAME AS FIRSTNAME0_2_,
        USER3_.GENDER AS GENDER0_2_, USER3_.IMAGEURL AS IMAGEURL0_2_,
        USER3_.LANGUAGE_ID AS LANGUAGE12_0_2_, USER3_.LASTNAME AS
        LASTNAME0_2_, USER3_.MOBILEPHONE AS MOBILEPH8_0_2_,
        USER3_.PASSWORD AS PASSWORD0_2_, USER3_.SMOKER AS SMOKER0_2_,
        USER3_.TELEPHONE AS TELEPHONE0_2_, LANGUAGE4_.ID AS ID9_3_,
        LANGUAGE4_.LANGUAGE AS LANGUAGE9_3_, LANGUAGE4_.LANGUAGECODE AS
        LANGUAGE3_9_3_
    FROM CARPOOLER CARPOOLERS0_ LEFT OUTER JOIN LOCATION LOCATION1_ ON
        CARPOOLERS0_.START_ID=LOCATION1_.ID LEFT OUTER JOIN LOCATION
        LOCATION2_ ON CARPOOLERS0_.STOP_ID=LOCATION2_.ID LEFT OUTER
        JOIN USER USER3_ ON CARPOOLERS0_.USER_ID=USER3_.ID LEFT OUTER
        JOIN LANGUAGE LANGUAGE4_ ON USER3_.LANGUAGE_ID=LANGUAGE4_.ID
    WHERE carpoolers0_.RouteId=?

Problem:

*

*This takes minimum 460ms.

*We only need the first query for our results.

,
ty in advance

A: You probably have so many queries because some relationships are eager loaded. Note that by default all OneToOne and ManyToOne relationships are eager loaded. This means that if a route has a car, which has a user, which has a language, etc., Hibernate will load all these referenced entities each time it loads a route.
Make them lazy loaded instead, and tune your queries to fetch only the entities you need.

A: I guess returned object is passed to some automatic serializer (you use @ResponseBody, yes?) that tries to serialize the whole graph of accessible objects and therefore triggers lazy loading of related objects which you don't need.
If so, you can create a DTO that contains only necessary fields, populate it from the loaded entity and return that DTO instead of entity.
Alternative approach would be to configure serializer to make it serialize only necessary fields, but it can be more complex.

A: See this for how to get only 1 result: How do you do a limit query in HQL?.
Have you configured indexes on your tables?


text:
Q: Inconsistent Time in Oracle Explain Plan I have following query with its EXPLAIN PLAN shown below.
The query take 2.3 seconds.
But EXPLAIN PLAN shows INDEX FAST FULL SCAN show Time = 00:10:06 seconds
Any reason why ?
select count(*) from c1
COUNT(*)
----------
  68656440

Elapsed: 00:00:02.31

Execution Plan
----------------------------------------------------------
Plan hash value: 2610173813

-------------------------------------------------------------------------
| Id  | Operation             | Name    | Rows  | Cost (%CPU)| Time     |
-------------------------------------------------------------------------
|   0 | SELECT STATEMENT      |         |     1 | 50450   (1)| 00:10:06 |
|   1 |  SORT AGGREGATE       |         |     1 |            |          |
|   2 |   INDEX FAST FULL SCAN| PF_TEST |    83M| 50450   (1)| 00:10:06 |
-------------------------------------------------------------------------

Note
-----

- dynamic sampling used for this statement (level=2)
Statistics

      0  recursive calls
      0  db block gets
 185865  consistent gets
 185820  physical reads
      0  redo size
    529  bytes sent via SQL*Net to client
    523  bytes received via SQL*Net from client
      2  SQL*Net roundtrips to/from client
      0  sorts (memory)
      0  sorts (disk)
      1  rows processed

A: explain plan is an estimate of what oracle think it will take to execute the statement, try this:
set timi on
select count(*) from c1;
set timi off

select * from table(dbms_xplan.display_cursor(null,null,'allstats last'));

Then look at the A-time column, is it accurate?
It should be.


text:
Q: ¿Por qué no se ven choices desde models.py en el template? una duda, ¿ustedes saben como pasar las opciones de un select desde forms.py?
Resulta que hice un modelo en la app de clientes, luego lo pasé al form de la app de clientes, lo heredé en otro form de una app que se llama presupuestos, y al presentarlo en el template sólo se ve el campo vacío sin las opciones

models.py (de la app de clientes)

class Clientes(models.Model):
    TITLE=(
        ('Mrs.','Mrs.'),
        ('Miss','Miss'),
        ('Mr.','Mr.'),
    )
    titulo=models.CharField(max_length=200, null=True,choices=TITLE)
    nombre =models.CharField(max_length=80)

    def __str__(self):
        return f'{self.id}:{self.titulo}{self.nombre}'

forms.py (de la app de clientes)

class ClientesForm(forms.ModelForm):
    class Meta:
        model=Clientes
        fields=['titulo','nombre']

forms.py (de la app de presupuesto que hereda de forms.py de la app de clientes)

class PresupuestosClientesForm(forms.ModelForm):
    class Meta:
        model = Clientes
        fields = '__all__'
        widgets = {
            'titulo': forms.TextInput(
                attrs={
                    'class': 'form-select'
                }
            ),
            'nombre': forms.TextInput(
                attrs={
                    'class': 'form-control'
                }
            ),
         }

en el template presupuestos-form.html donde no se ven las opciones reflejadas

<label for="titulo" id="titulo">Título</label>
{{presupuestosclientesform.titulo}}
<select class="form-select">
           <option>Elige</option>
           <option>Mrs.</option>
           <option>Miss</option>
           <option>Mr.</option>
</select>

views.py (de la app de clientes)

def create_Clientes(request):
    form=ClientesForm(request.POST or None)
    if form.is_valid():
        form.save()
        return redirect('clientes:index')
    return render(request,'clientes/clientes-form.html',{'form':form})

views.py (de la app de presupuestos)

def create_Presupuestos(request):
    presupuestosclientesform=PresupuestosClientesForm(request.POST or None)
    presupuestosvehiculosform=PresupuestosVehiculosForm(request.POST or None)
    presupuestosparteform=PresupuestosParteForm(request.POST or None)
    presupuestosmanoobraform=PresupuestosManoObraForm(request.POST or None)
    presupuestospagosform=PresupuestosPagosForm(request.POST or None)

    if presupuestosclientesform.is_valid():
        presupuestosclientesform.save()
        return redirect('presupuestos:index')
    return render(request,'Presupuestos/presupuestos-forms.html',{'presupuestosclientesform':presupuestosclientesform,'presupuestosvehiculosform':presupuestosvehiculosform, 'presupuestosparteform':presupuestosparteform, 'presupuestosmanoobraform':presupuestosmanoobraform,'presupuestospagosform':presupuestospagosform})


text:
Q: How to display username on navbar after login in react redux There is a nav link on my navbar named Login (I have used bootstrap navbar). After successful login I want to replace Login with a username using react-redux (not redux-toolkit).
Kindly help me in writing reducer and action code. As I am a beginner in redux and I don't know how to code in reducer and action file it is very confusing for me.
Navbar component (Navbar.js)
import React from 'react';
import { Link } from 'react-router-dom';
import { useSelector } from 'react-redux';

const Navbar = () => {
const {username} = useSelector((state) => state.user);
    return (

                    <Link className="navbar-brand" to="/hommepage">Ebuy</Link>
                    <button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-                        expanded="false" aria-label="Toggle navigation">

                    </button>

                                <Link className="nav-link" aria-current="page" to="/homepage">Home</Link>

                                <Link className="nav-link dropdown-toggle" to="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                                Select Category
                                </Link>

<Link className="dropdown-item" to="/skincare">Skincare Products</Link>

<Link className="dropdown-item" to="/stationary">Stationary Products</Link>

<Link className="dropdown-item" to="#">Clothing</Link>

                                    <Link className="nav-link" to="/">Login</Link>

    );
};

export default Navbar;

A: In your Navbar Component you should get username from redux, please try this :

const {username} = useSelector(state=> state.yourReducerName)

after this, in your jsx : you should write a condition like this :

{username ? (
{username}
): ()Login}

EDIT :
Please refer to this sandbox example and take a look on the reducer and actions files, also on the navbar components.
Let us know if the post helped you :)

A: reducer
const initialState = {
  username: null,
}

export  const userReducer(state = initialState, action) {
  switch (action.type) {
    case "CHANGE_USERNAME":
      return {
        ...state,
        username: action.payload,
      }
    default:
      return state
  }
}

action
export const changeUserName = (name) => {
 return {
  type: "CHANGE_USERNAME",
  payload: name
 }
}

after login call this

const dispatch = useDispatch()

const login = () => {
 ... login logic here

 dispatch(changeUserName("user-1"))

}

in navbar
const { username } = useSelector(state=> state.user)


text:
Q: Solving equation with 1 variable in Python Have here the following equation:
R = ρ * (l/A)
Need to solve it entering the inputs I have.
For example, if I enter R, ρ and l, it would return me the A.
If I enter ρ, l and A, it would return me R value.
If I enter R, l and A, it would return me ρ value.
Any idea on how could I do that in Python?
If I enter R, ρ and A, it would return me l value.

A: I suppose you should write a function with optional params like this:
def get_result(r=None, ro=None, i=None, a=None):
  if r is None: return ro * i / a
  if ro is None: return r / i * a
  if i is None: return r / ro * a
  if a is None: return ro * i / r
  return None

a1 = get_result(r=10,ro=20,i=30)
print(a1)
r1 = get_result(ro=20,i=30,a=40)
print(r1)
...

A: Maybe you could try:
comprim = input(f'Comprimento: ')

resist = input(f'Resistência: ')

resistiv = input(f'Resistividade: ')

area = input('Área: ')

if float(comprim) == 0:

    comprim = (float(area) * float(resist)) / float(resistiv)

    print(comprim)

if float(resist) == 0:

    resist = (float(resistiv) * float(comprim)) / float(area)

    print(resist)

if float(resistiv) == 0:

    resistiv = (float(resist) * float(area)) / float(comprim)

    print(resistiv)

if float(area) == 0:

    area = (float(resistiv) * float(comprim)) / float(resist)

    print(area)


text:
Q: How make a click on a chromium browser link open in the default browser? I want to achieve that when a user clicks on a hyperlink inside a TChromium browser page, the new page opens in his default browser.

A: In the OnBeforeBrowse event check if the navType parameter equals to NAVTYPE_LINKCLICKED and if so, return True to the Result parameter (which will cancel the request for Chromium) and call e.g. ShellExecute passing the request.Url value to open the link in the user's default browser:
uses
  ShellAPI, ceflib;

procedure TForm1.Chromium1BeforeBrowse(Sender: TObject;
  const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest;
  navType: TCefHandlerNavtype; isRedirect: boolean; out Result: Boolean);
begin
  if navType = NAVTYPE_LINKCLICKED then
  begin
    Result := True;
    ShellExecuteW(0, nil, PWideChar(request.Url), nil, nil, SW_SHOWNORMAL);
  end;
end;

A: In CEF3, navType = NAVTYPE_LINKCLICKED is no longer possible in the OnBeforeBrowse event, as in TLama's answer. Instead, I discovered how to detect this using the TransitionType property...
procedure TfrmEditor.BrowserBeforeBrowse(Sender: TObject;
  const browser: ICefBrowser; const frame: ICefFrame;
  const request: ICefRequest; isRedirect: Boolean; out Result: Boolean);
begin
  case Request.TransitionType of
    TT_LINK: begin
      // User clicked on link, launch URL...
      ShellExecuteW(0, nil, PWideChar(Request.Url), nil, nil, SW_SHOWNORMAL);
      Result:= True;
    end;
    TT_EXPLICIT: begin
      // Source is some other "explicit" navigation action such as creating a new
      // browser or using the LoadURL function. This is also the default value
      // for navigations where the actual type is unknown. Do nothing.
    end;
  end;
end;


text:
Q: What is the fastest way to send vector> from one process created in x86 platform to another process built in x64 I have two processes p1 and p2.
p1 is built in x86 and p2 is built in x64 platform using (Visual Studio 2013/MFC/C++)
p1 calculates result and holds it in
std::vector<std::vector<double>> data.
and I want this data to be transfered from p1 to p2's  std::vector<std::vector<double>> data in a way as fast as possible.
I have used boost::archive::text_iarchive to write it to text file. As it is cross platform compatible, I can read it using boost::archive::text_oarchive in p2. But it takes too much time as it involves disk reading and writing. So I need better way to do this job.
Kindly suggest me some faster way for cross platform data transfer. I will be highly thankful if someone could provide me some code also.

A: As others already mentioned, the fastest and straight forward way would be to use shared memory. Below is an example of how that would look like for Posix systems.
The server creates a shared memory object and serializes the vector into the memory by writing each sub vector as length plus items.
The receiver opens the shared memory object and deserializes the memory into a vector of vector object again.
Sender:
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>

#include <vector>
#include <algorithm>

static const std::vector<std::vector<double>> vec = {
  { 1.0, 1.1, 1.2 },
  { 2.0, 2.1 },
  { 3.0, 3.1, 3.2, 3.3 },
};

int main(int argc, char *const argv[])
{
  uint64_t vecsSize = 0;
  for (const auto& v : vec) {
    vecsSize += sizeof(double) * v.size() + sizeof(uint64_t);
  }

  // create a file of size 'vecsSize'
  int fd = open("VEC", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
  lseek(fd, vecsSize - 1, SEEK_SET);
  write(fd, "", 1);
  lseek(fd, 0, SEEK_SET);

  // memory map the file into the process and copy the data into it
  uint8_t* ptrFile = reinterpret_cast<uint8_t*>(mmap(0, vecsSize, PROT_WRITE, MAP_SHARED, fd, 0));
  uint8_t* ptr = ptrFile;
  for (const auto& v : vec)
  {
    reinterpret_cast<uint64_t*>(ptr)[0] = v.size();
    ptr += sizeof(uint64_t);

    std::copy(v.begin(), v.end(), reinterpret_cast<double*>(ptr));
    ptr += sizeof(double) * v.size();
  }

  munmap(ptrFile, vecsSize);
  close(fd);
  return 0;
}

Receiver:
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>

#include <iostream>
#include <vector>
#include <algorithm>

template<class T>
inline std::ostream& operator<< (std::ostream& o, std::vector<T> const& v) {
  for (auto const& i : v)
    o << i << " ";
  o << std::endl;
  return o;
}

static std::vector<std::vector<double>> vec;

int main(int argc, char *const argv[])
{
  int fd = open("VEC", O_RDONLY, S_IRUSR | S_IWUSR);

  struct stat fileStat = { 0 };
  fstat(fd, &fileStat);

  uint64_t vecsSize = static_cast<uint64_t>(fileStat.st_size);
  uint8_t* ptrFile = reinterpret_cast<uint8_t*>(mmap(0, vecsSize, PROT_READ, MAP_SHARED, fd, 0));

  uint8_t* ptr = ptrFile;
  while (ptr < ptrFile + vecsSize)
  {
    uint64_t vecSize = reinterpret_cast<uint64_t*>(ptr)[0];
    ptr += sizeof(uint64_t);

    std::vector<double> v(
      reinterpret_cast<double*>(ptr),
      reinterpret_cast<double*>(ptr) + vecSize);
    ptr += sizeof(double) * vecSize;

    vec.emplace_back(v);
  }

  munmap(ptrFile, vecsSize);
  close(fd);

  std::cout << vec;
  return 0;
}


text:
Q: How to change image after clicking on it? I have made scroll to bottom link on my image. It's a image of arrow pointing down. When you first visit site image of arrow is at bottom of page pointing down and when click on it it scrolls to bottom and ends up on top of page. Have can I implement that when arrow image is on top of page that it changes to image of arrow pointing up?
I have used this code to implement image and functionality of scrolling down.
.html

Supposed to replace it with src="https://blog.com/hubfs/Icon/arrowup.png">  and also add functionality when image changes to click on it and scroll to top
.js
 $(function() {
    $('.scroll-down').click (function() {
      $('html, body').animate({scrollTop: $('div.me').offset().top }, 'fast');
      return false;
    });
});

A:     $(function () {
        var clickedImg = false;
        var imageElement = $('#img_button');

        $('.scroll-down').click(function () {
            $("html, body").animate({ scrollTop: 0 }, 600);
            clickedImg = !clickedImg;
            if (clickedImg) {
                imageElement.attr("src", 'arrow_down.png');
            } else {
                imageElement.attr("src", 'arrow_up.png');
            }
            return false;
        });
    });

With variable clickedImg we know when the image is clicked or not. If it is clicked, the arrow is down, if not, the arrow is up (in my example).
With this: clickedImg = ! clickedImg; we are toggling the value of the variable.
Edit 1:
I edited the above code to make it full jQuery.
Edit 2:
here is a plunkr
Edit 3:
I belive this part of your code is not working:
$('html, body').animate({scrollTop: $('div.me').offset().top}, 'fast');

Because $('div.me') is undefined. Make sure that that element exists. If you comment this line, the code works. Fix that animate and you are set to go. Use my plunkr if it makes it easier for you. ;)


text:
Q: How to authenticate user using Twitter mobile app I'm currently authenticating user with Twitter using oauth flow inside a webView from the iOS app. However, I would like to authenticate user redirecting him to the native Twitter app if it is installed on the device.
The thing is that Twitter's documentation doesn't mention anything like that. Only the oauth flow I'm currently using.
So my question here is how to do that? I know some apps are doing that (e.g. Clubhouse), but have no idea how to do that since the official TwitterKit SDK is deprecated for a while now.


text:
Q: PHP Array of Some Kind I come across that array-looking object in a php file. Any clue what it is and how it works?
a:1:{i:2;a:2:{i:0;s:1:"m";i:1;s:10:"2013-02-11";}}

A: What you have is a serialized string. Run it through unserialize to convert it into a usable format.
Replace $string in the example below.
$unserialized = unserialize( $string );


text:
Q: How to search for specific char in an array and how to then manipulate that index in c# Okay, so I'm creating a hangman game and everything functions so far, including what I'm TRYING to do in the question.
But it feels like there is a much more efficient method of obtaining the char that is also easier to manipulate the index.
protected static void alphabetSelector(string activeWordAlphabet)
    {
        char[] activeWord = activeWordAlphabet.ToCharArray();

        string activeWordString = new string(activeWord);
        Console.WriteLine("If you'd like to guess a letter, enter the letter. \n
        If you'd like to guess the word, please type in the word. --- testing answer{0}",
        activeWordString);

        //Console.WriteLine("For Testing Purposes ONLY");
        String chosenLetter = Console.ReadLine();
        //Char[] letterFinder = Array.FindAll(activeWord, s => s.Equals(chosenLetter));
        //string activeWordString = new string(activeWord);

        foreach (char letter in activeWord);
        {
            if(activeWordString.Contains(chosenLetter))
            {
                Console.WriteLine("{0}", activeWordString);
                Console.ReadLine();

            }

            else
            {
                Console.WriteLine("errrr...wrong!");
                Console.ReadLine();

            }

        }

    }

I have broken up the code in some areas to prevent the reader from having to scroll sideways. If this is bothersome, please let me know and I'll leave it in the future.
So this code will successfully print out the 'word' whenever I select the correct letter from the random word (I have the console print the actual word so that I can test it successfully each time). It will also print 'wrong' when I choose a letter NOT in the string.
But I feel like I should be able to use the
    Array.FindAll(activeWord, ...)
functionality or some other way. But every time I try and reorder the arguments, it gives me all kinds of different errors and tells me to redo my arguments.
So, if you can look at this and find an easier method of searching the actual array for the user-selected 'letter', please help!! Even if it's not using the Array.FindAll method!!
Edit
Okay, it seems like there's some confusion with what I've done and why I've done it.
I'm ONLY printing the word inside that 'if' statement to test and make sure that the foreach{if{}} will actually work to find the char inside the string. But I ultimately need to be able to provide a placeholder for a char that is successfully found, as well as being able to 'cross out' the letter (from the alphabet list not shown here).
It's hangman - surely you guys know what I'm needing it to do. It has to keep track of which letters are left in the word, which letters have been chosen, as well as which letters are left in the entire alphabet.
I'm a 4-day old newb when it comes to programming, so please. . . I'm only doing what I know to do and when I get errors, I comment things out and write more until I find something that works.

A: Ok your code is really confusing, even with your edit.
First, why these 2 lines of code since activeWordAlphabet is a string :
char[] activeWord = activeWordAlphabet.ToCharArray();

string activeWordString = new string(activeWord);

Then you do your foreach.
For the word "FooBar", if the player types 'F', you will print
    FooBar
    FooBar
    FooBar
    FooBar
    FooBar
    FooBar
How does this help you in anything?
I think you have to review your algorithm. The string type have the function you need
int chosenLetterPosition = activeWord.IndexOf(chosenLetter, alreadyFoundPosition)

alreadyFoundPosition is an int from where the function will search the letter
IndexOf() returns -1 if the letter is not find or a positive number.
You can save this position with your letter in a dictionary to use it again as your new 'alreadyFoundPosition' if the chosenLetter is already in the dictionary

A: Take a look at this demo I put together for you: https://dotnetfiddle.net/eP9TQM
I'd suggest creating a second string for the display string. Use a StringBuilder, and you can replace the characters in it at specific indices while creating the fewest number of stringobjects in the process.
string word = "your word or phrase here";

//Initialize a new StringBuilder that will display the word with placeholders.
StringBuilder display = new StringBuilder(word.Length); //You know the display word is the same length as the original word
display.Append('-', word.Length); //Fill it with placeholders.

So now you have your phrase/word, and a string builder full of characters that need to be discovered.
Go ahead and convert the display StringBuilder to a string that you can check on each pass to see if it equals your word:
var displayString = display.ToString();

//Loop until the display string is equal to the word
while (!displayString.Equals(word))
{
    //Inside here your logic will follow.
}

So you are basically looping until the person answers here. You could of course go back and add logic to limit the number of attempts, or whatever you desire as an alternate exit strategy.
Inside this logic, you will check if they guessed a letter or a word based on how many characters they entered.
If they guessed a word, the logic is simple. Check if the guessed word is the same as the hidden word. If it is, then you break the loop and they are done. Otherwise, guessing loops back around.
If they guessed a letter, the logic is pretty straightforward, but more involved.
First get the character they guessed, just because it may be easier to work with this way.
char guess = input[0];

Now, look over the word for instances of that character:
//Look for instances of the character in the word.
for (int i = 0; i < word.Length; ++i)
{
    //If the current index in the word matches their guess, then update the display.
    if (char.ToUpperInvariant(word[i]) == char.ToUpperInvariant(guess))
        display[i] = word[i];
}

The comments above should explain the idea here.
Update your displayString at the bottom of the loop so that it will check against the hidden word again:
displayString = display.ToString();

That's really all you need to do here. No fancy Linq needed.

A: This is my answer. Because I don't have a lot of tasks today :)
class Letter
{
    public bool ischosen { get; set; }
    public char value { get; set; }
}

class LetterList
{
    public LetterList(string word)
    {
        _lst = new List<Letter>();
        word.ToList().ForEach(x => _lst.Add(new Letter() { value = x }));
    }

    public bool FindLetter(char letter)
    {
        var search = _lst.Where(x => x.value == letter).ToList();
        search.ForEach(x=>x.ischosen=true);
        return search.Count > 0 ? true : false;
    }

    public string NotChosen()
    {
        var res = "";
        _lst.Where(x => !x.ischosen).ToList().ForEach(x => { res += x.value; });
        return res;
    }

    List<Letter> _lst;

}

How to use
var abc = new LetterList("abcdefghijklmnopqrstuvwxyz");
var answer = new LetterList("myanswer");
Console.WriteLine("This my question. Why? write your answer please");
char x = Console.ReadLine()[0];
if (answer.FindLetter(x))
{
    Console.WriteLine("you are right!");
}
else
{
    Console.WriteLine("fail");
}
abc.FindLetter(x);

Console.WriteLine("not chosen abc:{0} answer:{1}", abc.NotChosen(), answer.NotChosen());

At least we used to play this game like that when i was a child.


text:
Q: Run bash script against 2 text files as variables I need to run the following command in a bash script or any script for that matter:
$ aws rds download-db-log-file-portion --db-instance-identifier $LIST1 --log-file-name $LIST2 --region us-west-2

I have a text file with all the hostnames $LIST1 and another file with all the log files names $LIST2.
Basically I would like to know the best way to take each entry from $LIST1 and download all the logs for that entry from $LIST2.
$LIST1 sample:
host1

host2

host3

$LIST2 sample:
error/mysql-error.log

error/mysql-error.log.0

error/mysql-error.log.1

Example of a regular run of the command:
$ aws rds download-db-log-file-portion --db-instance-identifier host1 --log-file-name error/mysql-error.log--region us-west-2

The problem is I have 100+ hosts and each host has about 90 logs.

A: Here is a bash solution:
while read -r host
do
  while read -r logfile
  do
    aws rds download-db-log-file-portion --db-instance-identifier $host --log-file-name $logfile --region us-west-2
  done < logfiles.txt
done < hosts.txt


text:
Q: Using a specific version of Buffer in Webpack My project depends on buffer ^4.0.0, but Webpack (through node-libs-browser) uses ^3.0.0. Updating the buffer dependency in node-libs-browser breaks crypto-browserify, so a PR would be require a lot more effort. What is the best way of overriding this module provided by node-libs-browser?
I attempted to use the resolve.alias configuration option with no success whatsoever. I installed the latest buffer as a project dependency, and I attempted the following:
resolve: {
  alias: {
    buffer: path.join(__dirname, 'node_modules/buffer')
  }
}

I also tried using 'buffer$', 'Buffer$', and Buffer for the key, and this had no effect (didn't want to leave anything up to chance). I even tried ResolverPlugin and ProvidePlugin, but had no success.
My project still ends up using node-libs-browser's Buffer, and I'm struggling to understand why.


text:
Q: Internal server error 500 crashes server laravel Every time there is 500 error server cpu gets 100% and crashes needs to restart every time
PHP Version 7.4
Laravel Version 8.83
Ubuntu Ngnix

I found this in php7.4-fpm.log error logs
[13-Sep-2022 08:13:16] WARNING: [pool www] server reached pm.max_children setting (5), consider raising it
[13-Sep-2022 08:19:05] NOTICE: Terminating ...
[13-Sep-2022 08:19:05] NOTICE: exiting, bye-bye!

error.log
2022/09/13 10:52:53 [error] 889#889: *3130 upstream timed out (110: Connection timed out) while reading response header from upstream
2022/09/13 11:09:41 [crit] 889#889: *148 SSL_do_handshake() failed (SSL: error:141CF06C:SSL routines:tls_parse_ctos_key_share:bad key share) while SSL handshaking

Does anyone know about this?

A: Your PHP-FPM config is set to the default 5 children (simultaneously executing PHP requests) and that limit is (on occasion it appears) being exceeded and hence the 500 error. Have a read of this article if you want background knowledge on the PHP-FPM max_children setting.
There is also a handy online calculator for calculating a more appropriate max_children value for your server configuration.
Once you have calculated a new (higher) value for the setting, you'll need to update your PHP-FPM configuration and reset the PHP-FPM service on your server for the change to take effect.


text:
Q: Sum of hypergeometric distribution
An urn contains $w$ white and $b$ black balls. $n$ extractions without replacement are made (Hypergeometric distribution). The distribution of $\mathbb{P}(X_i=s)$ with $i\geq s$ ($s$ white on $ith$ drawn) is:
$$\mathbb{P}(X_i=s)=\frac{\dbinom{w}{s}\dbinom{b}{i-s}}{\dbinom{w+b}{i}}$$

How can I find $\mathbb{P}(Z=X_i+X_j)$? I know that $X_i$ and $X_j$ are not independent.

A: I suspect that if $i \le j$ and $0 \le z \le i+j$ with $Z=X_i+X_j$ then $$\mathbb{P}(Z=z) = \frac{\displaystyle \sum_{s: \max(0,z-w) \le s \le \min(i,z/2)} \dbinom{w}{s}\dbinom{b}{i-s}\dbinom{w-s}{z-2s}\dbinom{b-i+s}{j-i-z+2s}}{\dbinom{w+b}{i} \dbinom{w+b-i}{j-i}} $$ and I would guess that it might be difficult to simplify this except in special cases


text:
Q: What happens when a C++ implementation throws an exception to C code So we have a public C header file (shooting for everything to be C callable)
 //foo.h
 #ifndef FOO_H
 #define FOO_H
 extern "C"
 {
   struct Foo;
   typdef FooHandle Foo*;

   FooHandle Foo_init();

   int Foo_bar(FooHandle handle);
 }
 #endif

And then the C++ header file:
 //foo.hpp
 #ifndef FOO_HPP
 #define FOO_HPP

 namespace my_foo
 {
   class Foo
   {
   public:
     int bar();
   };
 }

And than a source file:
 //foo.cpp
 #include "foo.h"
 #include "foo.hpp"
 #include <exception>

 void my_foo::Foo:bar() {throw std::exception();}

 FooHandle Foo_init() { return reinterpret_cast<FooHandle>(new my_foo::Foo());}
 int Foo_bar(FooHandle handle){
    my_foo::Foo& foo = *reinterpret_cast<my_foo::Foo*>(handle);
    foo.bar();
 }

What happens when I call Foo_bar from a pure C context (since C++ exceptions are not allowed) on various platforms? I know the behavior is probably "undefined", but I'm interested in what happens on various platforms.

A: In Win32 C++ exceptions are implemented on top of SEH (structured exception handling). The exceptions propagate through C code and crash it unless C code catches them by SEH mechanism.


text:
Q: how is [1,2,3]==[1,2,3] false in javascript? how is [1,2,3]==[1,2,3] and [1,2,3]===[1,2,3] false? Would appreciate a simple explanation. Came across this while watching a youtube video.. anymore "anomalies" like this?

A: The == operator checks whether the two operands reference the same object. While the two objects (arrays are objects) may have the same content, they are different instances, and thus the expression is false.

A: The === and == operators compares arrays by reference (i.e. location in memory), the easy way to think about it is that "they are different arrays with the same values".
If you give you arrays a name, maybe the reason for this will be clearer:
const arr1 = [1, 2, 3];
const arr2 = [1, 2, 3];

console.log(arr1 === arr2);

And arr1 is not the same array as arr2.
Conversely, this will log true, because it compares the same reference:
const arr = [1, 2, 3];

console.log(arr === arr);

A: They are not equal because they are not the "same".
In js, if you do [1,2,3] it stores the array as a variable with no name. Give it a name, say 'r', and do r==r and it will return true because window.r is the same as window.r. But window.undefinedvariable0 is not the same as window.undefinedvariable1, although they are visually the same.