text:
Q: Need help making button relay information Okay, so I have made a GUI with some input boxes and a combo box. I am wondering how I would go about having a listener know when the button is pressed then relay all the information in the imput boxes and combo box into different parts of the script...
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

    public class dogedice extends JFrame implements ActionListener {
        private static final long serialVersionUID = 1L;
        private JPanel contentPane;
        private JTextField textField;
        private JComboBox combo;

        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    try {
                        dogedice frame = new dogedice();
                        frame.setVisible(true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        public dogedice() {
            setTitle("DogeDice Bot");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            contentPane = new JPanel();
            contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
            contentPane.setLayout(new BorderLayout(0, 0));
            setContentPane(contentPane);

            JPanel panel = new JPanel();
            contentPane.add(panel, BorderLayout.WEST);
            GridBagLayout gbl_panel = new GridBagLayout();
            gbl_panel.columnWidths = new int[]{0, 0};
            gbl_panel.rowHeights = new int[]{0, 0};
            gbl_panel.columnWeights = new double[]{0.0, 1.0};
            gbl_panel.rowWeights = new double[]{0.0, Double.MIN_VALUE};
            panel.setLayout(gbl_panel);

            //Every new Label however needs every part that says "user" or on the Password: "pass" changed to something unique.
            JLabel userTag = new JLabel("Username:");
            GridBagConstraints gbc_userTag = new GridBagConstraints();
            gbc_userTag.insets = new Insets(0, 0, 0, 5);
            gbc_userTag.anchor = GridBagConstraints.EAST;
            gbc_userTag.gridx = 0;//Here are your x + y coords
            gbc_userTag.gridy = 0;//Adding to x moves left, adding to y moves down
            panel.add(userTag, gbc_userTag);

            //Every new textfield needs only the * part to change for it to be valid. (gbc_* =)
            textField = new JTextField();
            GridBagConstraints gbc_Username = new GridBagConstraints();
            gbc_textField.fill = GridBagConstraints.HORIZONTAL;
            gbc_textField.gridx = 1;
            gbc_textField.gridy = 0;
            panel.add(textField, gbc_textField);
            textField.setColumns(10);

            JLabel startTag = new JLabel("Starting Bid:");
            GridBagConstraints gbc_startTag = new GridBagConstraints();
            gbc_startTag.insets = new Insets(0, 0, 0, 5);
            gbc_startTag.anchor = GridBagConstraints.EAST;
            gbc_startTag.gridx = 0;
            gbc_startTag.gridy = 2;
            panel.add(startTag, gbc_startTag);

            textField = new JTextField();
            GridBagConstraints gbc_StartBid = new GridBagConstraints();
            gbc_textField.fill = GridBagConstraints.HORIZONTAL;
            gbc_textField.gridx = 1;
            gbc_textField.gridy = 2;
            panel.add(textField, gbc_textField);
            textField.setColumns(10);

            JLabel multTag = new JLabel("Multiplier:");
            GridBagConstraints gbc_multTag = new GridBagConstraints();
            gbc_multTag.insets = new Insets(0, 0, 0, 5);
            gbc_multTag.anchor = GridBagConstraints.EAST;
            gbc_multTag.gridx = 0;
            gbc_multTag.gridy = 3;
            panel.add(multTag, gbc_multTag);

            textField = new JTextField();
            GridBagConstraints gbc_Multiplier = new GridBagConstraints();
            gbc_textField.fill = GridBagConstraints.HORIZONTAL;
            gbc_textField.gridx = 1;
            gbc_textField.gridy = 3;
            panel.add(textField, gbc_textField);
            textField.setColumns(10);

            JLabel minTag = new JLabel("Min Remaining:");
            GridBagConstraints gbc_minTag = new GridBagConstraints();
            gbc_minTag.insets = new Insets(0, 0, 0, 5);
            gbc_minTag.anchor = GridBagConstraints.EAST;
            gbc_minTag.gridx = 0;
            gbc_minTag.gridy = 4;
            panel.add(minTag, gbc_minTag);

            textField = new JTextField();
            GridBagConstraints gbc_MinRemaining = new GridBagConstraints();
            gbc_textField.fill = GridBagConstraints.HORIZONTAL;
            gbc_textField.gridx = 1;
            gbc_textField.gridy = 4;
            panel.add(textField, gbc_textField);
            textField.setColumns(10);

            textField = new JTextField();
            GridBagConstraints gbc_Password = new GridBagConstraints();
            gbc_textField.fill = GridBagConstraints.HORIZONTAL;
            gbc_textField.gridx = 1;
            gbc_textField.gridy = 1;
            panel.add(textField, gbc_textField);
            textField.setColumns(10);

            JLabel passTag = new JLabel("Password:");
            GridBagConstraints gbc_passTag = new GridBagConstraints();
            gbc_passTag.insets = new Insets(0, 0, 0, 5);
            gbc_passTag.anchor = GridBagConstraints.EAST;
            gbc_passTag.gridx = 0;
            gbc_passTag.gridy = 1;
            panel.add(passTag, gbc_passTag);

            textField = new JTextField();
            GridBagConstraints gbc_Odds = new GridBagConstraints();
            gbc_textField.fill = GridBagConstraints.HORIZONTAL;
            gbc_textField.gridx = 1;
            gbc_textField.gridy = 5;
            panel.add(textField, gbc_textField);
            textField.setColumns(10);

            JLabel oddsTag = new JLabel("Odds %:");
            GridBagConstraints gbc_oddsTag = new GridBagConstraints();
            gbc_oddsTag.insets = new Insets(0, 0, 0, 5);
            gbc_oddsTag.anchor = GridBagConstraints.EAST;
            gbc_oddsTag.gridx = 0;
            gbc_oddsTag.gridy = 5;
            panel.add(oddsTag, gbc_oddsTag);

            textField = new JTextField();
            GridBagConstraints gbc_ComboBox = new GridBagConstraints();
            gbc_textField.fill = GridBagConstraints.HORIZONTAL;
            gbc_textField.gridx = 1;
            gbc_textField.gridy = 6;
            panel.add(textField, gbc_textField);
            textField.setColumns(10);

            //This is the Combo Box
            combo = new JComboBox<String>(new String[]{"BTC","LTC","PPC","NMC","XPM","FTC","ANC","DOGE","NXT"});
            combo.addActionListener(this);
            GridBagConstraints gbc_list = new GridBagConstraints();
            gbc_list.fill = GridBagConstraints.HORIZONTAL;
            gbc_list.gridx = 1;
            gbc_list.gridy = 7;
            panel.add(combo, gbc_list);

            JLabel maxTag = new JLabel("MaxBet:");
            GridBagConstraints gbc_maxTag = new GridBagConstraints();
            gbc_maxTag.insets = new Insets(0, 0, 0, 5);
            gbc_maxTag.anchor = GridBagConstraints.EAST;
            gbc_maxTag.gridx = 0;
            gbc_maxTag.gridy = 6;
            panel.add(maxTag, gbc_maxTag);

            JPanel panel_1 = new JPanel();
            contentPane.add(panel_1, BorderLayout.SOUTH);
            panel_1.setLayout(new FlowLayout(FlowLayout.RIGHT, 5, 5));

            JButton btnConfirm = new JButton("Turn Up");
            panel_1.add(btnConfirm);

        JScrollPane scrollPane = new JScrollPane();
            contentPane.add(scrollPane, BorderLayout.CENTER);
            JTextArea textArea = new JTextArea("Current Balance");
            textArea.setColumns(1);
            scrollPane.setViewportView(textArea);

        JScrollPane scrollPanel = new JScrollPane();//This will hold the information the bot sends over such as win/loose or error
            contentPane.add(scrollPane, BorderLayout.CENTER);
            JTextArea textAreal = new JTextArea("Input bot information here...");
            textArea.setColumns(20);
            scrollPane.setViewportView(textArea);

            pack();
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == combo) {
                System.out.println(combo.getSelectedIndex()+1);
            }
        }

    }

A: It's quite straightforward to add an ActionListener to a JButton.
// ...
btnConfirm = new JButton("Turn Up");
btnConfirm.addActionListener(this);
panel_1.add(btnConfirm);
// ...

Because you'll want to know when the button is triggering the callback, like so:
private JButton btnConfirm;

This way, you'll be able to tell when it's that button that triggered the actionListener() method:
if (event.getSource() == btnConfirm) {
    // Handle "Turn Up" button press here
}

A: Start by taking a look at How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listener
Essentially you need to register an ActionListener with your button...
There are a number of ways you might be able to achieve this...
You Could
Use the more traditional, purpose class...
public class ActionHandler implements ActionListener {
    public void actionPerformed(ActionEvent evt) {
        if ("Turn Up".evt.getActionCommand()) {
            // Handle Turn Up...
        }
    }
}

In this context, you'll be required to provide a reference to the component you want to modify so that the ActionHandler can interact with it, personally, this is best done via an interface, but that's just me...
public class ActionHandler implements ActionListener {
    private dogedice dice;
    public ActionHandler(dogedice dice) {
        this.dice = dice;
    }
    public void actionPerformed(ActionEvent evt) {
        //...
    }
}

The benefit of this is you can plug an play the action handler, changing what the action does depending on your needs. If you use an interface instead of an implementation reference, you further decouple the action from the program
You Could
Use use an anonymous class
btnConfirm = new JButton("Turn Up");
btnConfirm.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        // handle turn up action...
    }
});

The benefit to this is, you don't end up with "another" class, the ActionListener can reference all the internal fields of the parent class and, because you've attached it directly, you can assume that the only thing that is going to generate the ActionEvent is the btnConfirm button.
The downside is you lose the flexibility to change how the action is handled without physically modifying the code
You Could
Take advantage of the Actions API, this is a little like the first option, in that you (should normally) create another class specifically designed to handle the "Turn Up" event, but these are self contained entities.  That is, they carry all the information required to configure the UI element and perform the required action when triggered.
This is really good where the action may be repeated in the UI via menus, buttons or key strokes


text:
Q: How to subscribe/unsubscribe each server in an auto-scaling group to SNS We are using Elastic Beanstalk to serve a REST API. Now, I want to develop an endpoint that serves notifications from an SNS-topic in an asynchronous way.
In order to receive those notifications, I need to subscribe the API-servers to the SNS-topic. How could I do this, with the scenario in mind that the EBS application can scale up to multiple servers and scale down again? I don't want a lot of dead links subscribed to the SNS-topic...

A: In spring world we have a @PostConstruct which gets called on server startup, where you can subscribe "this.server" url to a given topic (you may need to build a proper working subscription url --using InetAddress et el).
Hence there is the working subscribe url using @RestController which confirms such an subscription instantaneously causes sns endpoint to be registered. Any new servers will do the same aka getting registered themselves (when new stack is created). We also need additional code for the consumption of notification messages subsequently and do something when confirmed subscription endpoints receive one.

A: The way AWS wants you to use SNS is not by directly subscribing to it. Any notification which need to trigger something in a component should buffer notifications with an SQS queue. For this reason we chose to do Pub-Sub with a variable/scalable group of Subs using the Amazon managed Redis distribution.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Manipulating SQL string result table I'm trying to change the result set so that the OriginalName column string is rewritten to the output table. There are 2 scenarios id like to change this string according to:

*

*Reading the OriginalName from left to right IF the first date value found is in the form YYYYMMDD then trim everything from the right and append .txt

*

*For example, for OriginalName := "TPV02002_KBA_HOUSE_Daily_Claims_20221009_221010091706003.txt"
Id want the output result to be changed to TPV02002_KBA_HOUSE_Daily_Claims_20221009.txt

