text:
Q: java frame not changing colour I am unable to change the colour of my frame in Java code below. I know the code to change it would be frame.getContentPane().setBackground(Color.gray); However, this is not working for me, I am not sure what is the reason behind this, but if you are able to solve the problem do let me know, thank you.
public class UserLoginPage implements ActionListener {
    //Put all JLabels,Frames and buttons here etc
    JPanel panel = new JPanel();
    JFrame frame = new JFrame();
    JLabel userLabel = new JLabel("Username");
    JLabel passwordLabel = new JLabel("Password");
    JTextField userText = new JTextField();
    JTextField passwordText = new JTextField();
    JButton loginButton = new JButton("Login");

    //Label for successful login
    JLabel success = new JLabel();

    //Default Constructor to add the frames and panels etc
    public UserLoginPage(){
        panel.setLayout(null);
        userLabel.setBounds(10,20,80,25);
        panel.add(userLabel);
        passwordLabel.setBounds(10,50,80,25);
        panel.add(passwordLabel);

        userText.setBounds(100,20,165,25);
        panel.add(userText);
        passwordText.setBounds(100,50,165,25);
        panel.add(passwordText);

        loginButton.setBounds(10,80,80,25);
        loginButton.addActionListener(this);
        panel.add(loginButton);

        success.setBounds(10,110,300,25);
        panel.add(success);
        //success.setText();

        frame.setSize(500,500);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.getContentPane().setBackground(Color.gray);
        frame.setVisible(true);
        frame.add(panel);

    }

    public static void main(String[] args){
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new UserLoginPage();
            }
        });
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String user = userText.getText();
        String password = passwordText.getText();
        System.out.println(user + ", " + password);

        if(user.equals("Jackson") && password.equals("1234")){
            JOptionPane.showMessageDialog(frame,"Login successful");
        }
        else{
            JOptionPane.showMessageDialog(frame,"Invalid password or username");
        }
    }
}

A: You're adding panel, a JPanel to your JFrame, and since JFrame's contentPane uses a BorderLayout, this JPanel (which is opaque), will completely cover the contentPane, preventing visualization of the contentPane's background.
Solution:

*

*Either make the panel not-opaque via panel.setOpaque(false); so that now its container's colors or images will show through

*or leave it default opaque give it and not the contentPane the background color of choice.

Unrelated issue is here:
panel.setLayout(null)

You really don't want to be doing this for many reasons, including because this will make your GUI work well / look nice on only one platform. It also makes it very hard to upgrade and enhance the GUI later.

For example, and incorporating some of Andrew Thompson's suggestions, here is an example login GUI that is geared towards creating a JPanel, one that in this example is placed into a modal JDialog (similar to a JOptionPane but with more flexibility) and displayed. The code uses GridBagLayout along with GridBagConstraints when adding components to place them where I want them to be in a pleasing way that works on all platforms, and that allows ease and flexibility should I want to add more components:
import java.awt.Color;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;

@SuppressWarnings("serial")
public class UserLoginPanel extends JPanel {
    private static final Color BACKGROUND = new Color(200, 200, 200);
    private JTextField userText = new JTextField(15);
    private JPasswordField passwordText = new JPasswordField(15);
    LoginAction loginAction = new LoginAction(this, "Login", KeyEvent.VK_L);
    JButton loginButton = new JButton(loginAction);

    public UserLoginPanel() {
        super(new GridBagLayout());
        setBackground(BACKGROUND);

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        int insetGap = 4;
        gbc.insets = new Insets(insetGap, insetGap, insetGap, insetGap);

        add(new JLabel("User Name:"), gbc);

        gbc.gridx = 1;
        add(userText, gbc);

        gbc.gridx = 0;
        gbc.gridy = 1;
        add(new JLabel("Password"), gbc);

        gbc.gridx = 1;
        add(passwordText, gbc);

        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.gridwidth = 2;
        add(loginButton, gbc);

        insetGap = 8;
        setBorder(BorderFactory.createEmptyBorder(insetGap, insetGap, insetGap, insetGap));
    }

    public String getUserName() {
        return userText.getText();
    }

    public char[] getPassword() {
        return passwordText.getPassword();
    }

    public static void main(String[] args) {
        UserLoginPanel loginPanel = new UserLoginPanel();
        JDialog dialog = new JDialog(null, "User Login", ModalityType.APPLICATION_MODAL);
        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        dialog.add(loginPanel);
        dialog.pack();
        dialog.setLocationByPlatform(true);
        dialog.setVisible(true);
    }
}

@SuppressWarnings("serial")
class LoginAction extends AbstractAction {
    private UserLoginPanel loginPanel;

    public LoginAction(UserLoginPanel loginPanel, String name, int mnemonic) {
        super(name);
        putValue(MNEMONIC_KEY, KeyEvent.VK_L);
        this.loginPanel = loginPanel;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String userName = loginPanel.getUserName();
        char[] password = loginPanel.getPassword();

        System.out.println("User Name: " + userName);
        System.out.println("Password:  " + new String(password));

        Component source = (Component) e.getSource();
        if (source != null) {
            Window window = SwingUtilities.getWindowAncestor(source);
            if (window != null) {
                window.dispose();
            }
        }
    }
}


text:
Q: EJB utf-8 characters not persisted I have an ejb 3 application and deployed it in Glassfish 3.1 server.
I have ExamDtl entity with exmId & qustion fields, when i persist entity in database i found value of qustion field become ????.
I have set UTF8 collation in table and I can insert utf-8 characters just fine with sql using like "INSERT INTO..."
I  have also set following property in sun-resources.xml file
<property name="URL" value="jdbc:mysql://localhost:3306/exam_databse?useUnicode=yes&characterEncoding=UTF-8"/>

Is there any setting for utf 8 in ejb?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why Node.ChildNodes.FindNode() fails but Node.ChildNodes[] succeeds? Can anyone explain why ChildNodes.FindNode('') (1) fails but ChildNodes[''] (2) succeeds? ==>
Code:
const
   cNodeSOAPEnvelope  = 's:Envelope';
   cNodeSOAPBody      = 's:Body';
   cNodeSOAPBodyFault = 's:Fault';
   cNodeSOAPHeader    = 's:Header';
   cNodeFaultCode     = 'faultcode';
   cNodeFaultString   = 'faultstring';

procedure TFrmXMLParsingTests.BtnTestClick(Sender: TObject);
var
   SoapBodyNode,
   SoapBodyFaultNode,
   SoapHeaderNode,
   FaultCodeNode,
   FaultTextNode,
   RootNode: IXmlNode;
begin
   RootNode := XMLDoc.DocumentElement;
   Assert(RootNode.NodeName = cNodeSOAPEnvelope,'Root node is not SOAP envelope');
   SoapBodyNode := RootNode.ChildNodes[cNodeSOAPBody];
   SoapBodyFaultNode := SoapBodyNode.ChildNodes[cNodeSOAPBodyFault];
   if SoapBodyFaultNode <> nil then
   begin
//      FaultCodeNode := SoapBodyFaultNode.ChildNodes.FindNode(cNodeFaultCode);     (*1*)
//      FaultTextNode := SoapBodyFaultNode.ChildNodes.FindNode(cNodeFaultString);   (*1*)
      FaultCodeNode := SoapBodyFaultNode.ChildNodes[cNodeFaultCode];                (*2*)
      FaultTextNode := SoapBodyFaultNode.ChildNodes[cNodeFaultString];              (*2*)
      Exit; // Nothing more to do
   end; { fault in body }
   SoapHeaderNode := RootNode.ChildNodes.FindNode(cNodeSOAPHeader);
   Assert(SoapHeaderNode <> nil,'SOAP Header not found');
end;

XML:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
   <s:Body>
      <s:Fault>
         <faultcode xmlns:a="http://schemas.microsoft.com/exchange/services/2006/types">a:ErrorSchemaValidation</faultcode>
         <faultstring xml:lang="nl-NL">The [snip] value.</faultstring>
         <detail>
            <e:ResponseCode xmlns:e="http://schemas.microsoft.com/exchange/services/2006/errors">ErrorSchemaValidation</e:ResponseCode>
            <e:Message xmlns:e="http://schemas.microsoft.com/exchange/services/2006/errors">The request failed schema validation.</e:Message>
            <t:MessageXml xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
               <t:LineNumber>10</t:LineNumber>
               <t:LinePosition>30</t:LinePosition>
               <t:Violation>The [snip] value.</t:Violation>
            </t:MessageXml>
         </detail>
      </s:Fault>
   </s:Body>
</s:Envelope>

Thanks
Jan

A: Read the documentation.  When you access the ChildNodes[] property asking for a non-existant node, a new node will automatically be created if the doNodeAutoCreate flag is enabled in the parent XMLDocument's Options property, otherwise an EXMLDocError exception will be raised instead.
Update: since your document contains multiple XML namespaces in it, you need to take the namespaces into account when using the ChildNodes[] property and the FindNode() method.  The reason your code is not finding the <faultcode> and <faultstring> nodes correctly is because they have a different namespace (actually, they don't have any namespace at all) than the <Fault> tag has, but the ChildNodes[] property and the 1-parameter FindNode() method expects them to have the same namespace as their parent node.  When you search a namespaced node for a child node that has a different namespace, you have to include the child's namespace in the search in order to find the child node correctly.
Try this:
uses
  ..., XmlIntf, XMLDom, XmlDoc;

const
  cSoapEnvelopeNS    = 'http://schemas.xmlsoap.org/soap/envelope/';
  cExchangeErrorsNS  = 'http://schemas.microsoft.com/exchange/services/2006/errors';
  cExchangeTypesNS   = 'http://schemas.microsoft.com/exchange/services/2006/types';

  cNodeSOAPEnvelope  = 'Envelope';
  cNodeSOAPBody      = 'Body';
  cNodeSOAPBodyFault = 'Fault';
  cNodeSOAPHeader    = 'Header';
  cNodeFaultCode     = 'faultcode';
  cNodeFaultString   = 'faultstring';
  cNodeDetail        = 'detail';
  cNodeResponseCode  = 'ResponseCode';
  cNodeMessage       = 'Message';
  cNodeMessageXml    = 'MessageXml';
  cNodeLineNumber    = 'LineNumber';
  cNodeLinePosition  = 'LinePosition';
  cNodeViolation     = 'Violation';

procedure TFrmXMLParsingTests.BtnTestClick(Sender: TObject);
var
   RootNode,
   SoapBodyNode,
   SoapBodyFaultNode,
   SoapHeaderNode,
   FaultCodeNode,
   FaultTextNode,
   DetailNode,
   ResponseCodeNode,
   MessageNode,
   MessageXmlNode,
   LineNumberNode,
   LinePositionNode,
   ViolationNode: IXMLNode;
begin
   RootNode := XMLDoc.DocumentElement;
   Assert(NodeMatches(RootNode.DOMNode, cNodeSOAPEnvelope, cSoapEnvelopeNS), 'Root node is not SOAP envelope');

   // these have the same namespace as <Envelope>
   SoapBodyNode := RootNode.ChildNodes[cNodeSOAPBody];
   SoapBodyFaultNode := SoapBodyNode.ChildNodes.FindNode(cNodeSOAPBodyFault);

   if SoapBodyFaultNode <> nil then
   begin
      // these have a different namespace than <Fault>!
      FaultCodeNode := SoapBodyFaultNode.ChildNodes.FindNode(cNodeFaultCode, '');
      FaultTextNode := SoapBodyFaultNode.ChildNodes.FindNode(cNodeFaultString, '');
      DetailNode := SoapBodyFaultNode.ChildNodes.FindNode(cNodeDetail, '');

      if DetailNode <> nil then
      begin
        // these have different namespaces than <detail>!
        ResponseCodeNode := DetailNode.ChildNodes.FindNode(cNodeResponseCode, cExchangeErrorsNS);
        MessageNode := DetailNode.ChildNodes.FindNode(cNodeMessage, cExchangeErrorsNS);
        MessageXmlNode := DetailNode.ChildNodes.FindNode(cNodeMessageXml, cExchangeTypesNS);

        if MessageXmlNode <> nil then
        begin
          // these have the same namespace as <MessageXml>
          LineNumberNode := MessageXmlNode.ChildNodes.FindNode(cNodeLineNumber);
          LinePositionNode := MessageXmlNode.ChildNodes.FindNode(cNodeLinePosition);
          ViolationNode := MessageXmlNode.ChildNodes.FindNode(cNodeViolation);
        end;
      end;
      Exit;
   end;

   // this has the same namespace as <Envelope>
   SoapHeaderNode := RootNode.ChildNodes.FindNode(cNodeSOAPHeader);
   Assert(SoapHeaderNode <> nil,'SOAP Header not found');
end;

A: Write your own function:
function SearchChilds(StartNode: IXMLNode; Nodename: string): IXMLnode;
var i: Integer;
begin
   Result := nil;
   for i := 0 to StartNode.ChildNodes.Count-1 do
   begin
      if (StartNode.ChildNodes[i] <> nil) and (StartNode.ChildNodes[i].LocalName = Nodename) then
      begin
         Result := StartNode.ChildNodes[i];
         break;
      end;
      if StartNode.ChildNodes[i].HasChildNodes then
      begin
         Result := SearchChilds(StartNode.ChildNodes[i], Nodename);
         if Result<>nil then break;
      end;
   end;
end;


text:
Q: AWS boto3 -- Difference between `batch_writer` and `batch_write_item` I'm currently applying boto3 with dynamodb, and I noticed that there are two types of batch write
batch_writer is used in tutorial, and it seems like you can just iterate through different JSON objects to do insert (this is just one example, of course)
batch_write_items seems to me is a dynamo-specific function. However, I'm not 100% sure about this, and I'm not sure what's the difference between these two functions (performance, methodology, what not)
Do they do the same thing? If they are, why having 2 different functions? If they're not, what's the difference? How's the performance comparison?

A: As far as I understand and use these APIs, with the batch_write_item(), you can even handle the data for more than one table in one query. But with batch_writer(), it means you are going to specify the actions are only applicable for a certain table. I think that should be the very basic difference I can tell you.

A:
batch_writer creates a context manager for writing objects to Amazon
  DynamoDB in batch.
The batch writer will automatically handle buffering and sending items
  in batches.
In addition, the batch writer will also automatically handle any
  unprocessed items and resend them as needed. All you need to do is
  call put_item for any items you want to add, and delete_item for any
  items you want to delete.
In addition, you can specify auto_dedup if the batch might contain
  duplicated requests and you want this writer to handle de-dup for you.

source


text:
Q: How to edit arabic string properly? <string name="message">هذا المجلد يحتويى على %1$s ملفات. الرجاء التأكد قبل الحذف. الملفات المحذوفة غير قابلة للإسترجاع.</string>

I wanna put "%1$s" in an arabic string, but as you can see here, word, notepad++, utraedit, all failed to get the right string. how you guys edit arabic string?

A: In android Studio 2, RTL support is not turned on by default,
Configure it Manually:
1. In your Computer, go to the [android-studio2.0]/bins/idea.properties
2. add editor.new.rendering=true to the end of idea.properties
3. restart your android studio.

A: This is a source of frustration when editing mixed-direction text. What counts is the logical order of the text, not how any of the editors display it. When you finally format the string at run time in the app, the %1$s will be replaced by whatever string you pass to the formatting method. The only thing that matters is how the string will be rendered after the substitution.
The easiest thing to do is to write the message without the %1$s, then position the insertion caret, paste in the format code, and simply ignore how the editors screw up the bidi analysis. (The screw-up is because the editors are using a left-to-right base level. In some editors, you can set the base flow to right-to-left, but then the xml markup ends up being unreadable.)

A: When I work with RTL text and I need to put a place holder(%1$s) or LTR words, I just write it in MS Word and copy to the IDE.
It works for me in Eclipse and Android Studio.
All you need to check is that the components that displays that string like TextView has the right gravity.

A: You can try in Activity..
String formatedString =  String.format("%1$s", getString(R.string.your_string));


text:
Q: Advanced logical operations in MongoDB with Java Driver I have a little problem with MongoDB, I'm trying to create a query with multiple operators with the Java driver. I'm looking for something like this :
x1 : y1 OR (x2 : y2 AND x3 : y3)
At the moment I have this :
 BasicDBObject andQuery = new BasicDBObject();

 List<BasicDBObject> obj2 = new ArrayList<BasicDBObject>();
 obj2.add(new BasicDBObject("x1", "y1"));
 andQuery.put("$or", obj2);

 List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
 obj.add(new BasicDBObject("x2", "y2"));
 obj.add(new BasicDBObject("x3", "y3"));
 andQuery.put("$and", obj);

And that give me this when I make a print :
 { "$or" : [ { "x1" : "x1"}] , "$and" : [ { "x2" : "x2"} , { "x3" : "y3"}]}

So I think the problem comes from the first ']' which should be at the end, so the $and will be in the $or array.
But how can I make this possible ? Thanks !

A: Try this :
BasicDBObject orQuery = new BasicDBObject();

List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
obj.add(new BasicDBObject("x2", "y2"));
obj.add(new BasicDBObject("x3", "y3"));
andQuery.put("$and", obj);

List<BasicDBObject> obj2 = new ArrayList<BasicDBObject>();
obj2.add(new BasicDBObject("x1", "y1"));
obj2.add(andQuery);
orQuery.put("$or", obj2);


text:
Q: Java (openjdk version "1.8.0_151", linux) millions of records in memory. Often adding and requesting sorted data Every record have id, price and quantity. When new record is added if id already exist, new record replace old one, id is unique in data set. Very often I need to get sorted data(by price). Like top 100 or 25-50 position in data set. Good thing is that every time I need sorted data is from starting of data set. (I have used Comparable compareTo(Object o) when I could).
I have tried storing data into:

*

*ArrayList replacing element when id is same or add element on the end. Sorting it when data is needed. Too slow.

*ArrayDeque removing old element if exist and adding new element. Sorting it when data is needed. Too slow.

*HashMap helps with unique id and replacing existing ones. When sorting  I took values from HashMap and sort them as ArrayList. Faster but still not enough.

*TreeMap helps with unique id but can't sort it then by key. Sorting values as ArrayList. Same as HashMap.

*SortedSet(TreeSet)  removing old element if exist and adding new element. Get sorted elements using iterator. Fastest by now but still not enough.
I have checked Java Collections – Performance (Time Complexity) on operation here and here.
If someone have any suggestion what data type / sorting to use or how to make this as fast as possible.
I have some time required for this for example there is 100 millions of records updated(add/replace) and sorted on request. Without using any benchmark software on octa/quad core(eight thread CPU) on 4Ghz should be around 2,3 minutes. Keep in mind that as number of records grown time for add/replace and sort are higher.

A: As suggested by László van den Hoek, you should consider actually storing your data in a database, which can handle large amounts of data, and can index the data for faster sorted lookups.
However, for you home-grown in-memory data "store", you should maintain both a HashMap for lookup by id, and a TreeSet for sorted access.
You didn't specify what sorting you were using, so below I'll assume you meant to sort by price.
A TreeSet requires elements to be unique, so to sort by price you also need to sort secondarily by id, to make the sort key unique. Bonus side-effect: Consistent sorting of records with same price.
First, we fully define your Record class:
class Record implements Comparable<Record> {
    private int id;
    private double price;
    private int quantity;

    public Record(int id, double price, int quantity) {
        this.id = id;
        this.price = price;
        this.quantity = quantity;
    }

    public Record(double price, int id) {
        this.id = id;
        this.price = price;
    }

    public int getId() {
        return this.id;
    }

    public double getPrice() {
        return this.price;
    }

    public int getQuantity() {
        return this.quantity;
    }

    @Override
    public int compareTo(Record that) {
        int cmp = Double.compare(this.price, that.price);
        if (cmp == 0)
            cmp = Integer.compare(this.id, that.id);
        return cmp;
    }

    @Override
    public boolean equals(Object obj) {
        if (! (obj instanceof Record))
            return false;
        Record that = (Record) obj;
        return (this.id == that.id);
    }

    @Override
    public int hashCode() {
        return this.id;
    }
}

The alternate constructor is a convenience helper for the DataStore below.
The equals and hashCode methods are not needed by the DataStore logic, but it's always a good idea to implement them, if equality is well-defined.
Now we implement the DataStore class that encapsulates the logic of having both a HashMap and a TreeSet:
class DataStore {
    private Map<Integer, Record> recordsById = new HashMap<>();
    private TreeSet<Record> recordsByPrice = new TreeSet<>();

    public Optional<Record> addOrReplace(Record newRecord) {
        Record oldRecord = this.recordsById.put(newRecord.getId(), newRecord);
        if (oldRecord != null)
            this.recordsByPrice.remove(oldRecord);
        this.recordsByPrice.add(newRecord);
        return Optional.ofNullable(oldRecord);
    }

    public Optional<Record> remove(int id) {
        Record oldRecord = this.recordsById.remove(id);
        if (oldRecord != null)
            this.recordsByPrice.remove(oldRecord);
        return Optional.ofNullable(oldRecord);
    }

    public Optional<Record> getById(int id) {
        return Optional.ofNullable(this.recordsById.get(id));
    }

    public NavigableSet<Record> getByPrice(double price) {
        return this.recordsByPrice.subSet(new Record(price, Integer.MIN_VALUE), true,
                                          new Record(price, Integer.MAX_VALUE), true);
    }

    public NavigableSet<Record> getByPriceRange(double fromPriceInclusive, double toPriceExclusive) {
        return this.recordsByPrice.subSet(new Record(fromPriceInclusive, Integer.MIN_VALUE), true,
                                          new Record(toPriceExclusive, Integer.MIN_VALUE), false);
    }
}


text:
Q: A weakness of the TDD method? This is in summary the TDD method:

*

*Write a test

*check if thes test fails

*write production code

*run test

I think that TDD as presented  works only in ideal circumstances. I'll take a simple example:
Specification:
Write a program that calculates the square root of a number, the user must enter a number. If the number is negative, the program should display an error, and if the number is positive or zero the program should display the number whose square is the number entered, or for decimal number whose square is closest to the number entered.
Writing test
class SquareRootTest {

   private SquareRoot squareRoot;

   public void testNegativeNumber() {
      assertException(squareRoot.execute(-5);
   }

   public void testIntegerSquareRoot() {
      assertEqual(squareRoot.execute(9),3);
   }

   public void testDecimalSquareRoot() {
     assertEqual(squareRoot.execute(3),1.732);
   }
}

run failed test
writing production code:
class SquareRoot {

 public double execute(Number number) {
     if(number < 0)
         throw exception;
     if(number < 1)
         return squareRootLessThanOne(number);
      else
         return squareRootGreaterThanOne(numner);
   }

//private methods....

}

this is when writing production code, I find that I have to deal with the numbers lower than one differently from those numbers greater than 1. So I need to update my tests to reflect this.
Updating test
class SquareRootTest {

   public void testNegativeNumber() {
       assertException(squareRoot.execute(-5));
   }

   public void testIntegerSquareRoot() {
       assertEqual(squareRoot.execute(9),3);
   }

   public void testDecimalSquareRoot() {
      assertEqual(squareRoot.execute(3),1.732);
   }

   public void testNumberLowerThanOne() {
      assertEqual(squareRoot.execute(0.04),0.200);
   }
}

If I had found a single algorithm to calculate the square root, I would not change my tests.
The TDD method focuses solely on tests from specifications, yet there are tests that are derived from the implementation, particularly all conditional instructions and all instructions controlled by loops should normally be tested. These tests case can not be detected at the time of specification.
My question: How does TDD will deal with this situation? or is effectivelly a weakness of the TDD?

A:
The TDD method focuses solely on tests from specifications

No. It doesn't. TDD encourages adding tests based on your implementation. At each stage of your implementation you are looking for a test that will fail. You add that test, and then make it pass.
So in your case, when you found that numbers less than one have to be deal with differently, you'd start by adding a test for those numbers which failed your implementation. Then you'd add the less than one version.

A: One test at a time.  You say it should throw an exception if given a negative argument?
public double execute(Number number) {
    throw exception;
}

Now it passes the first test.
You say it should return 3 if given 9?
public double execute(Number number) {
    if (number.equals(9))
        return 3;
    throw exception;
}

Now it passes both tests.
But you know you're not done.  You know you've just been putting in dummy values, dummy logic.  You add tests to drive it to a correct solution, and you'll know when it's easier to put in the correct solution than to add yet another dummy branch.
I believe the problem you are having in understanding TDD is the thought that all tests are written up front.  They're not.  Write one, make it pass.  Write the next one, make it pass (without breaking the first one).  Refactor when green.  That is TDD, not translating a full spec into tests and then making them pass.


text:
Q: Arrange by a new variable in R I've looked for similar threads but can't find a solution.
I've grouped the below dataset by carrier and created new variables to see average and sum delay times successfully. Now I simply want to arrange the data by avg delay, but when I put the below code in it's returning the same data for every row. Can anyone help me figure out where I went wrong?
Using dplyr package, dataset is "flights", have filtered out the na values using:
filter(!is.na(dep_delay), !is.na(arr_delay)).

I got the data and excercise from section 5.6.7 of this resource http://r4ds.had.co.nz/transform.html#exercises-11
bycarrier %>%
  transmute(
    arrsum = sum(arr_delay),
    arravg = mean(arr_delay),
    depsum = sum(dep_delay),
    depavg = mean(dep_delay)
  ) %>%
  arrange(desc(arravg))

Returns:
Adding missing grouping variables: `carrier`
Source: local data frame [327,346 x 5]
Groups: carrier [16]

   carrier arrsum  arravg depsum   depavg
     <chr>  <dbl>   <dbl>  <dbl>    <dbl>
1       F9  14928 21.9207  13757 20.20117
2       F9  14928 21.9207  13757 20.20117
3       F9  14928 21.9207  13757 20.20117
4       F9  14928 21.9207  13757 20.20117
5       F9  14928 21.9207  13757 20.20117
6       F9  14928 21.9207  13757 20.20117
7       F9  14928 21.9207  13757 20.20117
8       F9  14928 21.9207  13757 20.20117
9       F9  14928 21.9207  13757 20.20117
10      F9  14928 21.9207  13757 20.20117
# ... with 327,336 more rows

A: I think you need to use the function summarise instead of transmute as follows :
bycarrier %>%
  summarise(
    arrsum = sum(arr_delay),
    arravg = mean(arr_delay),
    depsum = sum(dep_delay),
    depavg = mean(dep_delay)
  ) %>%
  arrange(desc(arravg))

That will give the output :
# A tibble: 16 x 5
   carrier arrsum     arravg  depsum    depavg
     <chr>  <dbl>      <dbl>   <dbl>     <dbl>
1       F9  14928 21.9207048   13757 20.201175
2       FL  63868 20.1159055   59074 18.605984
3       EV 807324 15.7964311 1013928 19.838929
4       YV   8463 15.5569853   10281 18.898897
5       OO    346 11.9310345     365 12.586207
6       MQ 269767 10.7747334  261521 10.445381
7       WN 116214  9.6491199  212717 17.661657
8       B6 511194  9.4579733  700883 12.967548
9       9E 127624  7.3796692  284306 16.439574
10      UA 205589  3.5580111  694361 12.016908
11      US  42232  2.1295951   74261  3.744693
12      VX   9027  1.7644644   65263 12.756646
13      DL  78366  1.6443409  439595  9.223950
14      AA  11638  0.3642909  273758  8.569130
15      HA  -2365 -6.9152047    1676  4.900585
16      AS  -7041 -9.9308886    4134  5.830748


text:
Q: KTBoost.BoostingRegressor TypeError: __cinit__() takes exactly 5 positional arguments (6 given) I'm trying to run a BoostingRegressor model from the KTBoost package for binary classification, and i'm facing this error. I do not understand what it may cause it, nor any course of action I should follow to fix it.
Is there something I can do to give more information? plshelpme
Xtrain = df.iloc[:, 2:492]
ytrain = df.Target
model = KTBoost.BoostingRegressor(loss='tobit', yl=0, yu=100)
model.fit(Xtrain, ytrain)

A: Thanks for pointing this out. This is now fixed as of version 0.1.14 of KTBoost. It was a wrong dependency on scikit-learn. Note that you need the newest version of scikit-learn (scikit-learn>=0.21.3).
In the future, please open an issue on https://github.com/fabsig/KTBoost. It will be answered faster there.


text:
Q: How to implement compareTo for any types of comparable objects I don't know how I can compare 2 comparable objects without some other variable which tells me which is larger. The question is: Create a class called Max that provides a single class method called max. max takes two arguments to objects that can be compared—that is, that implement the Java Comparable interface as shown above. It returns a reference to whichever is larger. If the two objects are equal, you should return the first. How Comparable is implemented is up to each class, and your method will be called on multiple different kinds of objects.
It gives the int compareTo (Object other) method in the interface but I'm having trouble finding a solution.
public class Max implements Comparable
{
    public int compareTo(Object other)
    {

    }

    public static Comparable max(Comparable first, Comparable second)
    {
        int fi = first.compareTo(second);
        if(fi >0)
            return first;
        else if (fi<0)
            return second;
        return first;
    }
}

java.lang.AssertionError: Class should not implement Comparable: expected [false] but found [true]

That is one of the errors. But also I need help writing the compareTo method.

A: I deleted my previous answer because I think, imho, you are over complicating this.  Since the two arguments to max have implemented the Comparable<T> interface, all you have to do is call it as:
int ret = first.compareTo(second);

Then return first or second like you are doing based on the value of ret.  That way you don't need to know anything about how it was implemented.  Perhaps you could get some clarification from either your instructor or someone else who is working on this (I presume it is for an assignment).
It would be worthwhile for you to create some test classes which implement the interface.  You can just make up some variable that represents size.

A: The keyword for your question is generics. You might want to do some research and read something about it. Take a look at the following example. I've implemented the class Max as a static class to keep it simple:
import java.time.LocalDate;

public class MyTestClass{
    public static void main(String args[]) {
        Integer i = 16;
        Integer j = 15;
        Integer m = Max.max(i, j);
        System.out.println(m);
        String k = "aaaa";
        String n = "zzzz";
        String s = Max.max(k, n);
        System.out.println(s);
        LocalDate d = LocalDate.now();
        LocalDate e = LocalDate.now().plusDays(2);
        LocalDate f = Max.max(d , e);
        System.out.println(f);
    }
    static class Max{
        public static <T extends Comparable> T max(T first, T second) {
            if (first.compareTo(second) >= 0)
                return first;
            else
                return second;
        }
    }
}

As you can see, there is a class Max with a single method max which accepts two objects, for example two integers, two strings or two date objects.
Since all these classes implement the comparable interface, you can use the max method for all object types. The compiler then decides during the runtime which comapreTo method to call, that is the compareTo of the class Integer, String, LocalDate or whatever.


text:
Q: Inverse of given operator not continous Let $E = C[0,1]$ and $F = C^1[0,1]$ and equip both with the infinity norm $\|\cdot\|_\infty$.
Prove that the inverse of the operator $T: E\to F$ with $(Tf)(t) = \int_0^t f(s)\,\mathrm{d}s$ is not continuous.

A: Here's an example of a sequence $\{f_n\}_{n=1}^{\infty}$ within the unit ball $B_1(F)\subset F$ such that $\|T^{-1}f_n\|_{\infty}\to \infty$. Let $f_n(t) = 1-e^{-nt}$. As $nt\geq 0$, we have that $0 < e^{-nt}\leq 1$, so therefore we also have $0\leq f_n(t) < 1$ (implying $\|f_n\|_{\infty} < 1$). Also, $$f_n(t) = \int_0^t ne^{-ns}\,\mathrm{d}s$$ so $(T^{-1}f_n)(s) = ne^{-ns}$. This gives us $\|T^{-1}f_n\|_{\infty} = n$, which is unbounded. Therefore, $T^{-1} : F\to E$ is not continuous.


text:
Q: unable to find a MessageBodyReader I have this interface:
 @Path("inbox")
public interface InboxQueryResourceTest {

    @POST
    @Path("{membershipExternalId}/query")
    @Consumes(MediaType.APPLICATION_XML)
    @Produces("multipart/mixed")
    public MultipartOutput query(@PathParam("membershipExternalId") final String membershipExternalId,
                             @QueryParam("page") @DefaultValue("0") final int page,
                             @QueryParam("pageSize") @DefaultValue("10") final int pageSize,
                             @QueryParam("sortProperty") final List<String> sortPropertyList,
                             @QueryParam("sortReversed") final List<Boolean> sortReversed,
                             @QueryParam("sortType") final List<String> sortTypeString,
                             final InstanceQuery instanceQuery) throws IOException;
}

I have implemented the method to return a MultipartOutput.
I am posting an xml query from Fiddler and i receive the result without any problem.
BUT i have done an integration test for the same interface, i send the same objects and i put the response like:
final MultipartOutput multiPartOutput = getClient().query(getUserRestAuth(), 0, 25, null, null, null, instanceQuery);

But here, so from integration tests, i receive a strange error:

Unable to find a MessageBodyReader of content-type multipart/mixed;boundary="74c5b6b4-e820-452d-abea-4c56ffb514bb" and type class org.jboss.resteasy.plugins.providers.multipart.MultipartOutput

Anyone has any ideea why only in integration tests i receive this error?
PS: Some of you will say that i do not send application/xml as ContentType but multipart, which of course is false because the objects are annotated with the required @XmlRootElement etc, otherways neither the POST from Fiddler would work.

A: You can try this:
ResteasyProviderFactory providerFactory = ResteasyProviderFactory.getInstance();
providerFactory.registerProvider(org.jboss.resteasy.plugins.providers.multipart.MimeMultipartProvider.class);

A: Are including in classpath the corresponding resteasy addon for multipart encoding? (esteasy-multipart-provider).

A: Try adding this method to your test class.  This would register the default built-in providers which are already registered on your server.
@BeforeClass
public static void registerProviders() {
    ResteasyProviderFactory providerFactory = ResteasyProviderFactory.getInstance();
    RegisterBuiltin.register(providerFactory);
}


text:
Q: Running an Azure function app each time a CosmosDB document is created and updating documents in a second collection I have a scenario, where we have items save in one documentDb collection e.g. under /items/{documentId}. The document looks similar to:
{
    id: [guid],
    rating: 5,
    numReviews: 1
}

I have a second document collection under /user-reviews/{userIdAsPartitionKey}/{documentId}
The document will look like so:
{
    id: [guid],
    itemId: [guidFromItemsCollection],
    userId: [userId],
    rating: 4
}

Upon uploading of this document, I want a trigger to be fired which takes as input this new user rating document, is able to retrieve the relevant document from the items collection, transform the items document based on the new data.
The crux of my problem is: how can I trigger off a document upsert, and how can I retrieve and modify a document from another collection, all within a Funciton App?

I've investigated the following links, which tease at the idea of Triggers being possible on the CosmosDB, but the table suggests we can't hook up a trigger to document DB upload.
https://learn.microsoft.com/en-us/azure/azure-functions/functions-triggers-bindings
https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-documentdb
If it's not possible to set up directly, my assumption is I should have a middle tier service handling the upsert (currently using DocumentClient from client side), which can kick off this processing itself, but I like the simplicity of the serverless function apps if possible.

A: Operations are scoped to a collection. You cannot trigger an operation in Collection B from an event in Collection A.
You'd either need to implement this in your app tier (as you suggested) or... store both types of documents in the same collection (a common scenario). You might need to add some type of doctype property to help filter your queries, but since documents are schema-free, you can store heterogeneous documents in the same collection.
Also: You mentioned an Azure Function. Within a function, there's nothing stopping you from making multiple database calls (e.g. when something happens in collection a and causes your function to be called, your function can perform an operation in collection b). Just note that this won't be transactional.

A: I know this is a pretty old question.
The Change Feed was built for this exact scenario.
In today's Azure Portal, there's even a menu option in the CosmosDB blade that allows you to create and trigger Function based on changes in one collection which allows you to detect and react to changes - i.e. to create a document in another collection.


text:
Q: How to correctly start activity from PostExecute in Android? I have an AsyncTask, that fills a custom List with parsed data from Internet.
In PostExecute I fill that List and get it ready to transfer it to a new Activity.
I do it this way:
@Override
protected void onPostExecute(List<VideoDataDescription> result)
{
    super.onPostExecute(result);
    MainActivity.progressDialog.dismiss();

    context.startActivity(new Intent(context, ResultsQueryActivity.class));

}

where context
    private Context context;

In LogCat after executing this code I get a Java.lang.NullPointerException.
Is this possible and correct to start an Activity as I do it?
UPD
I have added
    private Context mContext;

public YoutubeAndYahooParser(Context context)
{
    super();
    this.mContext = context;
}

to initialize context and call
YoutubeAndYahooParser youtubeAndYahooParser = new YoutubeAndYahooParser(ResultsQueryActivity.this);
                    youtubeAndYahooParser.execute("my string to pass in asynctak");

After this in PostExecute
Intent intent = new Intent(mContext, ResultsQueryActivity.class);
 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 mContext.startActivity(intent);

I added new flag because of I have got in LogCat the next:
*Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?*
Am I right?

A: You should pass in the application context rather than a context from the local activity. I.e. use context.getApplicationContext() and save that in a local variable in your AsyncTask subsclass.
The code might looks something like this:
public class MyAsyncTask extends AsyncTask {

    Context context;
    private MyAsyncTask(Context context) {
        this.context = context.getApplicationContext();
    }

    @Override
    protected Object doInBackground(Object... params) {
        ...
    }

    @Override
    protected void onPostExecute(List<VideoDataDescription> result) {
        super.onPostExecute(result);
        MainActivity.progressDialog.dismiss();

        context.startActivity(new Intent(context, ResultsQueryActivity.class));
    }
}

you'd call it like this:
   new MyAsyncTask(context).execute();

A: I tried this just now ... it works in PostExecute Method!!!
Intent intent_name = new Intent();
intent_name.setClass(getApplicationContext(),DestinationClassName.class);
startActivity(intent_name);

A: But its better if you start a new Intent Based on the response(result) obtained from the previous activities.
This will eliminate the possibility of the error response from invoking the new intent.
Example if the previous activity was supposed to return Succesfully... or Welcome to allow the new intent to start, the i could check it out in this way
  protected void onPostExecute(String result) {
       if (result.equals("Succesfully...")){
           context.startActivity(new Intent(context, Login_Activity.class));
           Toast.makeText(context, result, Toast.LENGTH_LONG).show();

       }else  if (result.contains("Welcome")){
           context.startActivity(new Intent(context, MainActivity.class));
       }else {
           Toast.makeText(context,result,Toast.LENGTH_LONG).show();
       }

    }


text:
Q: ESRI JS API is stripping hrefs ESRI's JS API seems to be stripping out the hrefs of URLs.
Here I set up a static link. Then I attempt to put it in the description. The link text and target="blank" are rendered but the link's href (test/) is blank!
    {% for project in projects %}

    var link = "Legal Description";
    console.log(link) // This prints as expected with href intact.

    var attributes = {
        Name: "{{project.description}}",
        Description: link // strips out the href?!?!?!?!
    }

It SHOULD be localhost:8000/projects/test but there is no test href.

A: The arcgis-js-api sanitizes html content in popups for security reasons.  I'm not sure how you're defining your popups or using the attributes variable, but you'll want to create a PopupTemplate, and its its content property to do what you want.  You can do it like the linked article recommends, or you can use a CustomContent instance for the popupTemplate content property.


text:
Q: Multistage Dockerfile Python so I got trouble here, I've deployed my multistage dockerfile with python:3.8-slim-buster, but I can't access this URL ? is there something wrong with my Dockerfile ?
# Build Image
FROM python:3.8-slim-buster as builder

RUN apt-get update --fix-missing
RUN DEBIAN_FRONTEND=noninteractive apt-get install -y libgl1-mesa-dev python3-pip git
RUN mkdir /usr/src/app

WORKDIR /usr/src/app

COPY ./requirements.txt /usr/src/app/requirements.txt

RUN pip3 install -U setuptools
RUN pip3 install --upgrade pip
RUN pip3 install -r ./requirements.txt

COPY . /usr/src/app

# Production Image
FROM python:3.8-slim-buster as app

COPY --from=builder /usr/src/app /usr/src/app

WORKDIR /usr/src/app

ENTRYPOINT gunicorn --bind 0.0.0.0:1500 --workers 1 --threads 8 main:app --worker-class uvicorn.workers.UvicornH11Worker --preload --timeout 60 --worker-tmp-dir /dev/shm

This is how I run my Docker:
sudo docker build -t priceengine .
sudo docker run -dp 1500:1500 priceengine
sudo docker start 2d7f96017801

So, my # Production Image was correct ?

A: I'm assuming your app depends on the installed packages, if so it will not work with a multistage built. Multistage builds are only helpful to avoid adding build-time dependencies to the final image. Here you need the apt packages and requirements.txt packages at runtime (ENTRYPOINT). Just use a normal Dockerfile for this (no multistage).

A: Try adding a line with EXPOSE 1500 before your ENTRYPOINT. This exposes the port from the docker container to your host system. Can you access it then?
Edit: Also not unimportant, how are you running your Docker container? Can you show your docker run command?


text:
Q: CMD: Bat to Exe Converter - Temp directory problem i am using 'Bat to Exe Converter' to convert my batch files to exe format.
Now, i am running into some problems.
Whenever i convert something, and i set 'Working Directory' to 'Current Directory', and i start my exe in echo on mode, this is what i end up with to check if there is a specific file in the directory of my exe:
the actual command: if not exist "%~dp0\file.txt" goto :nofile
output: if not exist "C:\Users\MyUser\AppData\Local\Temp\4CBC\\file.txt" goto :nofile
Can anyone help me with this? I don't want it in the temp directory, i want it to be in the directory of my exe.
Thanks.

A: Without having Bat to Exe changed by the author, I think you have two options:

*

*Remove the need for accessing %~dp0
Perhaps you can merge file.txt with the include option of Bat to Exe into the EXE   file. If so, "file.txt" will automatically be unpacked in the current directory when running your compiled exe, and you can it access by %CD%\file.txt.

*Get %~dp0 from outside and pass it to the exe as a command line parameter.
This can be done by a simple starter bat file that resides in the same directory as your compiled main batch file. This script schould contain the line
YourCompiled.Exe %~dp0% %%*

Your compiled exe then gets its directory from %1. So you cannot pack everything into one exe, but the main portion of it, perhaps that is sufficient for you.

A: Well, apparently your batch to exe converter simply packs the batch file and extracts it to a temporary directory prior to execution. Very simplistic, hard to get wrong (compared to actually understand the batch file) but it introduces errors such as the one you're describing.
Your best bet is probably to use another batch to exe converter; some of them are actually a little more sophisticated.

A: Generally, this is not a good idea. firstly, its prone to errors and instability of the converter on different cmd features. secondly, a determined hacker can still decode what you are doing with the batch. My suggestion, if you are so afraid of people looking into your batch,
1) let only the people who are authorized to use your batch to use it
2) give them the correct permissions.