*Same change but instead IF is the first date format seen YYYY-MM-DD

*

*For example, for OriginalName := "TPV00165_Paid Claims 2022-10-09_221010080406124.txt"

*Desired output "TPV00165_Paid Claims 2022-10-09.txt"
SELECT
    RXInboundFileQueue.OriginalName,
    'rx' AS Filetype,
    RXInboundFileQueue.FileCatalogedOn

FROM
    EDIPlatform.dbo.RXInboundFileQueue

WHERE
    FileCatalogedOn >= DATEADD(DAY, -7, GETDATE())

ORDER BY
    OriginalName DESC,
    FileCatalogedOn

A: If your data is indeed that regular, just STUFF() the extraneous numerals with an empty string:
SELECT
    RXInboundFileQueue.OriginalName,
    STUFF(
        RXInboundFileQueue.OriginalName,
        LEN(RXInboundFileQueue.OriginalName)-19,
        16,
        ''
    ) AS OriginalNameFormatted,
    'rx' AS Filetype,
    RXInboundFileQueue.FileCatalogedOn

FROM
    EDIPlatform.dbo.RXInboundFileQueue

WHERE
    FileCatalogedOn >= DATEADD(DAY, -7, GETDATE())

ORDER BY
    OriginalName DESC,
    FileCatalogedOn

If the data gets more irregular, research regular expressions and pattern matching.

A: SELECT RXInboundFileQueue.OriginalName OldOriginalName
,SUBSTRING(RXInboundFileQueue.OriginalName, 0,
LEN(RXInboundFileQueue.OriginalName) - CHARINDEX('_',
REVERSE(RXInboundFileQueue.OriginalName), 0) + 1) + '.txt'
NewOriginalName
FROM EDIPlatform.dbo.RXInboundFileQueue
WHERE FileCatalogedOn >= DATEADD(DAY, -7, GETDATE())

A: A couple of approaches:
SELECT Q.OriginalName, U.UpdatedName, U.UpdatedName2, C.*
FROM EDIPlatform.dbo.RXInboundFileQueue Q
CROSS APPLY (
    SELECT
        pos1 = CHARINDEX('.', REVERSE(Q.OriginalName)),
        pos2 = CHARINDEX('_', REVERSE(Q.OriginalName)),
        pos3 = PATINDEX('%[.][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][_]%', REVERSE(Q.OriginalName))
) C
CROSS APPLY (
    SELECT
        UpdatedName =
            CASE WHEN pos1 > 0 AND pos2 > pos1
            THEN REVERSE(STUFF(REVERSE(Q.OriginalName), pos1 + 1, pos2 - pos1, ''))
            ELSE Q.OriginalName
            END,
        UpdatedName2 =
            CASE WHEN pos3 > 0
            THEN REVERSE(STUFF(REVERSE(Q.OriginalName), pos3 + 1, 16, ''))
            ELSE Q.OriginalName
            END
) U

The first just looks at the delimiters. The second looks for the specific sequence of underscore + 15 digits + dot.
See this db fiddle.


text:
Q: How to set your default value in a constructor of iterators? C++ I'm doing a constructor for my iterator but I can't figure what's the default value
here's the declaration :
const_iterator(typename map<TYPE, TYPE2>::const_iterator = ????? );
It's a vector of maps, so my iterator will be a map iterator.
What would be the default value?
Cause when I do :
HashMap<TYPE, TYPE2>::const_iterator i;
It says that I have no appropriate default constructor.
Thank you!

A: Not going into why you would need a default value, I would suggest to use the default value of the map iterator (which is an invalid iterator)
 typedef typename map<TYPE, TYPE2>::const_iterator map_citer;
 const_iterator(map_citer param = map_citer());
                                //^^^^^^^^^^^

Edit:
Considering your edit, it seems that most logical in your situation would be to overload your constructor. Have two overloads, one that doesn't take anything (do what you think is best in that constructor) and your original one. That should do the trick :)
const_iterator(typename map<TYPE, TYPE2>::const_iterator);
const_iterator();


text:
Q: Using `minted` environment inside a `tabu` table I am trying to use a piece of highlighted code using the minted package inside a tabu table:
\documentclass{article}

\usepackage{minted}
\usepackage{longtable}
\usepackage{tabu}

\begin{document}
    \begin{tabu*}{X[5,l]X[5,l]}
        \begin{minted}{matlab}
function out = op(x, y)
    out = x + y;
end
        \end{minted}
        & \\
    \end{tabu*}
\end{document}

With the above MWE I tried to place a minted environment inside a tabu cell analogously to what was done with the Verbatim environment explained within the tabu package documentation in section 1.3 "Inserting Verbatim material (fancyvrb)". However, by compiling the above MWE I get the following error message:
Enter file name:
! Emergency stop.
<read *>

l.15     \end{tabu*}
                    ^^J
*** (cannot \read from terminal in nonstop modes)

If I try to compile the document in scroll mode (-interaction=scrollmode with XeLaTeX from MiKTeX), I just get a command prompt with Enter file name:.
How can the minted environment be used within a tabu table?