OR, don't use batch at all
1) create a central interface such as a web interface, where all tasks to be done goes through that interface, like using an ATM machine where only buttons are allowed and all the available user options can be done by pushing buttons...etc..
2) authenticate your users through a central authentication system, eg Active Directory, or LDAP or a database.

A: This is an 2.5 yr old subject but there is an answer to this so I'm posting for anyone else that happens to find this in a search.

B2EC written by Fatih Kodak, has an option to "Submit current directory".
When this is used, you can reference %1 in your batch file to get the path of the EXE that was executed (instead of the path of the extracted BAT that is really being run).

Hovering over that option in the UI shows "Submit the current working directory as the last parameter".  The "last parameter" in my use has always been %1 but you can test your code to be sure.

A: The latest version, 2.1.4 at time of writing, of Bat to Exe by Fatih Kodak creates an Environmental Variable at runtime that can be substituted in place of %~dp0 to reference the Exe's path. Therefore, you can simply replace %-dp0 with %b2eprogrampathname% in the original batch file.

A: You can use external folders with f2ko's batch to exe converter.  Having
a separate folder for subroutines can neaten up a project folder.
To call mysubroutine that is located in mysubroutinesfolder\mysubroutine,
...
pushd mysubroutinesfolder
call mysubroutine
popd
...

The call can be made a one liner:
call xqt mysubroutine

where xqt.cmd is a program that does the call for you:
pushd mysubroutinesfolder
call %*
popd
exit /b

(the %* means "all of the arguments").
In this way your batch programs run as batch, and UNMODIFIED they will
compile with the bat to exe converter, creating a completely folder independent executable.  Select "temporary directory",
and include all of the subroutines/executables in your mysubroutines folder
by "selecting them all" with your cursor as usual, then hit "copy".
Be sure to include the xqt.cmd program too; place it "outside" of your mysubroutines folder.  Make sure that is is accessible by your main program.  Remember to select x64 if you
are runnning on a x64 machine, or the executable will not find SYSTEM32
files.  You can find f2k0's batch to exe converter at:
http://www.f2ko.de/programs.php?pid=b2e

A: Try this development environment for batch scripts, Batch Compiler . It has everything you need to develop a batch program.And compile into stable stand alone executable (Exe).
Friendly user interface.
Debugger, Check your code for syntax errors.
Powerful, versatile compiler.
Allows mouse input in batch files.
Use Windows Common Dialog Boxes.(BrowseFiles,BrowseFolders)
Draw graphics in batch files.
Reverse engineering proof encryption of source code.
Include Company name, Copyright info and Version info.
Make invisible(silent) executables.
Executables with administrator privileges.
Run & debug your script while editing.
Embed resources with executable.(music,images,files)
Advance Commands (BrowseFiles,LaunchSilent,MouseCMD)
Stand-alone executables.No dependencies needed.
Executables are woking on almost all windows operating systems.(98 to 10)