A: This is more of a hack than a real fix.  minted correctly creates the highlighted content, and the content is correctly brought in.  But at some point, minted's \minted@pygmentize macro tries to \input a file that "doesn't exist."  I put "doesn't exist" in quotes because I've tried minted with all file deletion disabled, and still get the error--so it seems to be related to tabu's multiple passes.  Anyway, the Enter file name: can be avoided by patching tabu*.  Basically, replace every \input with an \InputIfFileExists.  Insert the following in the preamble, after tabu is loaded, and you document will compile.
\usepackage{etoolbox}
\let\originalinput\input
\newcommand{\newinput}[1]{\InputIfFileExists{#1}{}{}}
\AtBeginEnvironment{tabu*}{\let\input\newinput}


text:
Q: Rails form submit causes undefined method 'allow_forgery_protection' for nil:NilClass I'm trying to create a form that submits from 1 controller to another. When I do so, I get "undefined method 'allow_forgery_protection' for nil:NilClass". However, if I POST back to the same controller, it successfully submits.
Things to know

*

*My application controller has protect_from_forgery set. I'm not
messing with :before_filter or anything in order to reduce
possible problems.

*There is no model for either controller. Both were generated with rails g controller <name>

*Rails 3.2 if it makes a difference

app/controllers/first_controller.rb
def myaction
end

app/views/first/myaction.html.erb
<%= form_tag(url_for(:controller => 'second', :action => controller.action_name), :method => :post) do %>
  <fieldset>
    <%= label_tag(:file_dir, "File location") %>
    <%= text_field_tag :file_dir, "/var/log" %>
  </fieldset>
  <%= submit_tag "Submit" %>
<% end %>

app/controllers/second_controller.rb
def myaction
end

app/views/second/myaction.html.erb

Second#myaction

Find me in app/views/second/myaction.html.erb

routes.rb
 match 'first/:action' => 'first#:action'
 match 'second/:action' => 'second#:action'

It's probably my lack of understanding about the CSRF, but I don't see how simply changing :controller => 'second'to :controller => 'first' will determine whether the nearly identical controllers will work.
Part of the log
# Rendered the form
Started GET "/first/myaction" for 127.0.0.1 at 2012-08-04 14:20:00 -0500
Processing by FirstController#myaction as HTML
Rendered first/myaction.html.erb within layouts/application (3.7ms)
Completed 200 OK in 142ms (Views: 141.9ms | ActiveRecord: 0.0ms)

# Submitted the form here
Started POST "/second/myaction" for 127.0.0.1 at 2012-08-04 14:22:00 -0500
Processing by SecondController#myaction as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"xyQetj0Wdks+iuOXNjrxs96TbEJOw4ktURTrraEARoU=",<everything else looks fine>}
Completed 500 Internal Server Error in 0ms
NoMethodError (undefined method `allow_forgery_protection' for nil:NilClass):

A: I created a third controller to test with (via the same exact steps), and the form performed a POST properly.
During this same time, the second threw this forgery error consistently.
I deleted the second controller with rails destroy controller second, and recreated it with rails g controller second, keeping the same routes in routes.rb, and everything worked properly.


text:
Q: How to install cocos2d 2.0 beta? http://i44.tinypic.com/2qb5dl0.jpg
I get all these errors after running the install-templates.sh. I only get them when compiling for device, simulator runs without any errors (the warnings remain though).
Why and how do i fix this? So frustrating..
Worth mentioning is that i edited the install-remplates.sh so i could run it as root, that wasnt recommended but it wouldnt work otherwise. (didnt get permission to create folders and such..). Im running Lion, that might be the reason.

A: Reinstall the templates without sudo, using the unmodified template installer script like so:
./install-templates.sh -f -u

This will install the templates in the user's Library folder which is the recommended way.
If this fails with errory, you most likely have older templates installed which you've installed with sudo. In that case the templates script won't allow you to overwrite them in the user folder without using sudo, while the script itself doesn't allow you to install the cocos2d templates to the user folder with sudo anymore.
To fix that, simply delete the old (installed with sudo) templates first by deleting this folder:
~/Library/Developer/Xcode/Templates/cocos2d

In a couple weeks I'll have cocos2d 2.0 integrated in Kobold2D. From then on you can just run the Kobold2D package installer and start working.


text:
Q: properties table pattern vs storing all properties in json column I'd like some feedback on having all properties a model can have in a properties table accessed via relationship (using laravel relationships) vs storing all properties/settings in the same table but in a json column.
Currently, my application has a propeties table called settings that is also polymorphic in nature so multiple models can store their properties there. This table has columns like
key (string),
value(string),
type (string) - tells if the value is of string, integer, boolean, json type

so that I do not send strings to javascript frontend, but instead I can send string, integer, boolean native types for better handling of types in frontend. I do this conversion before I send the properties to the frontend using php function that cast string values to int, boolean, json or string, depending on the type.
This means if a model has 40 properties, all get stored in its own row, so creating one model leads to creating 40 rows that store all properties it may have.
Now the above approach vs approach where I just have a single json column, we can call it settings and I dump all these 40 properties there.
What do I win with json column approach? I shave off a table and I shave off an extra relationship that I need to load on this model each time I do some queries. I also shave off having to each time I get properties cast them to integer, boolean, json or string. (remember the type column above) To keep in mind these properties do not need to be searchable, I need them only for reading from them. I will never use them in queries to return posts based on these properties.
Which one is a better idea to use, I'm building a CMS btw you can see it in action here:
https://www.youtube.com/watch?v=pCjZpwH88Z0

A: As long as you don't try to use the properties for searching or sorting, there's not much difference.
As you said, putting a JSON column in your model table allows you to avoid a JOIN to the properties table.
I think your properties table actually needs to have one more column, to name the property. So it should be:
key (string),
property (string),
value(string),
type (string) - tells if the value is of string, integer, boolean, json type

The downsides are pretty similar for both solutions.

*

*Queries will be more complex with either solution, compared to querying normal columns.

*Storing non-string values as strings is inefficient. It takes more space to store a numeric or datetime value as a string than as a native data type.

*You can't apply constraints to the properties. No way to make a property mandatory (you would use NOT NULL for a normal column). No way to enforce uniqueness or foreign key references.
There's one case I can think of that gives JSON an advantage. If one of your custom properties is itself multi-valued, there's a straightforward way to represent this in JSON: as an array within your JSON document. But if you try to use a property table, do you store multiple rows for the one property? Or serialize the set of values into an array on one row? Both solutions feel pretty janky.
Because the "schemaless properties" pattern breaks rules of relational database design anyway, there's not much you can do to "do it right." You're choosing the lesser of two evils, so you can feel free to use the solution that makes your code more convenient.


text:
Q: Codeigniter try to load a language file while there is an error reporting When sql is wrong, CI try to load a db_lang.php file, and I can't see the original error reporting. When there are other errors, it try to load another XXX_lang.php file. How to fix the bug?
It just print an error "Unable to load the request XXX_lang.php bahlahbahlah...."


text:
Q: Vue test login form I created a login form with vuejs. I'm new with the vue framework and want to write a test for my api call.
This is the form:
<template>

        <q-btn
          @click="loginGoogle"
          type="submit"
          color="primary"
          class="col"
          name="login_google"
          outline
          size="lg"
          label="Login with Google" />

      <q-btn
        type="submit"
        color="primary"
        class="col"
        name="login_apple"
        outline
        size="lg"
        label="Login with Apple ID" />

    <form @submit.prevent="submitForm" class="q-mt-lg">

          <q-input
            v-model="formData.email"
            outlined
            class="col"
            label="Email"
            ref="email"
            stack-label
            :rules="[ val => validateEmail(val) || 'Please enter a valid email address']"
            lazy-rules />

          <q-input
            v-model="formData.password"
            type="password"
            outlined
            class="col"
            label="Password"
            ref="password"
            stack-label
            :rules="[ val => val.length >= 8 || 'Password must be at least 8 characters']"
            lazy-rules />

            <q-btn
            type="submit"
            name="login"
            class="login"
            color="primary"
            label="Login" />

    </form>

</template>

Action method with api call:
submitForm () {
  this.$refs.email.validate()
  this.$refs.password.validate()
  if (!this.$refs.email.hasError && !this.$refs.password.hasError) {
    authService.login({ email: this.formData.email.toLowerCase(), password: this.formData.password })
      .then((res) => {
        this.$store.commit('SET_AUTH_USER')
        localStorage.setItem('access_token', res.access_token)
        localStorage.setItem('refresh_token', res.refresh_token)
        this.$store.dispatch('GET_ME').then((me) => {
          this.$router.push({ path: '/' })
        })
      }).catch((err) => {
        if (err.status === 500) {
          this.$swal({ icon: 'error', title: 'Something went wrong!' })
        } else {
          this.$swal({ icon: 'error', title: 'Wrong data!' })
        }
      })
  }
}

My api call:
/**
 * Send request for login user and set token in localstorage
 *
 * @param {String} email
 * @param {String} password
 * @returns {Object}
 */
async function login (data) {
  const requestOptions = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'application/json'
    },
    body: `email=${data.email.trim()}&password=${data.password.trim()}`
  }
  const res = await fetch('http://localhost/api/login', requestOptions)
  if ((await res.status) !== 200) {
    // eslint-disable-next-line no-throw-literal
    throw { status: res.status, message: res.statusText }
  } else {
    return await res.json()
  }
}

I read that I have to mock the action from vuex store and to trigger the action. So my test looks like this:
import Vuex from 'vuex'
import { mount, createLocalVue } from '@vue/test-utils'
import LoginComponent from '../components/Auth/Login'

const localVue = createLocalVue()
localVue.use(Vuex)

describe('Login form', () => {
  it('calls the login action correctly', () => {
    const loginMock = jest.fn(() => Promise.resolve())
    const store = new Vuex.Store({
      actions: {
        // mock function
        submitForm: loginMock
      }
    })
    const wrapper = mount(LoginComponent, { localVue, store })
    wrapper.find('form').trigger('submit.prevent')
    expect(loginMock).toHaveBeenCalled()
  })
})

The test is failed:
  Login form
    ✕ calls the login action correctly (50 ms)

  ● Login form › calls the login action correctly

    expect(jest.fn()).toHaveBeenCalled()

    Expected number of calls: >= 1
    Received number of calls:    0

      18 |     const wrapper = mount(LoginComponent, { localVue, store })
      19 |     wrapper.find('form').trigger('submit.prevent')
    > 20 |     expect(loginMock).toHaveBeenCalled()
         |                       ^
      21 |   })
      22 | })
      23 |

      at Object.<anonymous> (src/specs/login.spec.js:20:23)

Can you give me a suggestions what are the tests (not only the for api call) I need to write to make sure my form works correctly? Thank you!

A: You have to await the trigger since it is making an asyn function call
await wrapper.find('form').trigger('submit.prevent')

then
wrapper.$nextTick(() => {
   expect(loginMock).toHaveBeenCalled()
})

A: amend the last bit. You omitted vm.
wrapper.vm.$nextTick(() => { expect(loginMock).toHaveBeenCalled(); });


text:
Q: Mininet ping/iperf3 got unstable measurement results Expected/Desired Behavior:
Mininet should return stable ping RTT results, after setting the network conditions with Linux tc netem.
Actual Behavior:

Detailed Steps to Reproduce the Behavior:
sudo mn # start the default topo h1---s1---h2
s1 tc qdisc add dev s1-eth2 root handle 1: netem delay 20ms loss 0.01% # this will emulate 20ms RTT
h1 ping h2

Additional Information:
I am running Mininet 2.3.0 on Virtual Box in my win10 laptop.
The VM OS is Ubuntu 16.04 and I upgraded the Linux kernel to 4.15.
Only a host-only adapter is set in VM:

A: I have also seen this in the past and wondered. While I do not have a clear answer, here are a few possible explanations.
From your screenshot, I would assume your set RTT was 20 ms and I will work with it going forward.
The very first sample that you get has inflated RTT, since this is the first packet going through the controller and it is setting up the rules which has an increased latency.
After that, the difference in the probes that you get could be explained by:

*

*OS imprecision. Since all components are emulated and it happens in real time, there might not be enough processing power to serve packets all the time

*(More likely) Misconfigured link properties. Mininet links expose an option called max_queue_size. This is, how many packets can be buffered on this link before they get dropped. Naturally, packets sitting in the buffers will have an added propagation or buffering delay on top of their minimum path RTT measurement. I suspect this might be what you are observing since the "bad" samples seem to be clustered, hinting queuing possibly queued packets. This article explaining how queuing delay affects network links.


text:
Q: CSV en formato MS-DOS JAVA Tengo un problema al momento de generar mi archivo CSV desde JAVA en el Sistema Operativo SunOS 5.10 (en Windows funciona correctamente) el formato que necesito es MS-DOS intente con lo que me dice la siguiente pregunta del SO Ingles:

https://stackoverflow.com/questions/4098568/csv-and-ms-dos-csv-formats

Pero no me funciona, ademas lo intente con el siguiente código sacado del foro en ingles:
public final static char CR  = (char) 0x0D;
public final static char LF  = (char) 0x0A;

public final static String CRLF  = "" + CR + LF;     // "" forces conversion to string

String twoLines = "Line1" + CRLF + "Line2";   // 12 characters

Fuente:

https://stackoverflow.com/questions/13821578/crlf-into-java-string

Igual intente con:
System.getProperty("line.separator")

Pero de ninguna de las maneras me ha salido. Les comparto mi código que genera el CSV:
archivoCsv = new CsvWriter(new FileWriter(new File(System.getProperty("user.dir")+"/../salida/"+campaniasBL.nombreArchivoExtraccion),false), ',');
archivoCsv.write("Folio de Campaña");
archivoCsv.write("Nombre de Campaña");
archivoCsv.write("Inicio");
archivoCsv.write("Fin");
archivoCsv.endRecord();
if (archivoCsv != null) {
    archivoCsv.close();
}

Espero que me puedan ayudar.

A: Comparto la solución a mi problema por si alguien en un futuro se encuentra en la misma situación que yo:
public class CsvWriter {

    private static final String COMMA_DELIMITER = ",";
    private static final String NEW_LINE_SEPARATOR = "\r\n";
    private static final String FILE_HEADER = "id,firstName,lastName,gender,age";

    public static void main(String[] args) {
        FileWriter fileWriter = null;
        //Nombre y directorio del archivo a crear
        String fileName = System.getProperty("user.dir") + "/csvMsDosformat.csv";
        try {
            fileWriter = new FileWriter(fileName);
            fileWriter.append(FILE_HEADER.toString());
            fileWriter.append(NEW_LINE_SEPARATOR);
            for (int x = 0; x < 10; x++) {
                fileWriter.append("Prueba");
                fileWriter.append(COMMA_DELIMITER);
                fileWriter.append("Prueba 1");
                fileWriter.append(COMMA_DELIMITER);
                fileWriter.append("Prueba 2");
                fileWriter.append(COMMA_DELIMITER);
                fileWriter.append("Prueba 3");
                fileWriter.append(COMMA_DELIMITER);
                fileWriter.append("Prueba 4");
                fileWriter.append(NEW_LINE_SEPARATOR);
            }
            System.out.println("CSV creado correctamente");

        } catch (Exception e) {
            System.out.println("Error al crear CSV");
            e.printStackTrace();
        } finally {
            try {
                fileWriter.flush();
                fileWriter.close();
            } catch (IOException e) {
                System.out.println("Error al cerrar el CSV");
                e.printStackTrace();
            }
        }
    }
}

Fuente:

https://examples.javacodegeeks.com/core-java/writeread-csv-files-in-java-example/


text:
Q: How do I use an excerpt from Eleventy's gray-matter? Goal: Display a post excerpt for each post in the post list of an Eleventy blog
I'm adapting this starter project as my own blog.
I'm referring to this Eleventy document
to get the post excerpt.
My code:
I started by editing my .eleventy.js to enable gray-matter excerpt, per the above document, like so:
module.exports = function(eleventyConfig) {
  eleventyConfig.addPlugin(pluginRss);
  eleventyConfig.addPlugin(pluginSyntaxHighlight);
  eleventyConfig.addPlugin(pluginNavigation);

  eleventyConfig.setDataDeepMerge(true);
  eleventyConfig.setFrontMatterParsingOptions({ excerpt: true
                                              });
  /* file continues below */

Next, I added "---" following the first paragraph in some blog posts, per the example.
Finally, I updated /_includes/postslist.njk to include a reference to the excerpt for each post, so my new file now reads:

{% for post in postslist | reverse %}

    {% if post.data.title %}{{ post.data.title }}{% else %}{{ post.url }}{% endif %}
    <time class="postlist-date" datetime="{{ post.date | htmlDateString }}">{{ post.date | htmlDateString }}</time>
    {% for tag in post.data.tags %}
      {%- if collections.tagList.indexOf(tag) != -1 -%}
      {% set tagUrl %}/tags/{{ tag }}/{% endset %}
      {{ tag }}
      {%- endif -%}
    {% endfor %}
    {%- if post.excerpt -%}

{{ post.excerpt }}

    {%- endif -%}

{% endfor %}

but no excerpts appear.
What I've Tried
I've checked for empty paragraph tags in the output HTML, and they are not there, so the if
condition itself is failing.
I've tried setting the excerpt separator to something other than the default
"---", with the same result.
Importantly, I've tried disabling excerpts in the .eleventy.js, which causes the separator to
be read as regular markdown. This is important because it shows that gray-matter is correctly
reading my separators in the blog posts as separators, and therefore the problem must be in my
/_includes/postslist.njk.
Conclusion
How do I reference the excerpt that Eleventy generates from gray-matter?
(P. S.: I don't have enough reputation to create a StackOverflow tag for the gray-matter npm package, but imho it wouldn't be a bad idea if somebody wanted to do that. I've tagged it with
yaml-front-matter, which isn't wholly inaccurate, but as I understand it my issue is pretty
specific to the gray-matter dialect of yaml front matter. )

A: As per the documentation, eleventy makes the excerpt available under the page variable (see Eleventy supplied data), not as a 'top-level' property of a collection item. The page variable is part of the data object of a collection item. If you use post.data.page.excerpt instead of post.excerpt it will work as expected:
{%- if post.data.page.excerpt -%}

{{ post.data.page.excerpt }}

{%- endif -%}

Alternatively, you can use the excerpt_alias option to make the excerpt available as a top-level property. With this configuration, your template will work as is:
eleventyConfig.setFrontMatterParsingOptions({
    excerpt: true,
    excerpt_alias: 'excerpt',
});


text:
Q: Using Html Agility Pack, Selecting the current element in a loop (XPATH) I'm trying to do something simple, but somehow it doesnt work for me, here's my code:
var items = html.DocumentNode.SelectNodes("//div[@class='itembox']");
foreach(HtmlNode e in items)
{

     int x = items.count; // equals 10
     HtmlNode node = e;
     var test = e.SelectNodes("//a[@class='head']");// I need this to return the
                                                // anchor of the current itembox
                                                // but instead it returns the
                                                // anchor of each itembox element
     int y =test.count; //also equals 10!! suppose to be only 1
}

my html page looks like this:
....

    One

    Two

....

Is my XPath expression wrong? am i missing something?

A: Use
var test = e.SelectNodes(".//a[@class='head']");

instead. Your current code ( //a[]) searches all a elements starting from the root node. If you prefix it with a dot instead (.//a[]) only the descendants of the current node will be considered. Since it is a direct child in your case you could of course also do:
var test = e.SelectNodes("a[@class='head']");

As always see the Xpath spec for details.

A:  var test = e.SelectNodes("//a[@class='head']");

This is an absolute expression, but you need a relative XPath expression -- to be evaluated off e.
Therefore use:
 var test = e.SelectNodes("a[@class='head']");

Do note: Avoid using the XPath // pseudo-operator as much as possible, because such use may result in significant inefficiencies (slowdown).
In this particular XML document the a elements are just children of div -- not at undefinite depth off div.


text:
Q: Ubuntu 22.04 on Raspberry pi 4B not using total RAM I have installed Ubuntu 22.04 on my Raspberry Pi 4B (8GB, ARM64), but it runs slow and often lags even though I only opened a few things like the file explorer, terminal and Chromium browser. When I run $ free -m -l -t -h, I found that the available RAM shown is only 3.8G out of the total actual 7.6G. When I check System Monitor, the RAM usage always caps at about 3.9G even though I was really pushing the limits by opening up many browsers with many tabs, running VS Code, etc. So may I know what is actually going on here, and how can I make it use all available RAM? Thanks in advance!
               total        used        free      shared  buff/cache   available
Mem:           7.6Gi       3.2Gi       130Mi       324Mi       4.3Gi       3.8Gi
Low:           7.6Gi       7.5Gi       130Mi
High:             0B          0B          0B
Swap:          1.0Gi        16Mi       1.0Gi
Total:         8.6Gi       3.2Gi       1.1Gi

Besides, for reference, this is the output when I run $ cat /proc/meminfo.
MemTotal:        7995284 kB
MemFree:          492592 kB
MemAvailable:    4166240 kB
Buffers:          118360 kB
Cached:          3931688 kB
SwapCached:         3212 kB
Active:          2034552 kB
Inactive:        4568056 kB
Active(anon):      43304 kB
Inactive(anon):  2851476 kB
Active(file):    1991248 kB
Inactive(file):  1716580 kB
Unevictable:      247524 kB
Mlocked:              64 kB
SwapTotal:       1048572 kB
SwapFree:         997884 kB
Dirty:               124 kB
Writeback:             0 kB
AnonPages:       2798796 kB
Mapped:           811760 kB
Shmem:            342812 kB
KReclaimable:     279664 kB
Slab:             409648 kB
SReclaimable:     279664 kB
SUnreclaim:       129984 kB
KernelStack:       19616 kB
PageTables:        43292 kB
NFS_Unstable:          0 kB
Bounce:                0 kB
WritebackTmp:          0 kB
CommitLimit:     5046212 kB
Committed_AS:    9152712 kB
VmallocTotal:   133143592960 kB
VmallocUsed:       36292 kB
VmallocChunk:          0 kB
Percpu:             3408 kB
AnonHugePages:         0 kB
ShmemHugePages:        0 kB
ShmemPmdMapped:        0 kB
FileHugePages:         0 kB
FilePmdMapped:         0 kB
CmaTotal:         327680 kB
CmaFree:            6876 kB
HugePages_Total:       0
HugePages_Free:        0
HugePages_Rsvd:        0
HugePages_Surp:        0
Hugepagesize:       2048 kB
Hugetlb:               0 kB


text:
Q: Jquery separate list items AJAX  public class searchResult
 {
public int id;
public string name;
}
/// <summary>
/// Summary description for WebService1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
[System.Web.Script.Services.GenerateScriptType(typeof(searchResult))]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment                    the following line.
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{

[WebMethod]
public searchResult[] Search(int txtSearch)
{
//Semuler to slow internet connection
System.Threading.Thread.Sleep(2000);

//Declare collection of searchResult
List<searchResult> resultList = new List<searchResult>();
DataSet ds = Classes.getEmployeeDetailSet("SELECT [Employee ID],[First Name] FROM     [Employee$] WHERE [Employee ID] like '" + txtSearch + "%'");
DataTable dt = new DataTable();
dt = ds.Tables[0];
if (dt.Rows.Count > 0)
{
searchResult result = new searchResult();
result.id = int.Parse(dt.Rows[0]["Employee ID"].ToString());
result.name = dt.Rows[0]["First Name"].ToString();
resultList.Add(result);
}
return resultList.ToArray();
}

i have created a list like
      List<searchResult> resultList = new List<searchResult>(); this
      and i have return that list
      to call this i have use ajax code like this

         $.ajax({ type: "POST",
      url: "WebService1.asmx/Search", //function that in web service
      data: "{txtSearch:" + $("#txtSearch").val() + "}", // passing value of txtSearch input
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function(response) {
      var result = response.d;
      var value = '';
      $.each(result, function(index, res) {
      value = value + res.id + res.name;
      });

      alert(value);
      alert("Record was updated successfully,,");
      },
      error: function(msg) {
      alert("Error while calling web service,,");
      }
      });

My problem is that I am getting only one element from the database
I think I am not able to separate the list in the ajax response here
      $.each(result, function(index, res) {
      value = value + res.id + res.name;
      });

I want to create a array with use of this id+name
please help

A: As Robert Slaney said, you are only returning the first result from the database.
Try something like this on the server side.
public class SearchResult
{
    public int ID;
    public string Name;
}

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
[ScriptService]
public class WebService1 : System.Web.Services.WebService
{

    [WebMethod, ScriptMethod]
    public SearchResult[] Search(int employeeID)
    {
        List<SearchResult> resultList = new List<searchResult>();
        DataSet ds = Classes.getEmployeeDetailSet("SELECT [Employee ID],[First Name] FROM [Employee$] WHERE [Employee ID] like '" + employeeID + "%'");
        DataTable dt = ds.Tables[0];

        foreach(DataRow row in dt.Rows)
        {
            resultList.Add(new SearchResult{ ID = int.Parse(row["Employee ID"].ToString()), Name = row["First Name"].ToString()});
        }
        return resultList.ToArray();
    }
}

You can also use Chrome Developer Tools to inspect your request and response and verify that the data is actually being returned.


text:
Q: Changing frame of view loaded from Xib I am trying to change the frame of my custom view which I load from a xib.
Here is my init method of the view:
- (id)initWithUserName:(NSString*)userName andComment:(NSString*)comment
{

    if (self) {
        self = [[[NSBundle mainBundle] loadNibNamed:@"Comment" owner:self options:nil]objectAtIndex:0];

        self.userName = userName;
        self.comment = comment;
        NSLog(@"CREATED");
        NSLog(@"%@, %@",self.userName, self.comment);

        self.userNameButton.tag = -1;

        CGSize constraint = CGSizeMake(240, 2000);
        self.userNameButton.backgroundColor = [UIColor clearColor];
        CGSize sizeOfUsernameText = [self.userName sizeWithFont:[UIFont fontWithName:@"OpenSans-Light" size:12.0] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];

        //color converted from #161616 Hex
        [self.userNameButton.titleLabel setTextColor:[StaticMethods colorFromHexString:@"#161616"]];
        [self.userNameButton setTitle:[self.userName stringByAppendingString:@":"] forState:UIControlStateNormal];
        [self.userNameButton.titleLabel setFont:[UIFont fontWithName:@"OpenSans-Light" size:12.0]];
        [self.userNameButton setNeedsDisplay];

        //[self.userNameButton addTarget:self.delegate action:@selector(userNameButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        //Append appropriate amount so that the usernames can be seen and clickable
        NSString *indentString = @" ";
        CGSize sizeOfWhitespaces = [indentString sizeWithFont:[UIFont fontWithName:@"OpenSans-Light" size:12.0] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
        while (sizeOfWhitespaces.width < sizeOfUsernameText.width) {
            sizeOfWhitespaces = [indentString sizeWithFont:[UIFont fontWithName:@"OpenSans-Light" size:12.0] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
            indentString = [indentString stringByAppendingString: @" "];

        }
        CGSize sizeOfComment = [comment sizeWithFont:[UIFont fontWithName:@"OpenSans-Light" size:12.0] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];

        self.commentText.tag = -1;
        self.commentText.text = [indentString stringByAppendingString: self.comment];
        self.commentText.font = [UIFont fontWithName:@"OpenSans-Light" size:12.0];
        [self.commentText setTextColor:[StaticMethods colorFromHexString:@"#161616"]];

    }

    return self;
}

This method is called from a view controller like this:
- (void)viewDidLoad
{
    [super viewDidLoad];
    for(int i = 0; i < self.userNames.count;i++){
        CommentView *view = [[CommentView alloc]initWithUserName:[self.userNames objectAtIndex:i] andComment:[self.comments objectAtIndex:i]];
        [view setDelegate: self];
        [self.view addSubview:view];
        view.frame = CGRectMake(0,100,320,100);

    }

    // Do any additional setup after loading the view from its nib.
}

Now, the line where it says view.frame = CGRectMake(0,100,320,100); is where i try to change the views frame. I have tried putting that code inside the view's
- (id)initWithUserName:(NSString*)userName andComment:(NSString*)comment
method body as well, without luck.
So clearly I am having trouble resizing the view according to my preferences.
The view has always the same frame as when it is presented in interface builder.
What am I doing wrong?
EDIT
I have tried putting the above viewDidLoad body inside that viewcontroller's viewWillAppear body, without any progress.

A: Disabling "Use Autolayout" in .xib solved this for me.

A: put your code inside
- (void)viewDidLayoutSubviews
{

}

it is a delegate method executes only after autolayout has executed.


text:
Q: jQuery DataTables checkbox - event on row selection? I hope this is something I just overlooked, but I'm trying to capture the checkbox click or change event on a row of a DataTables table. The use case is that I want to enable a link on the page if any row is selected, and disable the link if no rows are selected. So I need some sort of a change event that happens when the checkbox is selected or deselected, but I'm not having any luck. I can see how to find out how many rows are selected inside of a function, but I need a trigger event.
I tried doing this with the Select extension for DataTables, but I couldn't seem to get what I wanted there, either.
Thanks!


text:
Q: show mysql query in smarty loop i want show query in smarty loop with some like title :
table1 (courses): id, title

table2 (questions): id, title, teachers_id

query:
$this->ctitle_qtitle = DatabaseHandler::GetAll("
                 SELECT courses.title , questions.title
                 FROM courses
                 JOIN questions
                 ON courses.id = questions.courses_id ");

this query work true, and in .tpl file i use loop:
{section name=i loop=$obj->ctitle_qtitle}

{$obj->ctitle_qtitle[i].title

        {$obj->ctitle_qtitle[i].title}
        Delete
         Edit

{/section}

how can i use courses.title or question.title in smarty result ?

A: You need to modify your SQL query from:
$this->ctitle_qtitle = DatabaseHandler::GetAll("
                 SELECT courses.title , questions.title
                 FROM courses
                 JOIN questions
                 ON courses.id = questions.courses_id ");

to
$this->ctitle_qtitle = DatabaseHandler::GetAll("
                 SELECT courses.title AS `ctitle` , questions.title AS `qtitle`
                 FROM courses
                 JOIN questions
                 ON courses.id = questions.courses_id ");

This way you create aliases for column names (earlier this was problem because 2 columns had the same name) and now you can simple use ctitle and qtitle in Smarty as for example:
{section name=i loop=$obj->ctitle_qtitle}

{$obj->ctitle_qtitle[i].ctitle

        {$obj->ctitle_qtitle[i].qtitle}
        Delete
         Edit

{/section}


text:
Q: Block regex to recognize number while it's part of a URL I am using regex: [(]?(((\d)([() .-]+)?)+){7,18}|\*\d{3,10}|\d{3,10}\*(?!/)
How can I change the attached regex to not recognize the numbers that are part of a URL to the Facebook as phone number, but could recognize a phone number that is not part of a URL?
The URL:
https://www.facebook.com/pages/Fashion-24/151055822249094?fr=ts
The above regex detect "151055822249094" as phone number.

A: You can use a negative lookbehind in your regex:
(?<!/)[(]?(((\d)([() .-]+)?)+){7,18}|*\d{3,10}|\d{3,10}*(?!/)

A: If you are using C#, you can use the look-behind to make sure you are not inside the URL:
(?i)(?<!\bhttp\S*)(?:[(]?(?:(?:(?:\d)([() .-]+)?)+){7,18}|\*\d{3,10}(?!\d)|(?<!\d)\d{3,10}\*)(?!/)

See demo


text:
Q: Transaction allow to fail and continue Im having a problem with a major data migration that can be configured by the user, lets say it goes like this:
try {
    daoManager.beginTransaction();

    for (Entity node : nodeList) {

        boolean inserted;

        if (migrationConfig.canInsert()) {
            try {
                inserted = daoManager.getDaoEntity().insert(node);
            }
            catch(IndexDuplicityException ex) {
                inserted = false;
                //I want the transaction to continues when this Exceptions is
                //throwed
            }
        }

        if (migrationConfig.canUpdate() && !inserted) {
            modificoEntidad = daoManager.getDaoEntity().update(node);
        }
    }

    //Later

    if (//Business Logic) {
        throw new MustRollBackTransaction();
    }

    daoManager.commitTransaction();

} catch (MustRollBackTransaction ex) {
    daoManager.RollBack();
}

My problem is that when the IndexDuplicityException is throwed, any of the future transactions are ignored, giving me this exception

PSQLException: current transaction is aborted, commands ignored until
  end of transaction block

Isnt there a way to my transaction allow failed excecuted statements and not abort the whole transaction?
Thanks.

A: Try to rollback the transaction and start a new one on IndexDuplicityException:
   }catch(IndexDuplicityException ex) {
    inserted = false;
    daoManager.RollBack();
    daoManager.beginTransaction();
   }


text:
Q: Get the value from the given array I have this given array ,
How can get the value of email and status in loop .
Array
(
    [0] => Array
        (
            [brandlogo_id] => 1
            [email] => upendtu@gmail.com
            [status] => 2
            [created_time] => 2017-11-13 14:00:10
            [update_time] => 2017-11-13 14:00:10
        )

    [1] => Array
        (
            [brandlogo_id] => 2
            [email] => upen3592@gmail.com
            [status] => 1
            [created_time] => 2017-11-13 13:58:46
            [update_time] => 2017-11-13 13:58:46
        )

    [2] => Array
        (
            [brandlogo_id] => 3
            [email] => ankigupta9492@gmail.com
            [status] => 1
            [created_time] => 2017-11-13 13:57:07
            [update_time] => 2017-11-13 13:57:07
        )

)

please let me know how can i get this value
thank you.

A: Be it any language, the method/ also will be more or less the same apart from the syntax. Search the syntax for the language you are using to parse JSON data.
Giving examples.
For Objective - C:
    NSArray *resultDataSet=[NSArray array];
    while([results next]) {
        NSString *name = [results stringForColumn:@"brand_name"];
        resultDataSet = [resultDataSet arrayByAddingObject:name ];
    }

For Python :
for array in data:
    print array['email']

For PHP :
foreach($arr as $item) { //foreach element in $array
    $stat = $item['status']; //etc
}

Hope that helps.

A: Assuming that you are using PHP or python (as this is an associative array) and the name of the array is "arr".
This code shall do the job.
For PHP
foreach($arr as $subarray) {
    echo $subarray["email"]." ".$subarray["status"]."<br>";
}

For Python
for subarray in arr:
    print subarray["email"], " ", subarray["status"]

It will display output similar to
xyz@gmail.com 2
abc@yahoo.com 3


text:
Q: How do I properly use strtotime in an IF statement? I'm trying to check for a specific time condition, but for some reason I cannot get it to work. Only the FIRST condition gets applied. It seems to me the second condition should be applied as it is past 9:59am central time.
I have:
<?php
$timezone       = date_default_timezone_set('America/Chicago');
$TheDate        = strtotime("April 1, 2016, 12:00 am");

if ($TheDate >= strtotime("March 30, 2016, 12:00 am") && $TheDate <= strtotime("April 1, 2016, 9:59 am")) {
    global $eventMsg;
    echo 'My name';
}

else if ($TheDate >= strtotime("April 1, 2016, 4:12 pm") && $TheDate <= strtotime("April 1, 2016, 4:59 pm")) {
    global $eventMsg;
    echo 'His name';
}

else {
    global $eventMsg;
    echo 'Pete\'s name';
}?>

I tested this two days ago and it was working while we were in the month of March, now I'm being fooled. Does anyone have an answer?

A: I played around with the code and figured out what I was trying to do, also with the help of Charlotte and the PHP Manual.
I simply added the time() function and formatted the time/date parameter.


text:
Q: Adding elements and columns based off a cutoff year? structure(list(`2005` = c(0L, 0L, 0L, 2L, 1L), `2006` = c(0L,
0L, 0L, 1L, 1L), `2007` = c(1L, 0L, 1L, 0L, 3L), `2008` = c(1L,
0L, 0L, 4L, 3L), `2009` = c(1L, 0L, 0L, 2L, 3L), `2010` = c(0L,
0L, 0L, 5L, 0L), `2011` = c(0L, 0L, 0L, 0L, 1L), `2012` = c(0L,
0L, 0L, 4L, 1L), `2013` = c(1L, 0L, 1L, 0L, 0L), `2014` = c(0L,
0L, 2L, 0L, 9L), `2015` = c(0L, 0L, 1L, 0L, 2L), `2016` = c(0L,
0L, 0L, 0L, 0L), Cutoff = c("2011", "2015", "2015", "2005", "2011"
)), .Names = c("2005", "2006", "2007", "2008", "2009", "2010",
"2011", "2012", "2013", "2014", "2015", "2016", "Cutoff"), row.names = c(NA,
5L), class = "data.frame")

Given the following dataframe. I would like to add 4 columns to the table.
One column that adds the numbers in the elements before the cutoff year and one column that adds the numbers in the elements after the cutoff year.
Then two more columns where one column adds the total number of years/columns before the cutoff and another column for after the cutoff.
The cutoff years should not be included in the respective rows.
So the final table will end up looking like this:
structure(list(`2005` = c(0L, 0L, 0L, 2L, 1L), `2006` = c(0L,
0L, 0L, 1L, 1L), `2007` = c(1L, 0L, 1L, 0L, 3L), `2008` = c(1L,
0L, 0L, 4L, 3L), `2009` = c(1L, 0L, 0L, 2L, 3L), `2010` = c(0L,
0L, 0L, 5L, 0L), `2011` = c(0L, 0L, 0L, 0L, 1L), `2012` = c(0L,
0L, 0L, 4L, 1L), `2013` = c(1L, 0L, 1L, 0L, 0L), `2014` = c(0L,
0L, 2L, 0L, 9L), `2015` = c(0L, 0L, 1L, 0L, 2L), `2016` = c(0L,
0L, 0L, 0L, 0L), Cutoff = c("2011", "2015", "2015", "2005", "2011"
), Numbers_Before = c(3, 0, 4, 0, 11), Numbers_After = c(1, 0,
0, 16, 12), Years_Before = c(6, 10, 10, 0, 6), Years_After = c(5,
1, 1, 11, 5)), .Names = c("2005", "2006", "2007", "2008", "2009",
"2010", "2011", "2012", "2013", "2014", "2015", "2016", "Cutoff",
"Numbers_Before", "Numbers_After", "Years_Before", "Years_After"
), row.names = c(NA, 5L), class = "data.frame")

A: I found it easier to first use melt to put the table in a tidy format then use some data.table operations to tally up the number of years or of the numbers before and after the Cutoff years.
library(data.table)

dt = setDT(structure(list(`2005` = c(0L, 0L, 0L, 2L, 1L), `2006` = c(0L,
  0L, 0L, 1L, 1L), `2007` = c(1L, 0L, 1L, 0L, 3L), `2008` = c(1L,
  0L, 0L, 4L, 3L), `2009` = c(1L, 0L, 0L, 2L, 3L), `2010` = c(0L,
  0L, 0L, 5L, 0L), `2011` = c(0L, 0L, 0L, 0L, 1L), `2012` = c(0L,
  0L, 0L, 4L, 1L), `2013` = c(1L, 0L, 1L, 0L, 0L), `2014` = c(0L,
  0L, 2L, 0L, 9L), `2015` = c(0L, 0L, 1L, 0L, 2L), `2016` = c(0L,
  0L, 0L, 0L, 0L), Cutoff = c("2011", "2015", "2015", "2005", "2011"
  )), .Names = c("2005", "2006", "2007", "2008", "2009", "2010",
  "2011", "2012", "2013", "2014", "2015", "2016", "Cutoff"), row.names = c(NA,
  5L), class = "data.frame"))

dt[, row := rownames(dt)]
dt2 = melt(dt, id.vars = c('Cutoff', 'row'), variable.name = 'Year', variable.factor = F)

dt2[, Numbers_Before := ifelse(Year < Cutoff, value, 0)]
dt2[, Numbers_After := ifelse(Year > Cutoff, value, 0)]
dt2[, Years_Before := ifelse(Year < Cutoff, 1, 0)]
dt2[, Years_After := ifelse(Year > Cutoff, 1, 0)]

dt3 = dt2[, .(Numbers_Before = sum(Numbers_Before), Numbers_After = sum(Numbers_After),
              Years_Before = sum(Years_Before), Years_After = sum(Years_After)), by = row]

dt = merge(dt,dt3, by = 'row')

> dt
   row 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 Cutoff Numbers_Before Numbers_After Years_Before Years_After
1:   1    0    0    1    1    1    0    0    0    1    0    0    0   2011              3             1            6           5
2:   2    0    0    0    0    0    0    0    0    0    0    0    0   2015              0             0           10           1
3:   3    0    0    1    0    0    0    0    0    1    2    1    0   2015              4             0           10           1
4:   4    2    1    0    4    2    5    0    4    0    0    0    0   2005              0            16            0          11
5:   5    1    1    3    3    3    0    1    1    0    9    2    0   2011             11            12            6           5

Edit:
Here's using a bit more clever datatable syntax and dcast instead of the ifelses:
dt[, row := rownames(dt)]
dt2 = melt(dt, id.vars = c('Cutoff', 'row'), variable.name = 'Year', variable.factor = F)
dt2 = dt2[Year != Cutoff][, .(Numbers = sum(value), Years = .N), by = .(row, Year > Cutoff, Cutoff)]
dt2 = dcast(dt2, row + Cutoff ~ Year, value.var = c('Numbers', 'Years'), fill = 0)
dt = merge(dt, dt2, by = c('row', 'Cutoff'))

> dt
   row Cutoff 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 Numbers_FALSE
1:   1   2011    0    0    1    1    1    0    0    0    1    0    0    0             3
2:   2   2015    0    0    0    0    0    0    0    0    0    0    0    0             0
3:   3   2015    0    0    1    0    0    0    0    0    1    2    1    0             4
4:   4   2005    2    1    0    4    2    5    0    4    0    0    0    0             0
5:   5   2011    1    1    3    3    3    0    1    1    0    9    2    0            11
   Numbers_TRUE Years_FALSE Years_TRUE
1:            1           6          5
2:            0          10          1
3:            0          10          1
4:           16           0         11
5:           12           6          5

A: Here is a dplyr method:
library(dplyr)
library(tidyr)

df1 %>%
  mutate(ID = row_number()) %>%
  gather(var, value, `2005`:`2016`) %>%
  group_by(ID) %>%
  mutate(Numbers_Before = sum(ifelse(var < Cutoff, value, 0)),
         Numbers_After = sum(ifelse(var > Cutoff, value, 0)),
         Years_Before = sum(ifelse(var < Cutoff, 1, 0)),
         Years_After = sum(ifelse(var > Cutoff, 1, 0))) %>%
  spread(var, value) %>%
  arrange(ID)

Result:
  Cutoff ID Numbers_Before Numbers_After Years_Before Years_After 2005 2006 2007 2008 2009 2010
1   2011  1              3             1            6           5    0    0    1    1    1    0
2   2015  2              0             0           10           1    0    0    0    0    0    0
3   2015  3              4             0           10           1    0    0    1    0    0    0
4   2005  4              0            16            0          11    2    1    0    4    2    5
5   2011  5             11            12            6           5    1    1    3    3    3    0
  2011 2012 2013 2014 2015 2016
1    0    0    1    0    0    0
2    0    0    0    0    0    0
3    0    0    1    2    1    0
4    0    4    0    0    0    0
5    1    1    0    9    2    0


text:
Q: EF comparing strings representing SAP dates in a linq query? In my table there is a varchar field which contains dates. (That's how SAP stores dates)
Anyway to run a query against this field similar to:
from c in db.Set<MyTable>()
   where c.Date >= "20120921" && c.Date <= "20121021"
   select c

I tried to do a String.Compare, but EF can't translate that to sql.
where Stirng.Compare(c.Date, "20120921") >= 0

I also tried to convert both strings to int and do the comparison, and again EF doesn't support that.

A: You can try using SqlFunctions.DateDiff method overload that takes three strings, like this:
var res = from c in db.Set<MyTable>()
   where SqlFunctions.DateDiff("dd", c.Date, "20120921") >= 0
      && SqlFunctions.DateDiff("dd", c.Date, "20121021") < 0
   select c


text:
Q: TapGestureRecognizer calling function in another class and access variables of first class I am calling a function in another class, as soon as I tap onto an UIImageView in my first ViewController:
let tapGestureRecognizer = UITapGestureRecognizer(target: secondclass, action: #selector(secondclass.imageTapped(tapGestureRecognizer:)))

In my secondclass I need to access some variables from my first ViewController.
How can I get a reference to my first ViewController to achieve this?
secondclass:
@objc func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
{

    let tappedImage = tapGestureRecognizer.view as! UIImageView

    //reference to first ViewController needed
}

A: Then add a delegate inside the SecondVC
weak var delegate:FirstVC?

And configure it inside the first vc like
secondclass.delegate = self

A: Try it with delegate between ViewControllers.
protocol ImageDelegate: class {
    func didTapped()
}

class FirstVC: UIViewController, ImageDelegate {
    let imageView: UIImageView!
    let secondVC: SecondVC!

    override func viewDidLoad() {
        super.viewDidLoad()
        secondVC.imageDelegate = self

    }

}
class SecondVC: UIViewController {
    weak var imageDelegate: ImageDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap))
    }

    @objc func handleTap() {
        imageDelegate?.didTapped()
    }
}


text:
Q: Not able to create dynamic tables using Entity Framework with a code-first approach I am trying to create tables dynamically using Entity Framework with a code-first approach. I am dynamically creating class using the System.Reflection.Emit namespace. I am able to add [Table] attribute to class and was also able to add [Key] attribute to a int property. When I try to create table it throws exception that the class has no key defined.
My questions:

*

*Is it mandatory to have a KeyAttribute?

*What is wrong with my code?
I tried to debug and try to find attributes attached to that property and it shows that there are no attributes added but it has custom attribute of type KeyAttribute.
I have statically defined class with KeyAttribute added to one of the property. When I debug that the KeyAttribute was not added in Attributes collection. It was there is GetCustomAttributes()
Create class, add int property and add KeyAttribute using System.Reflection.Emit:
public Type CreateClass(string className)
{
        Type returnValue = null;
        currentClassBuilder = currentModuleBuilder.DefineType(className, TypeAttributes.Public);
        AddTableAttributeToProperty(className);
        AddDefaultConstructor();
        FieldBuilder fieldBuilder = AddField("m_Number", typeof(Int32));
        PropertyBuilder propertyBuilder = AddProperty("Number", typeof(Int32));
        propertyBuilder.SetSetMethod(AddSetMethod(fieldBuilder, typeof(int)));
        propertyBuilder.SetGetMethod(AddSetMethod(fieldBuilder, typeof(int)));
        AddKeyAttributeToProperty(propertyBuilder);
        returnValue = currentClassBuilder.CreateType();
        return returnValue;
 }

In DbContext class
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
        var entityMethod = typeof(DbModelBuilder).GetMethod("Entity");

        foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
        {
            var entityTypes = assembly
              .GetTypes()
              .Where(t =>
                t.GetCustomAttributes(typeof(TableAttribute), inherit: true)
                .Any());

            foreach (var type in entityTypes)
            {
                entityMethod.MakeGenericMethod(type)
                  .Invoke(modelBuilder, new object[] { });
            }
        }
}


text:
Q: Automapper custom inline mapping I have two classes
 public class SourceClass
{
    public Guid Id { get; set; }
    public Guid Provider { get; set; }
}

public class DestinationClass
{
    public Guid Id { get; set; }
    public Guid Provider { get; set; }
    public Guid CustomerId {get; set;}
}

I've initialized my mapping by using the following code
CreateMap<SourceClass, DestinationClass>();

And then in my controller, I have :
Mapper.Map<List<DestinationClass>>(requests)

where "requests" is a List of SourceClass objects being passed in to my controller.
Now, this code works and the mapping works as configured. However, I also get passed a CustomerId and want to set it in the DestinationClass accordingly.
Is there any way to do this while the mapping is occuring, so that I don't have to write an additional loop to set CustomerId in every object in the list?

A: You can pass additional parameter by passing key-value to mapper (as suggested by @LucianBargaoanu). The custom value resolver and map execution can be implemented as:
// Configuration
var configuration = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<SourceClass, DestinationClass>()
      .ForMember(dest => dest.CustomerId, opt =>
      opt.MapFrom((src, dest, destMember, context) =>
      context.Items["CustomerId"]));
});

var mapper = configuration.CreateMapper();

//Sample source class
var sourceClass = new SourceClass { Id = Guid.NewGuid(), Provider = Guid.NewGuid() };

var destClass = mapper.Map<SourceClass, DestinationClass>(sourceClass,
              opt => opt.Items["CustomerId"] = "96b4b6e6-7937-4579-ba01-4a051bc0b93b");

The CustomerId member of destClass object is populated with passed GUID.
Note:SourceClass and DestinationClass definition are taken from OP.


text:
Q: How to parse Gmail chat logs from webpage? What would be the best way to parse Gmail chat logs from the webpage where it's displayed?  As far as I know, this is still the only way to access server-hosted Gmail chat logs (through either desktop Gmail or mobile Gmail).
When looking at the generated source where the conversation takes place, the markup looks like nested divs and spans (and the divs elsewhere on the page have randomized two-character ids and classes with no pattern).  Here's an excerpt from a line that has a timestamp to the left:

2:56 PM

me: i'm trying to think of a good way to parse gmail chat logs

But not every line has a timestamp, so those without one seem to place nonbreaking spaces in its place:

and reformat that into something like an xml format

Should I use XPath?  Is there something more efficient?
Edit:
As data only, this is what it looks like:
12:43 AM John: Something something something.
         Something something something.
         me: Something something something?
12:44 AM Also, something something something.
12:47 AM Something something something.
12:48 AM Something something something
         with something something something.
12:49 AM John: Something.

A:
Should I use XPath? Is there something
  more efficient?

I would use Ruby with the Nokogiri library, it gives you much more flexibility than just XPath/XSLT:
#!/usr/bin/ruby
require 'rubygems'
require 'nokogiri'

src = <<EOS

        2:56 PM

            me: i'm trying to think of a good way to parse gmail chat logs

            and reformat that into something like an xml format

EOS

chatlog = []
last_timestamp = nil
doc = Nokogiri::HTML(src)

doc.xpath('//div/span').each do |span|
    style = span.attributes['style'].value

    if style.include?('color:')
        last_timestamp = span.content.strip
    elsif style.include?('padding-left:')
        chatlog << {:timestamp => last_timestamp, :message => span.content.strip}
    end
end

builder = Nokogiri::XML::Builder.new do |doc|
    doc.chatlog {
        chatlog.each do |line|
            doc.line {
                doc.time    line[:timestamp]
                doc.message line[:message]
            }
        end
    }
end

Returns:
<?xml version="1.0" encoding="UTF-8"?>
<chatlog>
  <line>
    <time>2:56 PM </time>
    <message>me: i'm trying to think of a good way to parse gmail chat logs</message>
  </line>
  <line>
    <time>  </time>
    <message>and reformat that into something like an xml format</message>
  </line>
</chatlog>


text:
Q: Construction and integration of differential forms I'm computing measures on quotient spaces of SO(3) and I have questions about the integration of these measures.
I'm parameterizing SO(3) by the Euler angles
$R(\phi,\theta,\psi) = R_z(\phi)R_y(\theta)R_z(\psi)$
with the ordinary rotation matrices $R_y$ and $R_z$ and $0 \leq \phi \leq 2\pi, 0 \leq \theta \leq \pi, 0 \leq \psi \leq 2 \pi$.
By computing the matrix $R^{-1} dR$, we get all 3 Maurer-Cartan forms:
$\omega_{12} = -\cos \theta\, d \phi - d\psi\\
\omega_{13} = \sin \theta \sin \psi\, d \phi + \cos \psi\, d \theta\\
\omega_{23} = \sin \theta \cos \psi\, d \phi - \sin \psi\, d \theta$
(indices according to position in the matrix $R^{-1} dR$).
The Haar measure of SO(3) can be constructed from the Maurer-Cartan forms
$d \mu = \omega_{12}\wedge \omega_{13} \wedge \omega_{23} = \sin \theta\, d \psi \wedge d \phi \wedge d \theta$
which I can integrate to get the "volume" of SO(3):
$\int d \mu = \iiint \sin \theta \, d \psi d \phi d \theta = 8\pi^2$
Now I take as a 1-dim subgroup H, all elements of SO(3) that leave the $z$-axis invariant. Thus, H is characterized by $\theta = 0, \phi = 0$. This leads to $d \theta = 0, d \phi = 0$ which is equivalent to $\omega_{13} = 0, \omega_{23} = 0$.
The measure on SO(3)/H can then be constructed by
$d \mu_z = \omega_{13} \wedge \omega_{23} = \sin \theta \, d \theta \wedge d \phi$
and I can integrate this to get the "volume" of SO(3)/H:
$\int d \mu_z = \iint \sin \theta \, d \theta d \phi = 4\pi$
(this seems to be correct, because I think that $SO(3)/H \simeq S^2$)
When choosing other axis for the subgroup H (fixing two of the three angles), I come up with the following measures
$d \mu_x = \omega_{12} \wedge \omega_{13} = -\cos \theta \cos \psi \, d\phi \wedge d \theta - \sin \theta \sin \psi \, d\psi \wedge d \phi - \cos \psi \, d\psi \wedge d \theta\\
d \mu_y = \omega_{12} \wedge \omega_{23} = \cos \theta \sin \psi \, d\phi \wedge d \theta - \sin \theta \cos \psi \, d\psi \wedge d \phi + \sin \psi \, d\psi \wedge d \theta$
but I don't know how to integrate them.
I guess they are constructed correctly, because since $d (d\mu_x) = 0, d(d\mu_y) = 0$ they are integrable. I also guess that the result is the same as for $d\mu_z$.
A similar problem arises when I try to do this computation with angle-axis-coordinates for SO(3).
I appreciate any help or suggestions.


text:
Q: How to invoke selenium test into a Jenkins I am new to Jenkins.
I have sample selenium code like below in Java project:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class SampTest
{
    public static void main(String[] args)
    {
        WebDriver driver=new FirefoxDriver();
        driver.get("http://www.google.com");
        System.out.println(driver.getTitle());
        driver.quit();
    }
}

This works perfect.
I configured like below in Jenkins:
Create a new project with name.
In Advanced options, added Workspace as "D:\UD\ProgrammingSamples\Selenium\SeleniumPractice\src"
In build section, i used Execute Windows batch command like "javac SampTest.java | java SampTest"
(Basically i dont know what to use here. Can someone help me here).
When i build the project now i see an error message saying below:
Started by user anonymous
Building in workspace D:\UD\ProgrammingSamples\Selenium\SeleniumPractice\src
[src] $ cmd /c call C:\Users\user\AppData\Local\Temp\hudson578216989100659838.bat

D:\UD\ProgrammingSamples\Selenium\SeleniumPractice\src>javac SampTest.java   | java SampTest
java.lang.NoClassDefFoundError: org/openqa/selenium/WebDriver
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
    at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
    at java.lang.Class.getMethod0(Class.java:3018)
    at java.lang.Class.getMethod(Class.java:1784)
    at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)
    at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)
Caused by: java.lang.ClassNotFoundException: org.openqa.selenium.WebDriver
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 7 more
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" SampTest.java:1: error: package org.openqa.selenium does not exist
import org.openqa.selenium.WebDriver;
                          ^
SampTest.java:2: error: package org.openqa.selenium.firefox does not exist
import org.openqa.selenium.firefox.FirefoxDriver;
                                  ^
SampTest.java:8: error: cannot find symbol
        WebDriver driver=new FirefoxDriver();
        ^
  symbol:   class WebDriver
  location: class SampTest
SampTest.java:8: error: cannot find symbol
        WebDriver driver=new FirefoxDriver();
                             ^
  symbol:   class FirefoxDriver
  location: class SampTest
4 errors

D:\UD\ProgrammingSamples\Selenium\SeleniumPractice\src>exit 1
Build step 'Execute Windows batch command' marked build as failure
Finished: FAILURE


text:
Q: Take a percentage of your clients online payment profits I'm a freelancer and I'm negotiating with a potential client for a full e-commerce website using PayPal Payment Pro.
They want to list and sell everything from cheap fittings/fixtures to very expensive furniture on there new website.
It's a BIG job, and everything would be designed and developed bespoke. Right now were at the £2,500 mark, but I don't think they're going to agree... However, I had a thought.
They make a great profit just from instore sales. I'd be happy to reduce the design/development price by 50% (to possibly 65%) if they agree to give me 3% to 5% of all online sales.
My question is, how would I do this with PayPal Payment Pro?
I can record all online sales and invoice them for 3% to 5% each month, but I'd rather it be done automatically. I can't find any documentation on how to do this, any ideas?

A: What I would recommend is integrating Express Checkout and Pro into the website like usual, and then install Instant Payment Notification on the server to automate payments from the website owner to you.
Within the IPN script you can setup a Pay API request that submits the payment from the website owner's account to your account accordingly.  You can calculate your commission from within this based on the order total and push the funds to your account.
IPN occurs in real-time (or at least generally very close to it) so the procedure would be completely automated at that point and you would get your commission payments immediately when each order goes through.


text:
Q: Unable to install vmware horizon client in ubuntu 18..04 I am trying to install vmware horizon client in ubuntu 18.04. So far I have tried with so many versions of horizon client.
The Installer UI runs fine, just in the last step, it says - installation was unsuccessful. It doesn't give any clue where the issue is. There's some warning error coming in the console as well.
I've tried all the steps I found so far. Nothing works so far. Could someone please help ?
Extracting VMware Installer...done.
(vmware-installer.py:3414): IBUS-WARNING **: 18:16:03.239: The owner of /home/johnz/.config/ibus/bus is not root!
(vmware-installer.py:3414): IBUS-WARNING **: 18:16:03.444: Unable to connect to ibus: Unexpected lack of content trying to read a line
enter image description here


text:
Q: ASP.NET MVC 2 form submit route issue i'm having this issue, in ASP.NET MVC 2 where I'm adding a drop down list on the master page and filling it with data from an abstract master controller. When an option is selected an submit button clicked, it reroutes you to a new page. so lets say
the page lives on http://domain.com/landingPage

*

*i'm on: http://domain.com/landingPage

*i select option and submit

*takes me to http://domain.com/landingPage/Projects/FramedPage

*i select again and now the post tries to go to: http://domain.com/landingPage/Projects/landingPage/Projects/FramedPage because of the action="" i have set on the form tag.

Any ideas on how to go about this?
MasterPage:
<form method="get" action="landingPage/Projects/FramedPage">
 <%= Html.DropDownList("navigationList")%>
 <input id="navSubmitBtn" class="btnBlue" type="submit" value="Take Me There" />
</form>

Projects Controller
public ActionResult FramedPage(string navigationList)
  {
   ViewData["navLink"] = navigationList;
return View();
  }
The problem i am having is that if I am ON that page

A: Use relative location.

<form method="get" action="<%=Url.Action("FramedPage", "ControllerName") %>">


text:
Q: group actions on polynomial rings I am trying to prove that the symmetric group $S_n$ acting on $R[x_1,...,x_n]$ acts by ring homomorphisms. Ostensibly, this isn't so hard; you show that each $\sigma$ acts on the monomials homomorphically, with respect to both addition and multiplication, and then you can build the rest of the polynomials from them additively and multiplicatively. I'm wondering mostly how to formalize the notion of an arbitrary monomial, in the simplest indexical way possible, that covers all possible subscripts and products.
Then I need to prove that the set of all polynomials fixed by $S_n$ forms a subring of $R[x_1,...,x_n]$. I'm not totally sure how to proceed. Some guidance would be appreciated.

A: One way to index a monomial in the variables $x_1,\ldots,x_n$ is to let $I = (m_1,\ldots,m_n)$, $m_i \geq 0$, and then define
$$x^I = x_1^{m_1}\cdots x_n^{m_n}.$$
You want to show that given $\sigma \in S_n$, the map $f_{\sigma} : R[x_1,\ldots,x_n] \to R[x_1,\ldots,x_n]$ by
$$f_{\sigma}(f(x_1,\ldots,x_n)) = f(x_{\sigma(1)},\ldots x_{\sigma(n)})$$
is a ring homomorphism. As you noted, you can do this by checking it on monomials. It's straightforward to check that given $I = (m_1,\ldots,m_n)$ and $I' = (m_1',\ldots,m_n')$
$$f_{\sigma}(x^I + x^{I'}) = f_{\sigma}(x^I) + f_{\sigma}(x^{I'})$$
and
$$f_{\sigma}(x^Ix^{I'}) = f_{\sigma}(x^I)f_{\sigma}(x^{I'}).$$
Once you know that $f_{\sigma}$ is a ring homomorphism, showing that the ring $\Lambda_R$ of polynomials in $R[x_1,\ldots,x_n]$ fixed by $S_n$ is easy. For $f,g \in \Lambda_R$ is equivalent to $f_{\sigma}(f) = f$ and $f_{\sigma}(g) = g$ for all $\sigma \in S_n$. You simply must show that this also holds for $f + g$ and $fg$.

A: If I understood you correctly, you have already proved that $S_n$ acts on $R[x_1, \dots x_n]$ by ring homomorphisms. Then, proving that the set $R[x_1, \dots x_n]^{S_n}$ of fixed polynomials is a ring is just a matter of checking the axioms.
For example, let $f,g$ be two polynomials fixed by all $\sigma \in S_n$. This means that $\sigma f = f$ and $\sigma g = g$. Now, $\sigma(f\cdot g) = \sigma f \cdot \sigma g$ since $\sigma$ is a ring homomorphism, and $\sigma f \cdot \sigma g = f \cdot g$ since $f$ and $g$ are fixed by $\sigma$. Thus, $\sigma(f\cdot g) = f\cdot g$, meaning that $f\cdot g$ is also fixed by $\sigma$, so the set of fixed polynomials is closed under multiplication. Closure under all other ring operations is proved in a similar way, and finally you get that $R[x_1, \dots x_n]^{S_n}$ is actually a subring.

A: To show $f_{\sigma}(f+g) = f_{\sigma}(f)+f_{\sigma}(g)$, an induction argument is necessary here right?
I'm thinking the induction would be on the number of monomials in the polynomial?
The base case is pretty straightforward, and it would just require a hand checking of the properties
$\sigma(f + g) = \sigma f + \sigma g$
$\sigma(fg) = (\sigma f)(\sigma g)$
for f and g two monomials in $x_1, x_2, ..., x_n$.
Then, the inductive hypothesis would be $f_{\sigma}(f_1 + f_2 + ... + f_n) = f_{\sigma}(f_1)+f_{\sigma}(f_2) + ... + f_{\sigma}(f_n)$, where each $f_i$ is a monomial.
Then,
$f_{\sigma}(f_1 + f_2 + ... + f_n + f_{n+1}) = \; ...$
and here we would do some smart trick to show it equals $f_{\sigma}(f_1) + ... + f_{\sigma}(f_{n+1})$? I'm not sure how to complete this induction.
I guess my problem is that I'm not sure what is the definition of the action very clearly. How is the action defined for polynomials in general? When I saw this question first I was presented as "Let $\sigma\in S_n$ act on $(x_1, x_2, ..., x_n)$, and then extend this action to $R[x_1, ..., x_n]$. But "extend this action" is not a mathematically precise statement and so it's a bit hard to expect a mathematically precise proof.


text:
Q: How to fix the error InterpolatingPolynomial::ipdup: The abscissas are not distinct I'm trying to plot the function Abs[InterpolatingPolynomial[..] - f[x]] where f is a function. I receive the error:

InterpolatingPolynomial::ipdup: The abscissas are not distinct.

This is my actual code:
f[c_] := E^(4*c);
Do[x[k] = If[k < 4, 0, 1], {k, 0, 4}];

Plot[Abs[InterpolatingPolynomial[{{x[0], f[x[0]]}, {x[1],
      f[x[1]]}, {x[2], f[x[2]]}, {x[3], f[x[3]]}, {x[4],
      f[x[4]]}}, w] - f[w]], {w, 0, 5}]

Why am I receiving the error and how can I fix it?

A: Summed up and cleaned:
f[c_] := E^(4*c);
x[_] = 0;
x[4] = 1;
t = Union@Table[{x[i], f[x[i]]}, {i, 0, 4}];
Plot[Abs[InterpolatingPolynomial[t, w] - f[w]], {w, 0, 5}]


text:
Q: Stable Marriage Problem but with numerical ratings for each other person instead of a ranking Basically I have a group of people who rate each other from 1-10. I want to find the best way to get them into groups of 5, or preferably be able to change the group size easily.
My main issue with my previous attempts has been efficiency, as there are 1000+ people.
Some additional info is the data comes from a csv but I can convert that to any input that works better, and I have to write in python but again I am happy to convert from another language if someone finds a solution to this problem.
A similar problem I've found is a variation of the stable marriage problem where the group size is customizable.
https://www.reddit.com/r/learnpython/comments/ga0anm/comment/fowyem6/?utm_source=share&utm_medium=web2x&context=3
This is where I found an explanation to that problem. I'm just unsure how to make this work and optimize it for ratings out of ten instead of ordered preferences.
Thanks for any help


text:
Q: Passing iOS objects to React Native I have a object employeeList which contains objects employee and then each employee object has a person object and address object in it and person and address both contain NSString properties and well as a some function e.g.  calculateAge().
I want to pass this employeeList object from the Native side to the react native side but it come up as null, it is because it RN bridge will only send privimite data types.
https://facebook.github.io/react-native/docs/native-modules-ios#argument-types
What is the best way to convert employeeList to a JSON object or a nested map so that it can be viewed in the RN side?

A: You can not send through the bridge objects with nested functions as properties of the same object. But you are able to send native functions/methods  declared in a self built module in Objective-C or Swift.
I would recommend you to export a function calculateAge() in the native module. This function receives as parameter the JSON object employee a returns the desired age of this employee using callbacks or emitting events
although I would use a construction with Promises for that. Also this function could be called when you want on the JS side. However write this kind of function on a native module would make no sense because you can perform the same logic on the JS side.
Export a function in a native module would be useful if the logic needs extra data that only runs on the native side.
Finally make sure that you export an object (NSDictionary) with string keys and values of any type from this list. So you need to convert the object employeeList to a JSON Object and delete nested functions from it in order to avoid compatibility problems.


text:
Q: writing only dictionary values into a text file I just want to write dictionary values into text file line wise line.I can write whole dictionary in to the file using:
log_disk={}
log=open('log.txt','w')
log.write(str(log_disk))
log.close()

Any help will be appreciated.In addition I want to avoid those keys which have value 'Empty' while writing into the file.

A: Just loop over the values then:
with open('log.txt','w') as log:
    for value in log_disk.values():
        log.write('{}\n'.format(value))

A: Write data as JSON unformatted string
You may dump the data as JSON, without formatting JSON data it is written on one line.
Do not forget to append newline:
>>> import json
>>> data = {}
>>> with open(fname, "a") as f:
...     json.dump(data, f)
...     f.write("\n")
...

Try with another data:
>>> data = {"a": "aha", "b": "bebe"}
>>> with open(fname, "a") as f:
...     json.dump(data, f)
...     f.write("\n")
...

It does not have to be dictionary, lists are working too:
>>> data = range(10)
>>> data
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> with open(fname, "a") as f:
...     json.dump(data, f)
...     f.write("\n")
...

Reading data line by line
>>> with open(fname) as f:
...     for line in f:
...         print json.loads(line)
...
{}
{u'a': u'aha', u'b': u'bebe'}
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

A: You just need to convert log_disk.values() to a list and you can write them directly
with open(filename) as openfile:
    json.dump(list(log_disk.values()), file)


text:
Q: Tem como ignorar uma página no log do apache? Estou desenvolvendo uma página a qual fará consulta permanente via Ajax, acontece que o Log de acesso do Apache vai encher muito rapidamente e isso me traz um problema de espaço no servidor, fiquei imaginando como tratar isso, uma solução seria ignorar somente a página onde está o Ajax, pois não vejo necessidade de monitora-la.
Sei que podemos fazer múltiplos logs no apache, mas não sei se podemos ignorar ou escolher determinadas pastas ou páginas do servidor.
Seria possível?

A: Baseado nos DOCS, na secção "Conditional Logs" podemos ver:
# Não incluir nos logs caso a requisição venha do ip abaixo
SetEnvIf Remote_Addr "127\.0\.0\.1" dontlog
# Não incluir nos logs o request abaixo, este é o que tu queres
SetEnvIf Request_URI "^/robots\.txt$" dontlog
# Incluir tudo o resto
CustomLog logs/access_log common env=!dontlog

Colocas o que precisas no teu .htaccess


text:
Q: Custom validation with bootstrap V5 So right now im basically using the default Bootstrap V5 form validator and I was wondering if there is a way to make a custom parameter that needs to be checked in order for the input to be valid. Right now I want the user to input their licenseplate, which must include letters and numbers. I more or less got the must include part, but bootstrap still says that the input is valid, even if its technically not, because it only checks if there is any input in the field. Would there be a way for me to change what bootstrap views as valid?
The default bootstrap validation function looks like this:
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function () {
  'use strict'

  // Fetch all the forms we want to apply custom Bootstrap validation styles to
  var forms = document.querySelectorAll('.needs-validation')

  // Loop over them and prevent submission
  Array.prototype.slice.call(forms)
    .forEach(function (form) {
      form.addEventListener('submit', function (event) {
        if (!form.checkValidity()) {
          event.preventDefault()
          event.stopPropagation()
        }

        form.classList.add('was-validated')
      }, false)
    })
})()

A: After just spending the better part of the afternoon researching the same topic, there is very little information on custom JS validation with the OOB Bootstrap validation. I've concluded there are two viable options:

*

*Using the pattern attribute on the element

*Calling your own JS validation as part of the checkValidity() expression

Pattern Attribute
When creating an input, you can set a pattern attribute on the element.
From the MDN pattern article:
<p>
 <label>Enter your phone number in the format (123) - 456 - 7890
  (<input name="tel1" type="tel" pattern="[0-9]{3}" placeholder="###" aria-label="3-digit area code" size="2"/>) -
   <input name="tel2" type="tel" pattern="[0-9]{3}" placeholder="###" aria-label="3-digit prefix" size="2"/> -
   <input name="tel3" type="tel" pattern="[0-9]{4}" placeholder="####" aria-label="4-digit number" size="3"/>
 </label>
</p>

Here we have 3 sections for a north American phone number with an implicit label encompassing all three components of the phone number, expecting 3-digits, 3-digits and 4-digits respectively, as defined by the pattern attribute set on each.

JS Validation
When invoking the checkValidity() method, inject custom JS validation to invalidate the form's submission.
const myValidation = someValidation()

if (!myValidation || !form.checkValidity()) {
  event.preventDefault()
  event.stopPropagation()
}

When invoking someValidation(), be sure to add/remove the validation classes as-needed:
// valid input
const foo = document.getElementById("foo")
foo.classList.remove("is-invalid")
foo.classList.add("is-valid")

// invalid input
const bar = document.getElementById("bar")
bar.classList.add("is-invalid")
bar.classList.remove("is-valid")

However, I haven't quite figured out how to completely prevent the validation framework from showing the input as valid (checkmark on the right side of the input) even though the classes are set appropriately. I suspect it has something to do with the pattern attribute being empty, which simply means the field cannot be empty, and also needing to invoke the element's reportValidity() method: HTML Spec: reportValidity()
Conclusion
Looks like the pattern attribute and RegEx is the path forward when using this validation framework.
Hopefully someone else can improve this answer with a better path forward using the pure JS method.


text:
Q: MIPS recursive function not working properly I'm doing a factorial recursive function in MIPS. Here is the code:
fact: #a1 = n   a2 = res

addi $t1,$zero,1
beq $a1,$t1,end  # if n == 1 return res
#else
mul $a2,$a2,$a1
subi $a1,$a1,1

jal fact

end:
sb $a2,res
jr $ra

The problem is, this code only works when i write j fact instead of jal fact, with jal fact the code run infinitely for some reason.

A:     fact: #a1 = n   a2 = res

addi $t1,$zero,1
beq $a1,$t1,end  # if n == 1 return res
#else
addi $sp, $sp, 8
sw $a1, 0($sp) #  in the top of the stack store the argument you called fact
sw $ra, 4($sp) # ra holds the return adress ( I do not know whether you know it)
mul $a2,$a2,$a1
subi $a1,$a1,1
jr $ra

jal fact
lw $a1, 0($sp) # load the value from memory adress that the top stack pointer shows to back to the register a1
lw $ra, 4($sp)
addi $sp, $sp, 8 # delete current top , top-1 from the stack
jr $ra

end:
sb $a2,res
jr $ra


text:
Q: asp.net core 3 and identityserver4 I followed the IdentityServer4 tutorial to add authentication to a web api application created with asp.net core 3 preview 9.
My Startup.cs looks like this:
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddAuthorization();
            services.AddAuthentication("Bearer")
                .AddJwtBearer("Bearer", options =>
                {
                    options.Authority = "http://localhost:4800";
                    options.RequireHttpsMetadata = false;

                    options.Audience = "api1";
                });
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

I generate a valid JWT token and add it as Bearer to my requests, but I always get 401 Unauthorized.
The same server works with a web api application created using the .net core 2 sdk.
What's the difference?

A: app.UseAuthentication(); has to be placed before app.UseAuthorization();
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();

        app.UseAuthentication();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });

    }

quickstarts

A: public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers()
        .AddNewtonsoftJson();
    services.AddAuthorization();

    services.AddAuthentication("Bearer")
      .AddJwtBearer("Bearer", options =>
      {
          options.Authority = "http://localhost:5000";
          options.RequireHttpsMetadata = false;

          options.Audience = "api1";
      });

}


text:
Q: IE8 Checkbox or Radios Select Is there any way to run the radio or checkbox in Internet Explorer 8
I think the solution might be in jquery with some values to emulate?
:active
:before
:after

Is example: http://jsfiddle.net/x5E3W/

A: By "run" do you mean it should have the same style in IE 8?
As the example uses a lot of CSS3 features (rounded corners, shadows), the answer is most definitely no.


text:
Q: Flip UIView pre-iOS 4 from left to right I know there's a simple UIViewAnimationOptionTransitionFlipFromLeft and way to implement that, but how do you do something similar (i.e. flip a UIView over) pre-iOS 4, like on the iPad, for example.

A: [UIView beginAnimations: @"flipOverCard1" context: nil];
[UIView setAnimationDuration: 0.5f];
[UIView setAnimationTransition: UIViewAnimationTransitionFlipFromLeft forView: card1 cache: YES];

// Stuff to do while transitioning

[UIView commitAnimations];