Quick download : http://bc.gotek.info/files/BatchCompiler159.zip
Cheers!

A: Use %CD% instead of %~dp0.
EDIT:
B2EC is not a real converter. Creation location of equipped .cmd file was chosen to be %TEMP% and this is a good choice. Application just lacks 3rd option for working directory of the script - .exe file directory. I advise you to mail the author about adding this one.
Different paths for .exe and created .cmd lead to information loss, i.e. we are unable to know .exe directory and current directory at the same time without providing additional information to the script (e.g. using environment variable or passing it as first/last argument to the script). This script would need to handle it and we would end writing cmd scripts tailored for this converter, which is bad.
%~dp0 - script directory (%TEMP%/.../) - practically useless
%cd% - working directory (as set up in the converter) - currently there are only 2 options: current directory (working directory of .exe) and temporary directory (actually equal to %~dp0, but without trailing backslash)
I think it can be solved by patching cmd.exe instance in memory to change the script path, but that's B2EC developer's duty.
Side note: Normal executable files can be easily executed with specified 0th argument by providing appriopriate lpApplicationName and lpCommandLine to CreateProcess function. Command files are executed via cmd.exe, so 0th argument cannot be set this way.

A: %cd% will give you the current directory:
if not exist "%CD%\file.txt" goto :nofile


text:
Q: Explanation of my "efibootmgr -v" output I am trying to ascertain where the EFI boot records are located on my Lenovo U41o by using the command sudo efibootmgr -v.
Can someone explain it to me?
$ sudo efibootmgr -v
BootCurrent: 0008
Timeout: 0 seconds
BootOrder: 0010,0003,0004,0005,0006,0008,0007,0009,000A,000B,001D
Boot0000  Setup
Boot0001  Boot Menu
Boot0002  Diagnostic Splash
Boot0003* ATA HDD2: WDC WD5000LPVT-08G33T1                      ACPI(a0341d0,0)PCI(1f,2)03120a00010000000000..bYVD.A...O.*..
Boot0004* ATA SSD1: SanDisk SSD U100 24GB                       ACPI(a0341d0,0)PCI(1f,2)03120a00000000000000..bYVD.A...O.*..
Boot0005* RAID DEVICE2: 030a2500d23878bc820f604d8316c068ee79d25ba5388f9ca46ace40bf2f0ade9bc05d6d01
Boot0006* RAID DEVICE1: 030a2500d23878bc820f604d8316c068ee79d25ba5388f9ca46ace40bf2f0ade9bc05d6d00
Boot0007* ATAPI CD: 030a2400d23878bc820f604d8316c068ee79d25baea2090adfde214e8b3a5e471856a354
Boot0008* USB HDD: SanDisk Cruzer Edge  ACPI(a0341d0,0)PCI(1a,0)USB(0,0)USB(0,0)3.!..3.G..A.....
Boot0009* USB FDD:  030a2400d23878bc820f604d8316c068ee79d25b6ff015a28830b543a8b8641009461e49
Boot000A* USB CD:   030a2400d23878bc820f604d8316c068ee79d25b86701296aa5a7848b66cd49dd3ba6a55
Boot000B* PCI LAN: EFI Network (IPv4)   ACPI(a0341d0,0)PCI(1c,1)PCI(0,0)MAC(089e01381698,0)IPv4(0.0.0.0:0<->0.0.0.0:0,0, 0x.J.+*.N.....=8.
Boot000C* Lenovo Recovery System    ACPI(a0341d0,0)PCI(1f,2)03120a00010000000000HD(3,276800,1f4000,26c6992a-07b8-43bc-98b8-d8c83e64db3b)File(\EFI\Microsoft\Boot\lrsBootMgr.efi)
Boot0010* Windows Boot Manager  HD(2,1f4800,82000,72931328-061b-42e0-8fd8-8a5ac7775074)File(\EFI\Microsoft\Boot\bootmgfw.efi)WINDOWS.........x...B.C.D.O.B.J.E.C.T.=.{.9.d.e.a.8.6.2.c.-.5.c.d.d.-.4.e.7.0.-.a.c.c.1.-.f.3.2.b.3.4.4.d.4.7.9.5.}...e................
Boot0014  Setup
Boot0015  Boot Menu
Boot0016  Diagnostic Splash
Boot001C* Lenovo Recovery System    ACPI(a0341d0,0)PCI(1f,2)03120a00010000000000HD(3,276800,1f4000,26c6992a-07b8-43bc-98b8-d8c83e64db3b)File(\EFI\Microsoft\Boot\lrsBootMgr.efi)
Boot001D* PCI LAN: EFI Network (IPv6)   ACPI(a0341d0,0)PCI(1c,1)PCI(0,0)MAC(089e01381698,0)030d3c000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000x.J.+*.N.....=8.

A: I'm going to take these out of order, since some of the early lines refer to later ones. The bulk of the output is the Boot#### lines, which describe boot options.
Boot0000  Setup
Boot0001  Boot Menu
Boot0002  Diagnostic Splash

Your example output includes a large number of options like these, which have names but no further elaboration. These are likely built-in options on your specific firmware. In your case, these first three seem to be options to enter the firmware setup menu, to launch the built-in boot manager, and to display a diagnostic splash screen -- but really, there's no way to know for sure what they are, at least not from the efibootmgr output alone.
The numbers following the Boot string are in hexadecimal, and there's nothing special about any given number -- that is, Boot0000 is not reserved for any particular function, nor is Boot0001 or anything else. The numbers are assigned when a program creates a new boot entry, and the assignments are essentially meaningless. (At least, unless there's a bug; I know of some bugs that can make a firmware favor lower-numbered boot entries.)
Boot0003* ATA HDD2: WDC WD5000LPVT-08G33T1                      ACPI(a0341d0,0)PCI(1f,2)03120a00010000000000..bYVD.A...O.*..
Boot0004* ATA SSD1: SanDisk SSD U100 24GB                       ACPI(a0341d0,0)PCI(1f,2)03120a00000000000000..bYVD.A...O.*..

These two options describe specific devices. After the Boot#### string comes a description that is human-interpretable, at least to a point -- you can see that these are two disk devices. The ACPI(...) and PCI(...) strings identify the hardware, and this information isn't readily interpreted by humans, except by cross-checking with other hardware information. Then there's some gibberish, which is encoded data for the entry that might or might not be easily read by humans. In this case, it's clearly not easily interpreted by people.
In most cases, when you see an entry like this that refers to a disk device, the reference is really to the fallback boot loader file (EFI/BOOT/bootx64.efi, at least on x86-64 systems) on the disk's EFI System Partition (ESP). EFI does not use boot loaders embedded in a disk's MBR, the way BIOS does.
Boot0005* RAID DEVICE2: 030a2500d23878bc820f604d8316c068ee79d25ba5388f9ca46ace40bf2f0ade9bc05d6d01
Boot0006* RAID DEVICE1: 030a2500d23878bc820f604d8316c068ee79d25ba5388f9ca46ace40bf2f0ade9bc05d6d00
Boot0007* ATAPI CD: 030a2400d23878bc820f604d8316c068ee79d25baea2090adfde214e8b3a5e471856a354

These are clearly more hardware entries. I don't recognize the format for these entries. You can ignore the long strings; just know that they refer to hardware devices.
I'm omitting a few entries here, since they're more of the same....
Boot000B* PCI LAN: EFI Network (IPv4)   ACPI(a0341d0,0)PCI(1c,1)PCI(0,0)MAC(089e01381698,0)IPv4(0.0.0.0:0<->0.0.0.0:0,0, 0x.J.+*.N.....=8.

This is a variant on the disk entries, but this one identifies a network device. Note that it includes a MAC address (MAC(...)) and specifies use of IPv4 (IPv4(...)). If this entry were to be booted, the computer would try to PXE-boot from a network server.
Boot000C* Lenovo Recovery System    ACPI(a0341d0,0)PCI(1f,2)03120a00010000000000HD(3,276800,1f4000,26c6992a-07b8-43bc-98b8-d8c83e64db3b)File(\EFI\Microsoft\Boot\lrsBootMgr.efi)
Boot0010* Windows Boot Manager  HD(2,1f4800,82000,72931328-061b-42e0-8fd8-8a5ac7775074)File(\EFI\Microsoft\Boot\bootmgfw.efi)WINDOWS.........x...B.C.D.O.B.J.E.C.T.=.{.9.d.e.a.8.6.2.c.-.5.c.d.d.-.4.e.7.0.-.a.c.c.1.-.f.3.2.b.3.4.4.d.4.7.9.5.}...e................

These entries both identify EFI boot loaders stored on the hard disk. They do so with slightly different syntaxes -- note that the first begins with ACPI(...) and PCI(...) entries, as earlier ones did, whereas the second uses an HD(...) identifier. The latter includes a GUID for the partition, along with some other idenfications. Both entries include a filename (File(...)). The Windows entry includes more gibberish-like data at the end, but in this case it's a UTF-16 string that's passed to the boot loader as an option.
Your example includes a lot of entries. Many EFIs produce much shorter lists -- for instance, they may be missing the built-in options or the options for PXE-booting from the network. OTOH, sometimes you'll see other options, like entries that refer to BIOS-mode boots. Notably absent from your list was an entry for booting Ubuntu. Here's such an entry from one of my computers:
Boot000D* ubuntu    HD(1,800,112800,a8d39218-44ce-455b-8735-919754df131d)File(\EFI\UBUNTU\GRUBX64.EFI)..BO

As you can see, that's pretty similar in basic form to the entry for the Windows boot loader, although of course the details differ. Your example may have been missing an Ubuntu entry because you haven't yet installed Ubuntu, because you installed Ubuntu in BIOS/CSM/legacy mode (a mistake), because your EFI is buggy and so efibootmgr was unable to add an entry, or because you explicitly deleted the entry once it was created. If you're having a boot problem, I recommend you ask another question and provide details.
The remaining entries follow these patterns. Now, backing up to the start....
ubuntu@ubuntu:~$ sudo efibootmgr -v
BootCurrent: 0008

The BootCurrent line identifies the entry that was used to boot the computer. In this case, it's Boot0008, which I snipped but which identifies a USB flash drive -- you booted using the fallback boot loader stored on that drive.
Timeout: 0 seconds

This line identifies the timeout on the EFI's built-in boot manager. In practice, it might or might not mean anything.
BootOrder: 0010,0003,0004,0005,0006,0008,0007,0009,000A,000B,001D

This line identifies the order in which boot entries are tried. In this case, the EFI will try booting with Boot0010 (the Windows boot manager). If that entry identifies a non-existent device or file, or if the boot program returns, then the firmware will try Boot0003 (your Western Digital hard disk). If that entry fails, it will try Boot0004 (your SanDisk SSD), and so on.

A: You can get a detailed explanation of the efibootmgr package with the command:
    man efibootmgr

It explains the output you get from efibootmgr in great detail.


text:
Q: Error writing a file in Android 11 passing a variable as file name I am trying to save files created in a specific directory I choose. I have many reason why I am doing this not locally.
My app had as target up to Android 10, but now I am trying to target Android 11 as well and so far everything works, except for one thing, the files are not saved if I pass a string variable as file name instead of a written name in the StringBuilder.
Let me explain you showing the working code and the not working code:
////WORKING
public class MyLoggerUtility {
private static String filename = "MyMonitoring_Log";
static boolean isExternalStorageAvailable = false;
static boolean isExternalStorageWriteable = false;
static String state = Environment.getExternalStorageState();

public static void addRecordToLog(String var0) {
    if ("mounted".equals(state)) {
        isExternalStorageWriteable = true;
        isExternalStorageAvailable = true;
    } else if ("mounted_ro".equals(state)) {
        isExternalStorageAvailable = true;
        isExternalStorageWriteable = false;
    } else {
        isExternalStorageWriteable = false;
        isExternalStorageAvailable = false;
    }

    File var1 = new File("/sdcard/MYPATH/LOG");
    if ("mounted".equals(state)) {
        if (!var1.exists()) {
            Log.d("Dir created ", "Dir created ");
            var1.mkdirs();
        }

        StringBuilder var6 = new StringBuilder();
        var6.append("/sdcard/MYPATH/LOG/");
        var6.append(filename);
        var6.append(".txt");
        File var2 = new File(var6.toString());

        if (!var2.exists()) {
            try {
                Log.d("File created ", "File created ");
                var2.createNewFile();
            } catch (IOException var5) {
                var5.printStackTrace();
            }
        }

        try {
            FileWriter var3 = new FileWriter(var2, true);
            BufferedWriter var7 = new BufferedWriter(var3);
            StringBuilder var8 = new StringBuilder();
            var8.append(var0);
            var8.append("\r\n");
            var7.write(var8.toString());
            var7.flush();
            var7.close();
        } catch (IOException var4) {
            var4.printStackTrace();
        }
    }
}

}
And the not working one:
////NOT WORKING
public class MyLoggerUtility {
static boolean isExternalStorageAvailable = false;
static boolean isExternalStorageWriteable = false;
static String state = Environment.getExternalStorageState();

public static void addRecordToLog(String var0, String fileName) {
    if ("mounted".equals(state)) {
        isExternalStorageWriteable = true;
        isExternalStorageAvailable = true;
    } else if ("mounted_ro".equals(state)) {
        isExternalStorageAvailable = true;
        isExternalStorageWriteable = false;
    } else {
        isExternalStorageWriteable = false;
        isExternalStorageAvailable = false;
    }

    File var1 = new File("/sdcard/MYPATH/LOG");
    if ("mounted".equals(state)) {
        if (!var1.exists()) {
            Log.d("Dir created ", "Dir created ");
            var1.mkdirs();
        }

        StringBuilder var6 = new StringBuilder();
        var6.append("/sdcard/MYPATH/LOG/");
        var6.append(fileName); ================> USING THIS IT DOES NOT WRITE THE FILE
        var6.append(".txt");
        File var2 = new File(var6.toString());

        if (!var2.exists()) {
            try {
                Log.d("File created ", "File created ");
                var2.createNewFile();
            } catch (IOException var5) {
                var5.printStackTrace();
            }
        }

        try {
            FileWriter var3 = new FileWriter(var2, true);
            BufferedWriter var7 = new BufferedWriter(var3);
            StringBuilder var8 = new StringBuilder();
            var8.append(var0);
            var8.append("\r\n");
            var7.write(var8.toString());
            var7.flush();
            var7.close();
        } catch (IOException var4) {
            var4.printStackTrace();
        }
    }
}

}
I have no idea why this does not works only in Android 11. I have all the permits, as I said it does work with the first example, the problem happens only when using the second one.
If i run the log to watch errors i get the Exception: Operation not permitted.
But it does not make any sense to me because if i use "123" instead of my variable it does create it.
Thank you in advance for everyone who will have a look.
UPDATE: Solved thanks to the user @blackapps, answer in the comments.
I was using ":" character in the file name, it was working up to Android 10 but in Android 11 it caused the file not being created.


text:
Q: Creating styles from Material-UI theme that can be reused across components? In Material-UI 4, one can easily create styles that can be used inside a component. I use the makeStyles() function for this.
const useStyles = makeStyles((theme: Theme) => ({
    hoverableContent: {
        color: theme.palette.primary.contrastText,
        backgroundColor: theme.palette.primary.main,
        '&:hover': {
            backgroundColor: theme.palette.primary.dark
        }
    }
}));

const MyComponent = () => {
    const classes = useStyles();
    ...
}

However, I would like to reuse this style in multiple components. What is the best way to do this in Material-Ui 4?
Note: I think of this as a slightly higher level abstraction: sharing abstract classes (in a controlled way) instead of just colors (in a theme).

A: You could do one of the following:

*

*Share the style between your components

const styles = (theme: Theme) => ({
    hoverableContent: {
        color: theme.palette.primary.contrastText,
        backgroundColor: theme.palette.primary.main,
        '&:hover': {
            backgroundColor: theme.palette.primary.dark
        }
    }
})

This approach then leads to this question. How do you merge multiple styles? https://github.com/mui-org/material-ui/issues/11517

*Generate a global class name and apply it where it makes sense. But be careful with class name conflict and tree-shaking

A: I understand this is a bit late, however i just faced it and solved by making a hook:
// someSharedClasses.ts
export default makeStyles((theme)=>createStyles({
    hoverableContent: {
        color: theme.palette.primary.contrastText,
        backgroundColor: theme.palette.primary.main,
        '&:hover': {
            backgroundColor: theme.palette.primary.dark
        }
    }
}));

And other component:
import useSharedClasses from './someSharedClasses.ts';
const MyComponent = () => {
  const sharedClasses = useSharedClasses();
  // use sharedClasses.hoverableContent as className
}


text:
Q: How do I specify an NSPredicate to match strings that don't start with a letter? This predicate is used to look up CoreData objects based on their title field. I want to fetch any objects that don't start with a letter character (a-z, A-Z).
I have tried this and variations, but I can't get it to work:
[NSPredicate predicateWithFormat:@"%@ MATCHES '^[^a-zA-Z]+.*'", @"title"]

A: Try using %K to use a key path, rather than %@ which uses the value:
[NSPredicate predicateWithFormat:@"%K MATCHES '^[^a-zA-Z].*'", @"title"]

(I also dropped the + modifier as that is unnecessary in your pattern.)
HTH


text:
Q: automatically refit boxcollider2D upon sprite change I have a prefab with a sprite renderer and a boxcollider2D that I use for the bullets in my game.
The sprites I use for each type of bullet are of different sizes and so, when I instantiate a bullet with a different sprite size than the generic bullet from my prefab, the boxcollider doesn't always match the sprite size.
I noticed that when add a boxcollider to my gameobject that it automatically fits the sprite. Is there any way to make this autofit call from the script? Or the only way is to add the collider at runtime?

A: You can auto fit the collider to the size of the sprite like this:
renderer.bounds.size

Which will give you the size of the sprite.
Then you can make the current collider's size accordingly:
 Vector3 v = renderer.bounds.size;

 BoxCollider2D b = collider2D as BoxCollider2D;

 b.size = v;


text:
Q: What is MIP hypothesis? While reading about muon analysis I read that finding calorimetry segments along with the tracks in the silicon tracker for muons helps us find a subset of tracks compatible with the MIP hypothesis. I was looking for what MIP means and all I could find is Minimum Ionizing Particle. Does MIP mean that and what is the MIP hypothesis?

A: The relationship between the energy detected in (a large class of) ionizing detectors and the distance traveled depends a bit on the energy of the particle, but the curve has a valley and is only weakly sensitive to speed in that valley (and the speed of minimum ionization also depends on the particle mass).
The rate of energy deposition for particles at the bottom of the valley is called 'minimum ionization'.
A minimum ionizing particle (MIP) is one that has the speed that generate minimum ionization.
The hypothesis here is that the track length is connected to the detector response by the assumption that the particle's speed is in the valley. So this is a analysis method (rather than a result you are hoping to publish) that works by saying

"Assume [some fact] about the thing we've detected and use that to work out more details, then later we'll look to see if the fit that results is consistent with what we assumed."

And because the minimium ionization valley is pretty broad and a lot of particles are roughly qualified this works out very well.


text:
Q: Double up bit gb-emu Apologies in advance as this is an old topic. I was reading the following post on how the Nintendo logo data is decompressed and scaled before being copied into the v-ram during bootstrap and interestingly enough the data written does indeed look gibberish (as pointed out by the questioner) and I have tried my best (with a gb emulator I wrote) to produce that same output...but without success.
Link to post
The assembly code in question is this part of the boot rom:
LD C,A      ; $0095  "Double up" all the bits of the graphics data
    LD B,$04        ; $0096     and store in Video RAM
Addr_0098:
    PUSH BC     ; $0098
    RL C            ; $0099
    RLA         ; $009b
    POP BC      ; $009c
    RL C            ; $009d
    RLA         ; $009f
    DEC B           ; $00a0
    JR NZ, Addr_0098    ; $00a1
    LD (HL+),A      ; $00a3
    INC HL      ; $00a4
    LD (HL+),A      ; $00a5
    INC HL      ; $00a6
    RET

In reply to above post the output to v-ram is show to be:
8000: 00000000000000000000000000000000
8010: F000F000FC00FC00FC00FC00F300F300
8020: 3C003C003C003C003C003C003C003C00
8030: F000F000F000F00000000000F300F300
8040: 000000000000000000000000CF00CF00
... and so on

Can anyone explain how this output is generated and if it is indeed correct?
Many thanks in advance.
P.S. Assumption is made that the Nintendo logo is explicitly (inside some C/Java code) copied over to v-ram starting at address 0104h during boot process to test the bootstrap.
.DB $CE,$ED,$66,$66,$CC,$0D,$00,$0B,$03,$73,$00,$83,$00,$0C,$00,$0D
.DB $00,$08,$11,$1F,$88,$89,$00,$0E,$DC,$CC,$6E,$E6,$DD,$DD,$D9,$99
.DB $BB,$BB,$67,$63,$6E,$0E,$EC,$CC,$DD,$DC,$99,$9F,$BB,$B9,$33,$3E

A: After going through my code and seeing a potential silly bug (maybe a couple or two) I was able to finally get the same result as above. Please consider this resolved.
Basically I was forgetting to update the F register after the settings were changed for INC n, Add n and Sub n.
So technically, the above output seems to be correct.


text:
Q: Can I add elements to the aps payload sent by the Bluemix IBM Push Notifications service? I'm successfully using Bluemix Push to send notifications via the REST interface to an iOS app with a simple string alert message.  That works fine.
Now I would like to send a more complex message where alert is a dictionary and has a sibling "category" element per The Remote Notification Payload.
Is this possible with Bluemix Push? Whenever I try to deviate from the basic structure, I get "Bad Request - Invalid JSON".

A: After much head-scratching, I finally picked up a hint from https://www.ng.bluemix.net/docs/services/mobilepush/t_advanced_notifications.html#t_push_badge_sound_payload and figured out that since the category field is unique to APNS, what I needed to send is
    "settings" : {
        "apns"   : {
            "category" : "myCategory"
        }

A: @DSchultz_mo I was having issues to find the documentation but I finally found it, so if you go to https://mobile.ng.bluemix.net/imfpushrestapidocs/#/ you can use swagger to register your device and send notification and the  magic button is  in model there is more details for sendMessageBody


text:
Q: Making the sidebars\page of even size So, I'm making a page with 2 simple sidebars, one on the left and one on the right. The problem is, the sidebar have an height depending on its content, same is for the page. So, if the page content is shorter than the sidebar content, it will not display a single rectangle\square but it will display a sidebar rectangle longer than the page. On the other side, if the page content is longer than the sidebar, it will extend the rectangle and also "extends" the sidebar whitespace, but, that whitespace is of the page and not of the sidebar. The struct of the page is like that:

A: Use display:inline-block; and Width
Demo Here

#sidebar1{
  display:inline-block;
  width:24%;
  background:red;
  height: 300px;
}

#sidebar2{
   display:inline-block;
   width:24%;
    background:blue;
  height: 300px;
}

#pageContent{
   display:inline-block;
   width:50%;
    background:green;
  height: 300px;
}


text:
Q: I am getting error when placing below code in wordpress theme function file to change canonical URL in mass using Yoast SEO plugin Your PHP code changes were rolled back due to an error on line 35 of file wp-content/themes/Newspaper/functions.php. Please fix and try saving again.
syntax error, unexpected ' ' (T_STRING)
==================================================
and I am using this code for mass changes in canonical URLs:

// Batch Change Canonical URLs
function change_canonical($url) {
    global $post;

    if ( is_singular( 'post' ) ) {
         return 'https://templeshistory.in/' . $post->post_name;
    } else {
         return $url;
    }
}
add_filter( 'wpseo_canonical', 'change_canonical' );

If this code is wrong can you please provide me the right code for these changes in canonical URLs of all post pages.


text:
Q: Workign with floating
* elements in footer My website is on the local server right now however this will be a simple fix for those of you who know whats it's called.
I'm trying to get these lists (bordered in white) to float the the far left in the available space of the footer(bordered by black).

This is my CSS
#footer { width: 100%; height: 503px; background: url(img/FOOTER-bg.jpg) repeat-x; background-color: #821d20; position: relative; top: 100px;/*border: 1px solid #0C0;*/}
#footer a { text-decoration: underline; color: #c7bd89; }
#footer a:hover { text-decoration: none; color: #fff; }

#footer h6 { background: url(img/FOOTER-HR-BG.jpg) left center repeat-x; text-align: left;}
#footer h6 span { background: #8e2023; display: inline-block; padding-right: 5px; }

.footer-widgets { width: 960px; height: 503px; margin: 0px auto; padding: 0px; border: 1px solid #000;}
.footer-widgets li { width:280px; height: auto; list-style-image: none; list-style-position: outside; list-style-type: none; float: left; color: #fff; padding: 13px; margin-right: 10px; /*border: 1px solid #fff;*/ }
.footer-widgets li ul {color: red;}
.footer-widgets li ul li {color: #fff; margin-left: -50px; margin-top: -15px;}
.footer-widgets li p { font-size: 1em; line-height: 18px; text-align: left; /*border: 1px solid red;*/  }
.footer-widgets li h2 { font-size: 1.4em; font-weight: normal; letter-spacing: 1px; line-height: 30px; text-align: left;}
.footer-archives { position: relative; top: -210px;}
.footer-widgets li.last { position: relative; top: -210px;}

h6 { font-family:Verdana, Geneva, sans-serif; font-size: 1.2em; font-weight: normal; letter-spacing: 1px; margin-top: 15px; margin-bottom: 10px; color: #fff;}

.footer-copyright { position: absolute; width: 900px; left: 50%; margin-left: -450px; top: 400px; height: 100px; font-family: Tahoma, Geneva, sans-serif; line-height: 22px; font-size: 1em; color: #fff; text-align: center; text-transform: uppercase; }
.footer-copyright a { color: #fff !important; text-decoration: none !important; }
.footer-copyright a:hover { color: #c7bd89; text-decoration: underline !important; }

.copyright { margin-top: 27px; text-transform: uppercase; display: block; color: #cc9798;}
.copyright a { color: #cc9798 !important; text-decoration: underline; }

.footer-one, .footer-two, .footer-three, .footer-four { border: 1px solid #fff; float: left;}

I have the containing footer and within the 900px x 503px container I wish that all lists float left (and under each other if it's small enough). So "Archives" would flow under "Follow Us" and if I were to put a search bar under "Testimonials" it would fit.
What can I do with my CSS to have this happen?

A: Why no just create a column for each side (left, center, right) and simulate it that way, well atleast I think this is what you are trying to achieve
Fiddle http://jsfiddle.net/eEwdk/
Theres another workaround that would consist in making each li element absolute positioned and calculating it's position (yeah I know it's sound redundant)

A: As I understand it, you want each of the li elements underneath one another.  To do that you want to float the ul element to the left, not each individual li element.


text:
Q: Bootstrap navigation menu opens normally but refuses to close I am making a counter-part of an original HTML file in NuxtJS, I have the following code in the Navbar component for my NuxtJS project
<template>

          Bitflow

        <button
          class="navbar-toggler"
          type="button"
          data-toggle="collapse"
          data-target="#navbarSupportedContent"
          aria-controls="navbarNavAltMarkup"
          aria-expanded="false"
          aria-label="Toggle navigation"
        >

        </button>

              Mission

              Works

              Team

</template>

This is the useful chunk in the nuxt.config.js file
css: [
    '@/assets/css/fontawesome.min.css',
    '@/assets/font-awesome-brands/css/brands.min.css',
    '@/assets/themify/css/themify-icons.css',
    '@/assets/tether/tether.min.css',
    '@/assets/bootstrap/css/bootstrap.min.css',
    '@/assets/bootstrap/css/bootstrap-grid.min.css',
    '@/assets/bootstrap/css/bootstrap-reboot.min.css',
    '@/assets/animatecss/animate.css',
    '@/assets/dropdown/css/style.css',
    '@/assets/formstyler/jquery.formstyler.css',
    '@/assets/formstyler/jquery.formstyler.theme.css',
    '@/assets/socicon/css/styles.css',
    '@/assets/theme/css/style.css',
    '@/assets/mobirise/css/mbr-additional.css',
    '@/assets/web/assets/mobirise-icons2/mobirise2.css'
  ],

And finally the links to the javascript files in the index.vue file


text:
Q: How to use filter hook "the_posts" with a function that refers to $this? I'm using Carbon Fields to manage event-related metadata (such as event dates) for certain posts on my site, but I want to make sure that past events do not show up in my site's feeds. I need to use the filter the_posts with a function. Here is my code:
add_filter("the_posts", "filter_past_events");

function filter_past_events($posts) {
    if ($this->is_single) {
        return $posts;
    }
    if ($this->is_feed) {
        for ($i = count($posts) - 1; $i > -1; $i--) {
            $event_meta = carbon_get_post_meta($posts[$i]->ID, "event_meta");
            if ($event_meta) {
                $is_future = false;
                if (!empty($event_meta[0]["scheduling_blocks"])) {
                    $scheduling_blocks = $event_meta[0]["scheduling_blocks"];
                    for ($j = 0; $j < count($scheduling_blocks); $j++) {
                        if (DateTimeImmutable::createFromFormat("m/d/Y H:i:s", $scheduling_blocks[$j]["start"]) > new DateTimeImmutable()) {
                            $is_future = true;
                        }
                    }
                }
                if (!$is_future) {
                    array_splice($posts, $i, 1);
                }
            }
        }
    }
    return $posts;
}

I am getting Fatal error: Too few arguments to filter_past_events(), 1 passed. What am I doing wrong? Has WordPress stopped passing the WP_Query object $this to the function?

A: As you can see in the documentation, the 2nd argument passed to functions hooked to the_posts is the WP_Query object.
To access it you need to define the 4th argument of add_filter(), $accepted_args, to 2, so that you can accept it.
Then you just need to accept 2 arguments in your function, and use the 2nd argument to as the WP_Query object:
function wpse_313327_filter_past_events( $posts, WP_Query $query ) {
    if ( $query->is_single() ) {
        return $posts;
    }

    if ( $query->is_feed() ) {
        // etc. etc.
    }

    return $posts;
}
add_filter( 'the_posts', 'wpse_313327_filter_past_events', 10, 2 );


text:
Q: Unable to open file that was apparently saved as a list attachment One of our users is reporting not being able to find a word file. I followed the link to the library, and it's an empty list. I used the following link: .SharePoint.com/Sites//lists//attachments/16.
I expected some files to be here but It's empty. the error message:

It's in Dutch, but basically says "the file could not be found. Was it renamed or moved or deleted?"
Any ideas?


text:
Q: Create checkboxes with icons inside circles I would like some help over something thats driving me nuts so hard hahaha. So I have this checkboxes like this:

So, I have this design that my UX & UI colleague made for this project that I need something similar to this:

As you can see in the image above, I need to implement something where there`s no checkboxes and at the moment I select an Icon a color blue must show on the border as letting the user know that option has been selected.
The resource Im using for this is materializeCSS check boxes and my current CSS is the below:
/*Checkboxes*/
[type="checkbox"]:checked + span:not(.lever):before {
    top: -4px;
    left: -5px;
    width: 12px;
    height: 22px;
    border-top: 2px solid transparent;
    border-left: 2px solid transparent;
    border-right: 2px solid #2372bd;
    border-bottom: 2px solid #2372bd;
    -webkit-transform: rotate(40deg);
    transform: rotate(40deg);
    -webkit-backface-visibility: hidden;
    backface-visibility: hidden;
    -webkit-transform-origin: 100% 100%;
    transform-origin: 100% 100%;
}

/*Checkboxes*/
[type="checkbox"] + span:not(.lever):before, [type="checkbox"]:not(.filled-in) + span:not(.lever):after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 18px;
    height: 18px;
    z-index: 0;
    border: 2px solid #888888;
    border-radius: 1px;
    margin-top: 3px;
    -webkit-transition: .2s;
    transition: .2s;
}

//This are the current circles that wrapps the icons
.services-circle{
  border: 1px solid #858585;
  width: 45px;
  margin-top: 10px;
  margin-bottom: 20px;
  height: 45px;
  border-radius: 50%;
}

//Current HTML

     fireplace
      <input name="property[services_attributes][0][gas]" type="hidden" value="0"><input
 type="checkbox" value="1" name="property[services_attributes][0][gas]"
 id="property_services_attributes_0_gas">
     Gas

NOTE: If I select the icon or circle it gets checkboxed, so I guess thats nice

So, is there's some cool resource out there in the lost internet to do something like this? Or if have some basic code where pushes me to achieve something like this, that would be awsome! I will appreciate your help!

A: Set the checkboxes to display: none;


text:
Q: What does the phrase "contrasted coordinate elements" mean?

*Use a comma near the end of a sentence to separate contrasted coordinate elements or to indicate a distinct pause or shift.

What does "contrasted coordinate elements" mean?
Source: owl.purdue.edu


text:
Q: Short hand for [[UIApplication sharedApplication] delegate]? I stored global variables in my AppDelegate and access them by:
AppDelegate *d = [[UIApplication sharedApplication] delegate];
d.someString = ...

What's the recommend way to save some typing and so I don't need to AppDelegate *d = [[UIApplication sharedApplication] delegate]; again and again? Thanks!

A: You could just create a C-style macro and put it in a header file somewhere.
(As for using your app delegate as a giant global variable catch-all, that's another rant for another day.)

A: As Shaggy Frog said, define a macro in your YourAppDelegate.h file, an example like this:
#define AppDelegate (YourAppDelegate *)[[UIApplication sharedApplication] delegate]

Then you can get the app delegate in your code like this:
[AppDelegate ......];

A: I create a category called UIApplication+delegate with some convenience messages in it.  Getting my specific delegate being one of the convenience messages.  So, for instance, if my app delegate was called MyAppDelegate, it would look like this:
UIApplication+delegate.h
#import "MyAppDelegate.h"

@interface UIApplication(delegate)
+ (MyAppDelegate *)thisApp;
@end

and UIApplication+delegate.m
#import "UIApplication+delegate.h"

@implementation UIApplication(delegate)

+ (MyAppDelegate *)thisApp {
    return (MyAppDelegate*)[[UIApplication sharedApplication] delegate];
}

@end

In a class that needs the delegate, I do this:
#import "UIApplication+delegate.h"

...

- (void)doStuff {
    MyAppDelegate *app = [UIApplication thisApp];
    // use "app"
}

A: I also created a category, except that I applied mine to NSObject so any object in the application can easily get to the delegate.

#import "MyAppDelegate.h"

@interface NSObject(delegate)
- (MyAppDelegate *) appDelegate;
@end

#import "NSObject+delegate.h"

@implementation UIApplication(delegate)

- (MyAppDelegate *)appDelegate {
    return (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
}

@end

A: Since your app delegate never really changes, you can create an external that you define in the app delegate code, very similar to the NSApp external for Mac OS X Cocoa applications.
So, define the external in your AppDelegate header (or something else that you would include everywhere):
extern AppDelegate* appDelegate;

Then create it and set it in your implementation file:
AppDelegate* appDelegate = nil;

// later -- i can't recall the actual method name, but you get the idea
- (BOOL)applicationDidFinishLaunchingWithOptions:(NSDictionary*)options
{
  appDelegate = self;
  // do other stuff
  return YES;
}

Then other classes can just access it:
#import "AppDelegate.h"

// later
- (void)doSomethingGreat
{
  NSDictionary* mySettings = [appDelegate settings];
  if( [[mySettings objectForKey:@"stupidOptionSet"] boolValue] ) {
    // do something stupid
  }
}


text:
Q: AJAX error when passing a variable to a PHP file How my page works:

*

*The quiz php page loads and the user generates a score with a function inside quiz.js. The score is then saved in a variable score inside quiz.js

*After generating the score, the user has to press a button to go to the next question in the quiz inside the same page. Pressing the button would send the score to my database with a sql query I have in sendData.php, without reloading the page.

My button looks like this:
<form id="sendData" action="sendData.php" method="post">
  <button type="submit" name="send" onclick="sendAjax()">Send</button>
</form>

sendData.php is already finished and working, but for some reason, sendAjax() doesn't work at all:
function sendAjax() {
  $.ajax({
    url:  "sendData.php",
    type: "POST",
    data: {
      score: score,
      numQuiz: numQuiz
    },
    success: function() {
      alert("Data succesfully sent");
    },
    error: function() {
      alert("There has been an error");
    }
  })
}

And my PHP file being like this:
if (isset($_POST['score']) and isset($_POST['numQuiz'])) {
    $score = $_POST['score'];
    $numQuiz = $_POST['numQuiz'];
    // SQL query and stuff goes here
}

But it seems that $_POST['score'] and $_POST['numQuiz'] aren't set. Also, I can see the error pop up inside sendAjax before it loads the PHP file. I've tried adding to the form the attribute action="" but it doesn't work either.

A:
<form id="sendData" action="sendData.php" method="post">
  <button type="submit" name="send" onclick="sendAjax()">Send</button>
</form>

You're running the JS when you click a submit button in a form.
So the JS runs, then the browser immediately navigates to a new page (submitting the form, with no data in it, to the PHP) and the XMLHttpRequest object is destroyed before it receives a response.
You then see the result of the standard form submission.
If you just want a button to trigger some JavaScript, then use a non-submit button (<button type="button"), and don't put it in a form.
Better yet:

*

*switch away from onclick attributes (they have a variety of issues) in favour of addEventListener providing a submit event listener on the form

*Use preventDefault() to stop the form submission when the JS is successful

*Put form controls in the form so it submits useful data when the JS isn't successful

i.e. write Unobtrusive JavaScript then provides Progressive enhancement.

A: Two things:
You need to tell jQuery to use the application/json content-type:
function sendAjax() {
  $.ajax({
    url:  "sendData.php",
    type: "POST",
    contentType: 'application/json',
    dataType: 'json',
    data: {
      score: score,
      numQuiz: numQuiz
    },
    success: function() {
      alert("Data succesfully sent");
    },
    error: function() {
      alert("There has been an error");
    }
  })
}

PHP's $_POST variable is not populated as you think it is as the payload is not urlencoded as is standard with say a form submit. So we can parse the JSON payload (body) ussing:
$myData = json_decode(file_get_contents("php://input"));
var_dump($myData->score);


text:
Q: Turtle graphics color detection Is there any way to detect the color that the turtle is standing on in python?
For example if the the turtle is on a black colored space, he moves forward.

A: Quickly glancing over the turtle documentation, nope, there's no way to detect colors.
You should probably keep a record of which spaces you have drawn so far, adding to the collection whenever you draw a new space. Then, when you want to know the color of an old space, you only need to search through the collection.
What collection you ought to use depends on what kind of spaces we're talking about here. If the spaces are nice tessellated squares, like a chessboard, you could probably get away with a dictionary whose keys are (row,col) coordinate tuples.


text:
Q: Flutter: is calling setState() multiple times inefficient? Lets say I have a method onButtonPressed() which calls method a() and then method b(). Both methods a() and b() contain a call to setState():
void onButtonPressed() {
    ...
    a();
    ...
    b();
}

void a() {
    ...
    setState() {
        ...
    }
}

void b() {
    ...
    setState() {
        ...
    }
}

Does calling setState() twice cause the affected components to be rendered twice, or is Flutter optimized so that the components only get rendered once?

A: If all of your setState calls happen within the same frame, then there's no issue.
The widget will rebuild once and only once.
Once a widget is marked as needing build, all subsequent calls to setState will do nothing but call the callback until a frame is scheduled and the build is done.

A: There is a tiny overhead that every call to a function call cost, but this is negligible.
This does not cause an additional overhead from or for the framework.

A: You could do this
void onButtonPressed() {
  ...
  a();
  ...
  b();
  setState((){});
}

So you are calling setState in only one place


text:
Q: getMaximumSize() for dual screen if you have a dual screen computer, how do I make my program open to fill the screen just on my main monitor? If I use the getMaximumSize() method, it extends to my second screen?
frame.setSize(frame.getMaximumSize());

A: You can get the size from the graphics configuration.
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;

public class GuiScreens {
    public static void main(String[] args) {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice[] gs = ge.getScreenDevices();
        GraphicsConfiguration[] gc = gs[0].getConfigurations();
        System.out.println("    Bounds: " + gc[0].getBounds());
   }
}

A: You can use Toolkit#getScreenSize() to determine the screen size, and set the frame to that size


text:
Q: Multiple owners for Rust list elements (list owner and several referrers) - possible? We have a struct with a LinkedList:
struct XPipeline {
    handlers: LinkedList<XHandler>,
}

XPipeline is the owner of all XHandler objects and can access and modify them.
We already have the list of handlers; now we need that each handler could refer to its neighbors in the list. Namely, each handler's method could refer to handler's neighbors, modify them and invoke their methods.
My first thoughts were like this: I provide each handler with prev and next fields that will refer to neighbors. By adding a new handler into the list, I initialize these fields with corresponding references. Now I can use these references within all handler's methods. (That would be easy-peasy in C++ with pointers).
The problem is: only one owner (i.e. with modification permission) is allowed. And that owner (of all handlers) is already a XPipeline object. How could I solve it? Maybe, by employing:
handlers: Rc<RefCell<LinkedList<XHandler>>>

But how exactly?

A: One of the strategies in Rust for multiple links in data structures is to use a Vec<T> as the backing storage and then index into it with usize "pointers".
Your case would look something like:
struct XPipeline {
    head: usize,
    storage: Vec<Node>,
}

struct Node {
    handler: XHandler,
    next: Option<usize>,
    prev: Option<usize>,
}

The bookkeeping is very similar to the pointers you would use in C++.
Also have a look at this discussion on Reddit for ways to deal with ownership in graph-like structures.
I would also just look for crates that implement double linked lists, skip lists, graphs or similar and take inspiration from there.


text:
Q: Can't connect to mySQL localhost server I have 2 computers on my LAN. 1 is a Linux Ubuntu server with mySQL installed that I am attempting to remotely connect to via mySQL workbench from my other computer, a windows PC. I have already created a dba user account pointing towards my windows IP to allow remote log in, given privileges and flushed them, ect... But I am getting the error "Unable to connect to localhost" when trying to make the connection. Some things I've considered... Because both computers are on my LAN I believe I do not need to edit the mysqld.cnf file's bind-address. I've tried changing the "hostname" section on workbench to 127.0.0.1, the IPv4 of the Linux server, and the name of the Linux server all giving the same error. Do I possibly need to install mySQL on the Windows PC even though I already have workbench? Do I need to change my windows PC network settings to 'private' rather than 'public'? That seems unlikely since they're already localhost anyways. Do I need to port forward my mySQL? Again seems unlikely because it's just a localhost connection. Do I need to make both computers have static IP's? Although since I haven't turned either of them off the IP's have not been changed by DHCP so I believe that shouldn't matter for the initial connection attempt. Any ideas?

A: 127.0.0.1 "localhost" refers to literally that - the local host, and is never going to work to address one machine to another. if your computers are networked together they should have another IP probably starting with 192.168, 10., or 172.. No, you don't need static IPs ; chances are on a home network they will not change. You need to make sure mysql is listening on an address other than localhost / 127.0.0.1 - very likely you will need to change the bind-address. 0.0.0.0 is a fine choice here for controlled networks. I don't believe windows networking settings are relevant