text:
Q: C# Datagridview Checkbox Checked Event - multiple rows? I have a datagridview with multiple columns and rows.
The first column contains a checkbox.
I want the user to be able to select multiple checkboxes and then perform an action.
For example if they select checkboxes in rows 1 and 2, the data from other columns in rows 1 and 2 can be selected and passed into a messagebox.
I know i need to use the checkbox_changed event to do this. However I am having trouble working out how to do this for multiple rows?

A: On button Click event do:
static int SelectColumnIndex = 0;
PerformAction_Click(object sender, System.EventArgs e)
{
    string data = string.Empty;
    foreach(DataGridViewRow row in MyDataGridView.Rows)
    {
      if(row.Cells[SelectColumnIndex].Value!=null &&
             Convert.ToBoolean(row.Cells[SelectColumnIndex].Value) == true)
      {
        foreach(DataGridViewCell cell in row.Cells)
        {
          if(cell.OwningColumn.Index!= SelectColumnIndex)
          {
            data+= (cell.Value + " ") ; // do some thing
          }
        }
        data+="\n";
      }
   }
   MessageBox.Show(data, "Data");
}

A: If you want the user to click on a button to perform the action, then what you need to handle is the Click event of the button, not the CheckBox Changed event... When the button is clicked, just go through all rows of your DataGridView and perform an action on rows with a checked checkbox.

A: static int SelectColumnIndex = 0;

PerformAction_Click(object sender, System.EventArgs e)
{
    string data = string.Empty;

    foreach(DataGridViewRow row in MyDataGridView.Rows)
    {
        if(row.Cells[SelectColumnIndex].Value != null
            &&
         Convert.ToBoolean(row.Cells[SelectColumnIndex].Value) == true)
        {
            foreach(DataGridViewCell cell in row.Cells)
            {
                if (cell.OwningColumn.Index != SelectColumnIndex)
                {
                    data+= (cell.Value + " ") ; // do some thing
                 }
            }

            data+="\n";
        }
    }

    MessageBox.Show(data, "Data");
}

A: I think you dont need to any event
i solved this problem by this code:
//In Fill DataGridViewEvent :
        DataGridViewCheckBoxColumn ChCol = new DataGridViewCheckBoxColumn();
        ChCol.Name = "CheckedRow";
        ChCol.HeaderText = "انتخاب";
        ChCol.Width = 50;
        ChCol.TrueValue = "1";
        ChCol.FalseValue = "0";
        dg.Columns.Insert(0, ChCol);

// In Button Event put these codes:

            try
            {
                MessageBox.Show(row.Cells[2].Value.ToString() + " --> " +
                row.Cells["CheckedRow"].Value.ToString());
            }
            catch
            {
                // Nothing Act
            }

enter code here

Your Output by this parameter :
    ItemID --> 0 // For Unchecked Values
    ItemID --> 1 // For Checked Values
Now You Can filter the rows that return 1 as value for your action
i tested this code and it work for me


text:
Q: The process of using taylor series to evaluate limits. For instance we want evaluate this simple limit using taylor series :
$$L=\lim_{x\to 0}\frac{\sin x}{x^5}=\lim_{x\to 0}\frac{x-\frac{x^3}{3!}+\frac{x^5}{5!}-\frac{x^7}{7!}+\frac{x^9}{9!}+\cdots}{x^5}$$
In this case we only care about coefficient of $x^5$ to cancel out $x^5$s in  the fraction and get $L=\frac{1}{5!}$. This is a simple example of what we usually do when evaluating limit using taylor series.
My question is why we ignore other terms of the numerator? I mean:
$$L=\lim_{x\to0}\color{red}{\frac{1}{x^4}-(\frac{1}{3!}\times\frac{1}{x^2})}+\color{green}{\frac{1}{5!}}\color{red}{-(\frac{1}{7!}\times x^2)+(\frac{1}{9!}\times x^4)+\cdots}$$
I don't understand why we can ignore other terms (showed in red color) and confirm $\frac1{5!}$ as the answer. It is obvious that terms appeared on the rightside of $\color{green}{\frac1{5!}}$ are equal to zero but what about other side?

A: We can't ignore the other terms, we obtain indeed
$$\frac{x-\frac{x^3}{3!}+\frac{x^5}{5!}-\frac{x^7}{7!}+\frac{x^9}{9!}+\cdots}{x^5}=\frac1{x^4}-\frac1{3!x^2}+\frac1{5!}+O(x^2) \to \infty$$
the limit is finite for
$$\lim_{x\to 0}\frac{\sin x-\left(x-\frac{x^3}{3!}\right)}{x^5}=\lim_{x\to 0}\frac{\frac{x^5}{5!}-\frac{x^7}{7!}+\frac{x^9}{9!}+O(x^{11})}{x^5}=\frac1{5!}$$

A: The limit is not $\frac{1}{5!}$, in fact the limit does not exist (or, you could say the limit is $+\infty$). You need to take the limit of each individual term. Notice that the first 2 terms diverge at $x=0$ after you divide by $x^5$.
In short, you can't just blindly ignore the other terms. That only works if all the other terms go to $0$.

A: Others have pointed out that the limit does not really exist... But, addressing the general question, it is probably easier to understand (and more correct) if you use Taylor's polynomial instead of taylor's series. Imagine you want to compute a limit that actually exists, like the well known $\lim_{x \to 0}\dfrac{\sin x}{x}$, using Taylor's formula. You know that
$$
\sin x = x - \frac{\cos (\xi_x)}{3!} x^3, \quad \xi_x \in (0,x)
$$
and so,
$$
\lim_{x \to 0} \frac{\sin x}{x} = \lim_{x\to 0}\dfrac{x - \dfrac{\cos (\xi_x)}{3!} x^3}{x} = 1-\frac 16 \underbrace{\lim_{x \to 0}\cos(\xi_x)x^2}_{=0} = 1
$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to display error message to user when snter wrong pass I want when the user enters a wrong name or password to return a message to the user but does not enter into (catch) it only returns in console 401 error
```
[LOGIN](vuexContext, credentials) {
  return new Promise((resolve, reject) => {
    console.log("ip")
      axiosIns.post("login", credentials)
        .then((res) => {
          console.log("lpl")
          console.log(res)
          const token = res.data.token
          localStorage.setItem('token', token)
          axios.defaults.headers.common['Authorization'] = token
          resolve(res)
        }).catch((error) => {
          console.log("reee")
          vuexContext.commit(
            SET_ERROR,
            "incorrect password or user name")
            reject(error)
            throw error;
        });
    });
  },
``


text:
Q: Firebase for half and SQL for another half I have built an app using firestore as we are interested in the realtime updates portion of things. However,we are not building a website that has CRM component where a lot of reports will be generated. The contents of that CRM are all new. There is only one report that would need firebase data as well as the new data (you can say 1 report out of 20).
I was thinking of building the CRM backend off mysql DB? Do you recommend to go with this approach or shall I do the CRM in the same firebase/firestore db?
Thanks

A: If you are looking for a real-time backend database for your CRM, then the Firebase RTDB / Cloud Firestore would be ideal for this.  I'm not sure why you'd want to add a mySQL component, unless you are going to create some reports that require complex joins.  However, if your data is modelled correctly, this also shouldn't be an issue.
Take a look at this video to get a better understanding: What is a NoSQL Database? How is Cloud Firestore structured? - Get to Know Cloud Firestore Ep.1


text:
Q: DataGridView DataSource can't be added to This part of my code is responsible for adding new items to my BindingList<DevicePropertyTable> called DeviceStorage
public void StoreDevice(string deviceName)
        {
            var device = new DevicePropertyTable()
            {
                IEEE = deviceName,
                StateRegister = ""
            };

            DeviceStorage.Add(device);
        }

The problem is, the code hangs on the .Add, because the DGV's DataSource has been assigned as this list.
If I assign it after I filled it with some data it displays correctly, but then I can'd add new items yet again. The DGV seems to hold my List hostage.
How would I go about making the list accessible? Since this code is in a seperate class from the Form, I can't access the DGV directly to just set the DataSource to null.

A: As @user18387401 said in the comments above, this is a problem with accessing the UI thread from a different thread. I got around this by adding 2 methonds and 2 invokers to my From:
public void ReleaseTableDataBindInvoker()
{
    mapping_table.Invoke(new MethodInvoker(ReleaseTableDataBind));
}

public void ReleaseTableDataBind()
{
    mapping_table.DataSource = null;
}

public void BindTableDataInvoker()
{
    mapping_table.Invoke(new MethodInvoker(BindTableData));
}

public void BindTableData()
{
    mapping_table.DataSource = DeviceTableStorage.getInstance().DeviceStorage;
}

note: mapping_table is the name of my DGV
and then I passed a reference to the form when starting the seperate thread, to access these methods. Then I simply release the bind, add my data and re-bind the table.
public static void HandleIncomingMessages(Form1 mainFrom)
        {
           //some code here

            mainFrom.ReleaseTableDataBindInvoker();
            DeviceTableStorage.getInstance().StoreDevice(device_friendly_name);
            mainFrom.BindTableDataInvoker();
        }


text:
Q: How to refactor componentWillReceiveProps to componentDidUpdate or possibly a Hook? I have this application that has a deprecated lifecycle method:
componentWillReceiveProps(nextProps) {
    if (this.state.displayErrors) {
      this._validate(nextProps);
    }
  }

Currently, I have used the UNSAFE_ flag:
UNSAFE_componentWillReceiveProps(nextProps) {
    if (this.state.displayErrors) {
      this._validate(nextProps);
    }
  }

I have left it like this because when I attempted to refactor it to:
componentDidUpdate(prevProps, prevState) {
     if (this.state.displayErrors) {
       this._validate(prevProps, prevState);
     }
   }

It created another bug that gave me this error:

Invariant Violation: Maximum update depth exceeded. This can happen
  when a component repeatedly calls setState inside componentWillUpdate
  or componentDidUpdate. React limits the number of nested updates to
  prevent infinite loops.

It starts to happen when a user clicks on the PAY NOW button that kicks off the _handlePayButtonPress which also checks for validation of credit card information like so:
UNSAFE_componentWillReceiveProps(nextProps) {
    if (this.state.displayErrors) {
      this._validate(nextProps);
    }
  }

  _validate = props => {
    const { cardExpireDate, cardNumber, csv, nameOnCard } = props;

    const validationErrors = {
      date: cardExpireDate.trim() ? "" : "Is Required",
      cardNumber: cardNumber.trim() ? "" : "Is Required",
      csv: csv.trim() ? "" : "Is Required",
      name: nameOnCard.trim() ? "" : "Is Required"
    };

    if (validationErrors.csv === "" && csv.trim().length < 3) {
      validationErrors.csv = "Must be 3 or 4 digits";
    }

    const fullErrors = {
      ...validationErrors,
      ...this.props.validationErrors
    };
    const isValid = Object.keys(fullErrors).reduce((acc, curr) => {
      if (fullErrors[curr]) {
        return false;
      }

      return acc;
    }, true);

    if (isValid) {
      this.setState({ validationErrors: {} });
      //register
    } else {
      this.setState({ validationErrors, displayErrors: true });
    }

    return isValid;
  };

  _handlePayButtonPress = () => {
    const isValid = this._validate(this.props);

    if (isValid) {
      console.log("Good to go!");
    }

    if (isValid) {
      this.setState({ processingPayment: true });
      this.props
        .submitEventRegistration()
        .then(() => {
          this.setState({ processingPayment: false });
          //eslint-disable-next-line
          this.props.navigation.navigate("PaymentConfirmation");
        })
        .catch(({ title, message }) => {
          Alert.alert(
            title,
            message,
            [
              {
                text: "OK",
                onPress: () => {
                  this.setState({ processingPayment: false });
                }
              }
            ],
            {
              cancelable: false
            }
          );
        });
    } else {
      alert("Please correct the errors before continuing.");
    }
  };

Unfortunately, I do not have enough experience with Hooks and I have failed at refactoring that deprecated lifecycle method to one that would not create trouble like it was doing with the above error. Any suggestions at a better CDU or any other ideas?

A: You need another check so you don't get in an infinite loop (every time you call setState you will rerender -> component did update -> update again ...)
You could do something like this:
componentDidUpdate(prevProps, prevState) {
     if (this.state.displayErrors && prevProps !== this.props) {
       this._validate(prevProps, prevState);
     }
   }

Also I think that you need to call your validate with new props and state:
this._validate(this.props, this.state);

Hope this helps.

A: componentDidUpdate shouldn't replace componentWillRecieveProps for this reason. The replacement React gave us was getDerivedStateFromProps which you can read about here https://medium.com/@baphemot/understanding-react-react-16-3-component-life-cycle-23129bc7a705. However, getDerivedStateFromProps is a static function so you'll have to replace all the setState lines in _validate and return an object instead.

A: This is how you work with prevState and hooks.
Working sample Codesandbox.io
import React, { useState, useEffect } from "react";
import "./styles.css";

const ZeroToTen = ({ value }) => {
  const [myValue, setMyValue] = useState(0);
  const [isValid, setIsValid] = useState(true);

  const validate = value => {
    var result = value >= 0 && value <= 10;
    setIsValid(result);
    return result;
  };

  useEffect(() => {
    setMyValue(prevState => (validate(value) ? value : prevState));
  }, [value]);

  return (
    <>
      {myValue}

        {isValid
          ? `${value} Is Valid`
          : `${value} is Invalid, last good value is ${myValue}`}

    </>
  );
};

export default function App() {
  const [value, setValue] = useState(0);

  return (

      <button value={value} onClick={e => setValue(prevState => prevState - 1)}>
        Decrement
      </button>
      <button value={value} onClick={e => setValue(prevState => prevState + 1)}>
        Increment
      </button>

Current Value: {value}

      <ZeroToTen value={value} />

  );
}

We have two components, one to increase/decrease a number and the other one to hold a number between 0 and 10.
The first component is using prevState to increment the value like this:
onClick={e => setValue(prevState => prevState - 1)}

It can increment/decrement as much as you want.
The second component is receiving its input from the first component, but it will validate the value every time it is updated and will allow values between 0 and 10.
useEffect(() => {
    setMyValue(prevState => (validate(value) ? value : prevState));
  }, [value]);

In this case I'm using two hooks to trigger the validation every time 'value' is updated.
If you are not familiar with hooks yet, this may be confusing, but the main idea is that with hooks you need to focus on a single property/state to validate changes.


text:
Q: Array formula not calculating on Excel MAC 2020 I have an issue with my Mac to enter an array formula.
I detail what I did so far.

*

*I choose the output cells of the formula

*Write the formula

*press CMD+SHIFT+RETURN

It does not transform the formula into an array formula with the brackets {},
It only makes a line break on my formula. I tried pressing F2 upfront CMD+SHIFT+RETURN but it doesn't work neither.
Can you help me with this one ?
I've seen there are many people having the same issue on Excel Mac 2020, but didn't find any solution so far.
Best


text:
Q: Initialization of Auxillary Property Maps in Boost Graph Library Objective
Generate a random spanning tree on a randomly generated graph.
Why: because I don't know yet if I can directly generate random trees with specific number of nodes or leaves in BGL.
My problem
I think it boils down to struggling initializing the Auxillary Property Maps to a sensical default.
As you will see I've tried a number of combination of solutions, in the current state the code fails to compile with a  cannot form a reference to 'void'.
What I tried
  template<class Graph, class Generator>
  auto generate_random_spanning_tree(int n_vertices, int n_edges, Generator& rng)
  {
    // create empty graph
    Graph g;

    using vertex_t = typename Graph::vertex_descriptor;
    using edge_t = typename Graph::edge_descriptor;

    // The key and value types of the map must both be the graph's vertex type.
    using predecessor_map_t = boost::static_property_map<vertex_t, vertex_t>;
    predecessor_map_t predecessor_map = boost::make_static_property_map<vertex_t,vertex_t>(vertex_t());

    // unweighted version selected by passing an object of type static_property_map<double> as the weight map, so let's go
    using weight_map_t = boost::static_property_map< double >;
    // weight_map_t weight_map = boost::make_transform_value_property_map([](edge_t& e) { return 1.0; }, get(boost::edge_bundle, g)); // nope
    //weight_map_t weight_map = boost::make_static_property_map<double>(1.0); // yes but complicated
    // weight_map_t weight_map;  // nope: why isn't it default constructible?
    double my_constant_weight = 1.0;
    weight_map_t weight_map(my_constant_weight);

    using color_map_t = typename boost::property_map<Graph, boost::vertex_color_t>::type;
    color_map_t color_map ; // i suspect this is faulty

    // mutate graph
    boost::generate_random_graph(g, n_vertices, n_edges, rng);

    // pick root, I guess we could as well pick 1st vertex
    auto root = boost::random_vertex(g, rng);

    boost::random_spanning_tree(g, rng, root, predecessor_map, weight_map, color_map);
    return g;
  }

A: First: Your own suspect
using color_map_t = typename boost::property_map<Graph, boost::vertex_color_t>::type;
color_map_t color_map; // i suspect this is faulty

Yes. PropertyMaps map properties. They are like references. Here, color_map
is essentially an unitialized reference. You need something like
color_map_t color_map = get(boost::vertex_color, g);

This, of course, assumes that a vertex_color_t property map has been
associated with the graph by traits. In other words, this assumes that the
property is an iternal property of the graph. Internal properties are often
used by default.
Second: A constant cannot be modified
You use a static property map:
auto predecessor_map =
    boost::make_static_property_map<vertex_t, vertex_t>(vertex_t());

That just creates a "virtual" property map (without a backing data structure)
that returns the construction parameter on every key. Logically, the return
value is constant. However, predecessor map is an output parameter:

You will need an LValuePropertyMap there. E.g.
std::map<vertex_t, vertex_t> predecessors;
auto predecessor_map =boost::make_assoc_property_map(predecessors);

Or even
auto vindex          = get(boost::vertex_index, g);
auto predecessors    = std::vector<vertex_t>(num_vertices(g));
auto predecessor_map = boost::make_safe_iterator_property_map(
    predecessors.begin(), predecessors.size(), vindex);

Which uses a vertex index to (optionally) translate descriptors into vector
indices. Note that the second is fixed-size, so initialize it after creating
all vertices.
Other Points Of Interest
// weight_map_t weight_map;  // nope: why isn't it default constructible?

What would it do? Surely it won't default to what you think is a good default
(1.0). So I'd just write
auto weight_map = boost::static_property_map(1.0);

Simplified
I'd write the entire function as:
template <class Graph, class Generator>
auto generate_random_spanning_tree(int n_vertices, int n_edges, Generator& rng) {
    using vertex_t = typename Graph::vertex_descriptor;

    Graph g;
    generate_random_graph(g, n_vertices, n_edges, rng);

    std::map<vertex_t, vertex_t> predecessors;
    random_spanning_tree(g, rng, random_vertex(g, rng),
                         boost::make_assoc_property_map(predecessors),
                         boost::static_property_map(1.0), // unweighted
                         get(boost::vertex_color, g));
    return g;
}

Functional Problems
You're asking some good questions yourself. But let me start with some observations.

*

*You have Unspecified/Undefined
Behaviour because your
input graph doesn't conform to the requirements:

There must be a path from every non-root vertex of the graph to the
root; the algorithm typically enters an infinite loop when given a
graph that does not satisfy this property, but may also throw the
exception loop_erased_random_walk_stuck if the search reaches a vertex
with no outgoing edges

Indeed, running your code only completes for a few random seeds, and fails
or runs infinitely for others (this is even increasing the chance of
satisfying the requirements by using undirectedS):
Listing
 while true; do (set -x; time ./build/sotest& sleep 3; kill %1); done

*You are creating the random spanning tree only to completely forget about
it. Did you intend to return the predecessor map as well (or a derived path
representation)?

*Your own questions:

*

*"cannot form a reference to 'void'"
Usually indicates an associated property map could not be found (e.g.
what happens if you fail to supply the vertex_color interior
property. In
this case the remedy is simply to use the default color
map:
 random_spanning_tree(
     g, rng,
     boost::root_vertex(random_vertex(g, rng))
         .predecessor_map(boost::make_assoc_property_map(predecessors))
         .weight_map(boost::static_property_map(1.0)) // unweighted
 );

*"I don't know yet if I can directly generate random trees with specific
number of nodes or leaves in BGL."
You can generate random graphs with specific number of nodes and leaves -
as you already demonstrate.
trees.
You can also find random spanning trees (given a graph satisfying the preconditions).
To adhere to the preconditions the simplest way would be to generate
undirected graphs, whilst additionally making sure that the result is
connected. A simple, possible inefficient(?) way to ensure it would be to
explicitly connect components:
 if (int n = boost::connected_components(ug, cmap); n > 1) {
     std::cout << "Connecting " << n << " components:\n";

     for (int c = 1; c < n; ++c)
         std::cout << "Added " << add_edge(from(c - 1), from(c), ug).first << "\n";
 }

It might be more effective to write your own generating algorithm.
BONUS EXAMPLE
Showing the use of connected_components to make sure the graph is fully
connected, and even building a directed tree from undirected source graph. Also
writing graphviz representations of the "raw" (undirected) source and "tree"
(directed spanning tree), it seems to work pretty well.
Live On Coliru
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/connected_components.hpp>
#include <boost/graph/graph_utility.hpp>
#include <boost/graph/graphviz.hpp>
#include <boost/graph/random.hpp>
#include <boost/graph/random_spanning_tree.hpp>
#include <boost/property_map/function_property_map.hpp>
#include <iomanip>
#include <random>

namespace detail {
    template <typename T> struct make_undirected { using type = void; };

    template <typename A, typename B, typename C, typename D, typename E, typename F>
    struct make_undirected<boost::adjacency_list<A, B, C, D, E, F>> {
        using type = boost::adjacency_list<A, B, boost::undirectedS, D, E, F>;
    };
} // namespace detail

template <typename T> using Undirect = typename detail::make_undirected<T>::type;

template <class Graph, class Generator>
auto generate_random_spanning_tree(int n_vertices, int n_edges, Generator& rng) {
    using UG = Undirect<Graph>;
    using vertex_t = typename UG::vertex_descriptor;

    // assuming integral vertex index for simplicity
    static_assert(std::is_same_v<vertex_t, size_t>);
    static_assert(std::is_same_v<typename UG::vertex_descriptor,
                                 typename Graph::vertex_descriptor>);

    UG ug;
    generate_random_graph(ug, n_vertices, n_edges, rng);
    vertex_t const root = random_vertex(ug, rng);

    print_graph(ug, std::cout << "Raw root: " << root << ", graph:\n");

    { // make connected
        std::map<vertex_t, int> components;

        auto from = [&](int component) { // just picking the first...
            for (auto& [v, c] : components) if (c == component) return v;
            throw std::range_error("component");
        };

        auto cmap = boost::make_assoc_property_map(components);
        if (int n = connected_components(ug, cmap); n > 1) {
            std::cout << "Connecting " << n << " components:\n";

            for (int c = 1; c < n; ++c)
                std::cout << "Added " << add_edge(from(c - 1), from(c), ug).first << "\n";
        }
    }

    std::map<vertex_t, vertex_t> predecessors;
    random_spanning_tree(
        ug, rng,
        boost::root_vertex(root) //
            .predecessor_map(boost::make_assoc_property_map(predecessors)));

    Graph tree(num_vertices(ug)); // build a tree copy
    for (auto v : boost::make_iterator_range(vertices(ug)))
        if (predecessors.contains(v))
            if (auto pred = predecessors.at(v); ug.null_vertex() != pred)
                add_edge(predecessors.at(v), v, tree);

    auto save = [&predecessors](auto& g, auto name) {
        using edge_t = typename std::decay_t<decltype(g)>::edge_descriptor;
        auto tree_edge = [&predecessors](auto s, auto t) {
            auto it = predecessors.find(s);
            return it != end(predecessors) && it->second == t;
        };

        boost::dynamic_properties dp;
        dp.property("node_id", get(boost::vertex_index, g));
        dp.property("color",
                    boost::make_function_property_map<edge_t>([tree_edge, &g](edge_t e) {
                        auto s = source(e, g), t = target(e, g);
                        return tree_edge(s, t) || tree_edge(t, s) ? "red" : "gray";
                    }));

        std::ofstream os(name);
        write_graphviz_dp(os, g, dp);
    };
    save(ug, "raw.dot");
    save(tree, "tree.dot");

    return std::pair(std::move(tree), root);
}

int main(int argc, char** argv) {
    using G = boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS>;

    auto const seed = argc > 1 ? std::stoull(argv[1]) : std::random_device{}();
    std::cout << "seed: " << seed << std::endl;

    std::mt19937 prng(seed);
    auto [tree, root] = generate_random_spanning_tree<G>(10, 20, prng);

    print_graph(tree, std::cout << "From root: " << root << ", tree:\n");
}

Prints the sample seed: 1577455792
Raw root: 7, graph:
0 <--> 7 2 3 7 5 2 8
1 <-->
2 <--> 8 0 4 0 4 9
3 <--> 9 5 0 8
4 <--> 7 7 2 2 5
5 <--> 8 3 0 4
6 <-->
7 <--> 4 4 0 8 0
8 <--> 2 5 7 9 0 3
9 <--> 3 8 2
Connecting 3 components:
Added (0,1)
Added (1,6)
From root: 7, tree:
0 --> 1 3
1 --> 6
2 --> 9
3 --> 5
4 --> 2
5 --> 4 8
6 -->
7 --> 0
8 -->
9 -->

Running locally with:
watch './build/sotest; for a in raw tree; do (set -x ; dot -Tpng -o $a.png $a.dot); done'

Shows random solutions like:


text:
Q: unable to open port in Qt 5.0.2 I am designing a real time application on Qt. got stuck in QExtserialport
the design has hardware part which sense and send signal through UART communication. I design application to display GUI interface. the following code not open port in Qt. but it does on Minicom, cutecom display value's.
HeadeFile.h
INCLUDEPATH += .
include(..project/qextserialport-1.2rc/src/qextserialport.pri)

CONFIG += extserialport

Mainwindow.cpp
Qextserialport *rs232_;

Mainwindow.cpp
rs232_ = new QextSerialPort("/dev/ttyS0");
rs232_->open( QIODevice::ReadWrite );
if (!rs232_->isOpen()) {
    qDebug()<<"....Port ttyS0 CanNot Open...."<<endl
}
rs232_->setBaudRate(BAUD4800);
rs232_->setFlowControl(FLOW_OFF);
rs232_->setParity(PAR_ODD);
rs232_->setDataBits(DATA_8);
rs232_->setStopBits(STOP_1);

QTimer *s2_timer = new QTimer(this);
s2_timer->setInterval(17);
s2_timer->start();

connect(rs232_, SIGNAL(readyRead()), this, SLOT(onDataAvailable()));

it always display "Port ttyS0 CanNot Open"

A: updated Qt to 5.6, solved by QtSerialPort.
http://doc.qt.io/qt-5/qtserialport-index.html


text:
Q: How should I get user input in a model using MVVM pattern? I'm writing a program using c# and MVVM pattern. This program has an online connection, which requires a login. I've created a model class to handle the login process.
The login process goes like this: the login credentials (user name and password) are sent to a login page online, and on successful login, the server sends back login cookies. I store those cookies locally, and send them with each request from the server, until they expire.
I've created a GetLoginCookies() method in the model, which I'd like to be the only method to get the login cookies. The login in this method is as follows: get the stored login cookies, and verify them with the server. If there are no login cookies, or they are invalid (e.g. expired), the ask the user for new credentials, and send them to the server and get new login cookies.
The reason I want to handle everything in one method, is that I want to have one method that will always give me valid login cookies (or abort the operation) that I can use before any communication with the server.
My question is, what's the best way to implement the user input when using MVVM pattern?

A: Instead of a model you want a service. A service is just a utility class that can be injected into your ViewModels via dependency injection (you are using an IoC?)
Given logging in is just part of the system, and the cookie will be needed to perform other web calls I would create a service for the complete server interaction. That way the service can keep the cookie internally and your app doesn't have to worry about the details of login interaction.
For example
public class WebService {
    public void Login(string username, string password) { ... }
    public Data GetData() { ... }
    public void AddNewData(Data data) { ... }
}


text:
Q: Cronjob wget triggers http requests multiple times in unpredictable intervals I setup the crons in ubuntu server for php services using wget and I run crons on every 5 min. It was worked good for some days. Recently, I got an issue that service is running twice or thrice (as per output of application logs) but cron ran for only one time (as per syslog).
I have gone through with link Why is this cron entry executed twice? but it didn't work for me. I have only one PID (ps -aux | grep 'cron') and I restarted,stopped,started the cron service (service cron restart/stop/start) but none of them worked for me. So finally I restarted the server as cron job is init service but after restarting also, I got same issue.
Cron running as root user.
Cron:
*/5 * * * * /usr/bin/wget --no-check-certificate  https://**********/controlller/method

From Syslog:
Jul 31 12:05:01 web-server CRON[26997]: (root) CMD (/usr/bin/wget --no-check-certificate  https://xx.xx.xx.xx/controller/method)
Jul 31 12:10:01 web-server CRON[27222]: (root) CMD (/usr/bin/wget --no-check-certificate  https://xx.xx.xx.xx/controller/method)
Jul 31 12:15:01 web-server CRON[27470]: (root) CMD (/usr/bin/wget --no-check-certificate  https://xx.xx.xx.xx/controller/method)
Jul 31 12:20:01 web-server CRON[27768]: (root) CMD (/usr/bin/wget --no-check-certificate  https://xx.xx.xx.xx/controller/method)

ps -aux | grep 'cron'
root      1079  0.0  0.0  26012   696 ?        Ss   Jul30   0:03 cron

From Application logs:
31 Jul 2019 12:05:01 [26836] DEBUG [xx.xx.xx.xx]:entered into controller/method
31 Jul 2019 12:05:01 [26922] DEBUG [xx.xx.xx.xx]:entered into controller/method
31 Jul 2019 12:13:00 [27378] DEBUG [xx.xx.xx.xx]:entered into controller/method
31 Jul 2019 12:13:01 [27376] DEBUG [xx.xx.xx.xx]:entered into controller/method
31 Jul 2019 12:23:47 [27733] DEBUG [xx.xx.xx.xx]:entered into controller/method
31 Jul 2019 12:23:47 [27674] DEBUG [xx.xx.xx.xx]:entered into controller/method

From Apache2 access logs:
xx.xx.xx.xx - - [31/Jul/2019:12:05:01 +0200] "GET /controller/method HTTP/1.1" 200 6914 "-" "Wget/1.15 (linux-gnu)"
xx.xx.xx.xx - - [31/Jul/2019:12:05:01 +0200] "GET /controller/method HTTP/1.1" 200 6909 "-" "Wget/1.15 (linux-gnu)"
xx.xx.xx.xx - - [31/Jul/2019:12:13:01 +0200] "GET /controller/method HTTP/1.1" 200 6862 "-" "Wget/1.15 (linux-gnu)"
xx.xx.xx.xx - - [31/Jul/2019:12:13:00 +0200] "GET /controller/method HTTP/1.1" 200 6862 "-" "Wget/1.15 (linux-gnu)"
xx.xx.xx.xx - - [31/Jul/2019:12:23:47 +0200] "GET /controller/method HTTP/1.1" 200 6862 "-" "Wget/1.15 (linux-gnu)"
xx.xx.xx.xx - - [31/Jul/2019:12:23:47 +0200] "GET /controller/method HTTP/1.1" 200 6862 "-" "Wget/1.15 (linux-gnu)"


text:
Q: Cakephp not sure if this business logic belongs in View? I beginning experimenting with CakePHP, and I am contemplating whether calculation, probably business, logic that would determine what gets presented on the View should be in the view or somewhere else.
The issue why I end up putting them in the view is because the data is only available when I do a foreach loop. Here is a simple example:
    <?php foreach ($records as $record):
        $amountDifference = $record['Record']['outstanding'] - $record['Record']['paid'];

        if ($amountDifference > 5){
            echo "greater than 5";
         }else{
            echo "less than 5";
         }

    endforeach; ?>

What do you all say?

A: A few things to point out...
First, in this case, your code is fine as is. It's simple stuff, so I'd say it doesn't matter too much if it's in the model or the view.

The issue why I end up putting them in the view is because the data is
  only available when I do a foreach loop.

Second, and more importantly, it's important to know that the "foreach" loop is no barrier, and you could easily do that in your model if you wanted. You'd just make a method in your model something like this:
public function findAllWithAmountDifference(){
    $records = $this->find('all');

    // Now go through your records and adjust, before returning them
    foreach ($records as &$record):
        $record['Record']['difference'] = $record['Record']['outstanding'] - $record['Record']['paid'];
    endforeach;

    // Now your return value will have extra array keys with the difference
    return $records;
}

And third, I would say that the best way to do it in this particular case would be to use virtual fields (http://book.cakephp.org/2.0/en/models/virtual-fields.html), so the calculations take place as part of the database query.
Last, there is obviously not always a totally clear cut between what is deemed presentation logic, and what is deemed business logic. In simple cases like yours, it could go either way, and it's not worth losing sleep over.
Strictly speaking, calculating the difference between two values is manipulation of data, and therefore belongs in the model.
Having said that, if you think your code will be more transparent, and easier to understand and maintain, with that code in your view rather than your model, the just put it in the view!
The thing about code theory and best practices is that they are intended as a general guide to making your code easier to debug / read / extend / maintain. Usually, they're pretty good, but they're not absolute rules. And in cases where violating a rule or best practice will genuinely make your code easier to debug / read / maintain, then fine! Violate away!


text:
Q: List exceeds threshold. query large lists I have a list that exceeds the 5000 threshold. total is 16013. Is it possible to query lists of this size. I can get all of contents with no query in batch using
query..ListItemCollectionPosition

But can I query just folders and then files, in the test I am running I have a folder that contains 16000 files and then a single folder. Can I query this list efficiently to find this folder. I've tried this:
query.ViewXml = @"<View><Query><Where><BeginsWith><FieldRef Name='ContentTypeId' /><Value Type='ContentTypeId'>0x0120</Value></BeginsWith></Where></Query><RowLimit>" + FileFoldeBatchSize + "</RowLimit></View>";

then when I want to query for files this :
query.ViewXml = @"<View><Query><Where><Eq><FieldRef Name='FSObjType' /><Value Type='Lookup'>0</Value></Eq></Where></Query><RowLimit>" + FileFoldeBatchSize + "</RowLimit></View>";

When trying to query for files, this will timeout with the following set:
clientContext.RequestTimeout = 1800000;

I've tried setting different row limits and still the same result

A: As far as I can tell, it seems like MS made an unannounced change related to this at some point in the last 2-4 weeks. You used to be able to prevent the threshold error by filtering based on indexed/built-in fields, (so long as the filtered results counted less than 5000) but that no longer seems to be the case.
That said, I have two suggestions that might work for you. The first is a generic solution that should work for both lists and libraries, while the second is specifically for libraries.
List/Library Solution
Since you already know about retrieving the list item in batches, this is more for other people looking for an answer to their threshold-related issue. The FilesOnly value in the Scope attribute might help your situation, though.
I ran into an issue a few weeks back where one of my applications started hitting the threshold error after running fine for 2 years. After trying all sorts of modifications to the query, I finally ended up with the following:
    private static CamlQuery BuildFilesQuery(List spList, string queryFolder=null)
    {
        if(String.IsNullOrEmpty(queryFolder) && !spList.RootFolder.IsPropertyAvailable("ServerRelativeUrl")) {
            spList.Context.Load(spList.RootFolder,
                folder => folder.ServerRelativeUrl
            );
            spList.Context.ExecuteQuery();
            queryFolder = spList.RootFolder.ServerRelativeUrl;
        }

        return new CamlQuery() {
            ViewXml = @"
                <View Scope='FilesOnly'>
                    <RowLimit>5000</RowLimit>
                </View>",
            FolderServerRelativeUrl = queryFolder
        };
    }

    public static IList<ListItem> LoadRecordsQuery(List spList, string queryFolder=null, CamlQuery spQuery=null, ListItemCollectionPosition position=null)
    {
        spQuery = spQuery ?? BuildQuery(spList, queryFolder);
        spQuery.ListItemCollectionPosition = position;
        ListItemCollection spItems = spList.GetItems(spQuery);
        spList.Context.Load(spItems, items => items.ListItemCollectionPosition);
        spList.Context.ExecuteQuery();

        List<ListItem> spItemsList = spItems.ToList();
        if(spItems.ListItemCollectionPosition != null) {
            spItemsList.AddRange(LoadRecordsQuery(spList, queryFolder, spQuery, spItems.ListItemCollectionPosition));
        }

        return spItemsList;
    }

To use this, you'd call: LoadRecordsQuery(spList) This should give you all of the files (or list items) in the root folder of your list/library. If you want to query the files in a subfolder instead, pass the folder's server-relative url to the queryFolder parameter. Unfortunately you'll have to do any sorting/filtering on the client side, as the threshold behavior has become inconsistent when <Where> and <OrderBy> clauses are used. (at least in my experience)
If I understood correctly, you already have a working solution for querying folders. If not, let me know and I'll edit this section.
Library-Only Solution (WebDAV)
In your case, you're working on a document library, so you can use the WebDAV interface to list all files and folders in one request: (takes a little while, since it's such a big response)
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.IO;
    using System.Net;
    using System.Xml;

    using Microsoft.SharePoint.Client.Utilities;

    namespace Microsoft.SharePoint.Client
    {
        internal static class FolderExtensions
        {
            #region Constants

            const int RequestTimeout = 60000;

            const string DAVNS = @"DAV:";
            const string UserAgent = @"Microsoft-WebDAV-MiniRedir/6.1.7601";
            const string PropFindBody = @"<?xml version=""1.0"" encoding=""utf-8"" ?><propfind xmlns=""DAV:""><propname/></propfind>";

            #endregion

            #region DAV XML Parsing

            internal static XmlElement GetDAVElement(this XmlDocument self, string localName)
            {
                foreach(XmlElement element in self.GetElementsByTagName(localName, DAVNS))
                    return element;
                return null;
            }

            internal static XmlElement GetDAVElement(this XmlElement self, string localName)
            {
                foreach(XmlElement element in self.GetElementsByTagName(localName, DAVNS))
                    return element;
                return null;
            }

            internal static XmlNodeList GetDAVElements(this XmlDocument self, string localName)
            {
                return self.GetElementsByTagName(localName, DAVNS);
            }

            internal static XmlNodeList GetDAVElements(this XmlElement self, string localName)
            {
                return self.GetElementsByTagName(localName, DAVNS);
            }

            internal static IEnumerable<XmlElement> GetDAVResponses(this XmlDocument self)
            {
                foreach(XmlElement davElement in self.GetDAVElements(@"response")) {
                    yield return davElement;
                }
            }

            internal static string GetResponseHref(this XmlElement self)
            {
                // ReSharper disable once PossibleNullReferenceException
                return HttpUtility.UrlKeyValueDecode(self.GetDAVElement(@"href").InnerText.TrimEnd('/'));
            }

            internal static string GetRelativeResponseHref(this XmlElement self, string folderUrl)
            {
                return self.GetResponseHref().Substring(folderUrl.Length);
            }

            internal static bool IsFolderResponse(this XmlElement self)
            {
                return self.GetDAVElement("isFolder") != null;
            }

            #endregion

            #region Request Factories

            public static HttpWebRequest CreateWebRequest(this ClientContext self, Uri requestUri, string requestMethod=WebRequestMethods.Http.Get)
            {
                // Grab a reference to the SPO credentials object.
                SharePointOnlineCredentials spoCreds = self.Credentials as SharePointOnlineCredentials;
                if(spoCreds == null) {
                    throw new InvalidOperationException("Request methods are only meant to be used with SharePoint Online.");
                }

                HttpWebRequest oRequest = (HttpWebRequest)WebRequest.Create(requestUri);
                oRequest.Pipelined = true;
                oRequest.UserAgent = UserAgent;
                oRequest.Method = requestMethod;
                oRequest.Timeout = RequestTimeout;
                // Wasteful. This re-processes the authentication logic every time to call it in order
                // to generate a new authentication cookie. This should definitely be cached somewhere in
                // your real code.
                oRequest.Headers[HttpRequestHeader.Cookie] = spoCreds.GetAuthenticationCookie(requestUri, true);
                return oRequest;
            }

            public static HttpWebRequest CreateListRequest(this ClientContext clientContext, Uri folderUri, string requestBody = null)
            {
                char[] requestBodyChars = (requestBody ?? PropFindBody).ToCharArray();
                HttpWebRequest oRequest = CreateWebRequest(clientContext, folderUri, "PROPFIND");
                oRequest.Headers["Depth"] = "infinity,noroot";
                oRequest.Headers["Translate"] = "f";
                oRequest.ContentLength = requestBodyChars.LongLength;
                using(Stream requestStream = oRequest.GetRequestStream()) {
                    using(StreamWriter writer = new StreamWriter(requestStream)) {
                        writer.Write(requestBodyChars);
                        writer.Close();
                    }
                    requestStream.Close();
                }
                return oRequest;
            }

            #endregion

            #region List Request Processing

            public static IEnumerable<String> ListRecursively(this Folder oFolder, bool filesOnly=true)
            {
                // Grab references to the ClientContext and SPO Credentials objects.
                ClientContext clientContext = oFolder.Context as ClientContext;
                Debug.Assert(clientContext != null);
                SharePointOnlineCredentials spoCreds = clientContext.Credentials as SharePointOnlineCredentials;
                if(spoCreds == null) {
                    throw new InvalidOperationException("ListFolder method is only meant to be used with SharePoint Online.");
                }

                // Load the ServerRelativeUrl property on our folder if necessary.
                if(!oFolder.IsPropertyAvailable("ServerRelativeUrl")) {
                    clientContext.Load(oFolder, folder => folder.ServerRelativeUrl);
                    clientContext.ExecuteQuery();
                }

                // Build the folder's absolute url.
                Uri folderUri = new Uri(
                    new Uri(clientContext.Url).GetLeftPart(UriPartial.Authority) +
                    oFolder.ServerRelativeUrl
                );

                // Read the request response as an xml document.
                XmlDocument responseXml = new XmlDocument();
                HttpWebRequest oRequest = CreateListRequest(clientContext, folderUri);
                using(Stream responseStream = oRequest.GetResponse().GetResponseStream()) {
                    Debug.Assert(responseStream != null);
                    using(XmlReader reader = XmlReader.Create(responseStream)) {
                        responseXml.Load(reader);
                    }
                }

                // Process the response xml document
                foreach(XmlElement element in responseXml.GetDAVResponses()) {
                    if(filesOnly && element.IsFolderResponse()) continue;
                    string href = element.GetResponseHref();
                    yield return href;
                }

            }

            #endregion
        }
    }

The above code should be usable as:
    // Files only
    foreach(string fileUrl in spList.RootFolder.ListRecursively()) {
        ...
    }

    // Files & Folders
    foreach(string pathUrl in spList.RootFolder.ListRecursively(false)) {
        ...
    }

If necessary, you can get the Microsoft.SharePoint.Client.File & Microsoft.SharePoint.Client.Folder objects from the URLs. (context.Web.GetFileByServerRelativeUrl I think. If not, you'll have to look it up)
Note: Haven't actually tested this. Threw it together from the source code in a few of my previous projects, so sorry for any unused/unnecessary code that was left in.

A: You may try to add an OrderBy clause to your CAML query, to order by ID. ID is a naturally indexed column in SP, so ordering by ID should help overcome the 5000 threshold. To be done maybe in conjonction with a RowLimit to avoid the timeout...
<OrderBy><FieldRef Name='ID' Ascending='TRUE' /></OrderBy>

That would make:
query.ViewXml = @"<View><Query><Where><BeginsWith><FieldRef Name='ContentTypeId' /><Value Type='ContentTypeId'>0x0120</Value></BeginsWith></Where><OrderBy><FieldRef Name='ID' Ascending='TRUE' /></OrderBy></Query><RowLimit>" + FileFoldeBatchSize + "</RowLimit></View>";

Update
As per this MSDN blog thread, we may need the Override='TRUE' attribute on the OrderByclause + Scope='Recursive' on the View. i.e.:
query.ViewXml = @"<View Scope='RecursiveAll'><Query><Where><BeginsWith><FieldRef Name='ContentTypeId' /><Value Type='ContentTypeId'>0x0120</Value></BeginsWith></Where><OrderBy Override='TRUE'><FieldRef Name='ID' Ascending='TRUE' /></OrderBy></Query><RowLimit>" + FileFoldeBatchSize + "</RowLimit></View>";


text:
Q: How to display another window after successful Login from the login window? I have two classes like below:
class Login(QMainWindow):
    ...
    ...

class WinOne(QMainWindow):
    ...
    ...

Login class has the Login window.
WinOne class has the post-login window.
I am importing these two classes into another module and I want to display the window from the WinOne class after successful login from the login window of the Login class.
I am not sure how to close the first window and open another window.
I am not able to apply this logic.
If someone can suggest just the logic, I'll try to implement.

A: You can have a blocking way to show the login dialog and access the results. It can be done by using exec() and seeing the results when it returns :
login = Login()
winOne = WinOne()

if login.exec():
    result = login.successfulLogin;
    if result:
       winOne.show()
    else:
       ...

Another option is to use the asynchronous way. You can have a signal in Login to show the login is successful and connect it to show() slot of WinOne :
QtCore.QObject.connect(login, QtCore.SIGNAL('LoggedIn()'), winOne, QtCore.SLOT('show()'))


text:
Q: allow create table for some users, not all I need to create 2 roles in postgres, a read only role that only has permission to run SELECT queries, and an admin role that has full superuser privileges.
How can I remove "CREATE TABLE" from 1 role, while allowing "CREATE TABLE" on another role?
I'm using "REVOKE CREATE ON SCHEMA public FROM PUBLIC" to revoke create permissions, but this applies to all roles, and I'd like to allow an admin role to still create tables.

A: PostgreSQL doesn't have a special CREATE TABLE privilege, everybody is always allowed to create tables. Creating tables is restricted by schema permissions: if you grant a role the CREATE privilege on a schema, that role can create tables (and other objects) in that schema.
So grant CREATE on a schema to the one role and don't grant CREATE on any schema to the other role.


text:
Q: Remove the highlight from combobox in readonly mode (python) I would like to remove the highlighting from my combobox widget when the user selects an option. But the method select_clear() doesn't seem to be working :(
Any clues why ?
from tkinter import *
from tkinter.ttk import Combobox

class hey(Frame):
    def __init__(self):
        Frame.__init__(self)

        self.comboboxVariable = StringVar()
        values = (1, 2, 3, 4, 5)

        self.comboBox = Combobox(self, textvariable = self.comboboxVariable, values = values, state = 'readonly')
        self.comboBox.pack()

        self.comboBox.bind("<<ComboboxSelected>>", self.updateData)

    def updateData(self, event =None):

        self.comboBox.select_clear()

myClass = hey()
myClass.pack()
root = myClass.master
root.mainloop()

A: What you are trying to do and what your script is attempting to do are two different things. First, you have event = None, which causes the function to be called when you first initialize an object and then never again. Instead, leave the function attribute just as 'event' so that it runs when the specified event takes place.
To remove the selection made, your updateData function would look like the following:
def updateData(self, event):

    self.comboBox.set("")

However, to remove the highlighting from the chosen value, you would need to change the focus from the combobox to the root window:
def updateData(self, event):

    self.focus_set()

Hope this helps.


text:
Q: Powershell - Incorrect Array Count when piping ForEach-Object I don't understand why I get the correct count of my array when using ForEach, but not when I pipe to ForEach-Object. The piped count is always 0.
Correct Count:
$hash = @(Get-ChildItem C:\Dir -Recurse -Include *.txt | Where {$_.length -gt 0})
ForEach ($i in @hash) {
     Write-Host = $i.BaseName
}
"Array Count = $($hash.Count)"

Output:
File1.txt
File2.txt
Array Count = 2

Incorrect Count:
$hash = @(Get-ChildItem C:\Dir -Recurse -Include *.txt | Where {$_.length -gt 0}) | ForEach-Object {
    Write-Host $_.BaseName
}
"Array Count = $($hash.Count)"

Output:
File1.txt
File2.txt
Array Count = 0

A: In your second formulation the ForEach-Object is eating up the values found by
Get-ChildItem and returning nothing useful to $hash.
You should enclose the entire assignment to $hash in the parenthesis to have it
evaluated before it is grabbed by ForEach-Object.
This is the formulation that worked for me in my test:
($hash=@(Get-ChildItem -Path "C:\Temp\*" -Include "*.jpg") | Where {$_.length -gt 0}) | ForEach-Object { Write-Host $_.BaseName }

A: $hash is null in the second example (type $hash -eq $null to verify). The output of the pipeline is "consumed" by the Write-host in your loop --- there's nothing left to assign to $hash. If you want the names assigned to $hasn and displayed on the console, something like this would work:
$hash = @(Get-ChildItem c:\dir -Recurse -Include *.txt | Where {$_.length -gt 0}) | ForEach-Object {
    $_.BaseName # continues through pipeline to populate $hash
    write-host $_.basename
}
"Array Count = $($hash.Count)"


text:
Q: Plesk failed to upgrade on centos 6 I am unable to upgrade existing Plesk 12.4 update 23 on centos 6.7.
The log shows that the upgrade script is trying to fetch data from a non-existing folder in opensuse repository. Have some faced this situation with plesk? i just simply dont understand why it is trying a folder related to older version of centos (5)?  how can i fix this. The log reads like this:
Loading mirror speeds from cached hostfile

* base: mirror.checkdomain.de
 * extras: mirror.checkdomain.de
 * rpmforge: mirror.de.leaseweb.net
 * updates: mirror.checkdomain.de
http://download.opensuse.org/repositories/server%3A/mail/CentOS_5/repodata/repomd.xml: [Errno 14] PYCURL ERROR 22 - "The requested URL returned error: 404 Not Found"
Trying other mirror.
Failed to install plesk-l10n:

A: It seems to be corrupted Yum cache. Can you please try "yum clear all" and see if it helps?
Source : http://kb.plesk.com/en/124973

A: It was an unused repo that was creating this issue. 'Server:mail.repo' referring to non-existing url was actually leftover from some previous package. I just removed it and Yum is doing all good.
To check what package is using a repo (server:mail.repo in my case) :

rpm -df /etc/yum.repos.d/server:mail.repo

It shown than no package was using it. I than simply removed it.
Hope it helps someone with similar situation. Regards


text:
Q: Stata can't open file saved in local cloud storage folder on Mac I am using Stata on a Mac. I updated the OS to Monterey today. If I try to open a .dta file---that is saved on my local computer in a folder that syncs to OneDrive---from code in the Do File Editor/Command prompt (where I refer to the file using its full file path), it doesn't open. The error is r(601) - File ... cannot be found.
But if I click on it in Finder, it opens in Stata just fine. After I have done this, I can then open this file in Stata by running the exact same Stata code that didn't work before. Somehow it seems like Stata can't see the file/folder initially, but then it can. I am not sure if this has to do with the OneDrive file/folder permissions or something else.
If, in Stata, I change the directory to the correct directory using cd and then load the file (without referring to the path), it works. However, I would like to be able to refer to the file using the entire file path and not have to change the directory each time.
Interestingly, if I change the directory to the correct directory using Change working directory in the File drop down and then try to load the file using the file path, it also works. But if I do not do the drop down and write out the cd using code, and try accessing the file using the path it doesn't work!
Somehow Stata has to initially "see"/"access" the correct folder (in a very particular way) before being able to access it with the file path. Very strange. (Just to be clear, if I do not change the directory to the correct directory and then try to load the file using its file path, it doesn't work.)
I also tried creating a file using texdoc init... (in a folder that already exists, but that has not been used by Stata before) and get this error:
could not create directory .....
                 mkdir():   693  could not create directory
          texdoc_mkdir():     -  function returned error
           texdoc_init():     -  function returned error
                 <istmt>:     -  function returned error

I do not get this error if I instead use another folder in the same directory that I have previously used.
I think that the error I am encountering is the same or similar to this one (with no acceptable answer): https://answers.microsoft.com/en-us/msoffice/forum/all/onedrive-folder-doesnt-exist/e6b97d47-3f6a-4863-bf68-d3a02832f2bb


text:
Q: Simple home router routing Having simple home modem/router i have no option to view and edit the routing table (the configuration is WEB-page type). Moreover there is an option "RIP support" which is disabled by default.

*

*Does it mean that the routing table is build statically (without interacting with other routers).

*If I'm right that the routing table is modified automatically when the network topology changes (for e.g. a new route added when connecting a new host to the router port)?

*Is there any way to view the table?

A: I imagine your routing table is going to be very simple and look like this:
Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
default         <gw address removed> 0.0.0.0         UG        0 0          0 eth0
<ip address removed>     *               255.255.252.0   U         0 0          0 eth0
192.168.10.0    *               255.255.255.0   U         0 0          0 br0

(excuse the formatting)
That is; a default route pointing to your ISP's gateway device, a route for your ISP's network out of one interface and a route for your local LAN out of the other one. There's not going to be any requirement to dynamically build a routing table because everything not destined for the LAN will be sent to your ISP's gateway. The routing table will be built based on the network interface configurations or DHCP.
It's impossible to say if you can view the routing table as you don't provide a make or model.

A: *

*Sort of, a default gateway is provided by DHCP from the ISP. That is injected as a static route in the routing table by the DHCP client process.

*For individual hosts, it will not add an additional entry to the routing table. Routes are for L3 subnets, not for L2 ARP entries.

*This is higly dependant on the router/firmware. Check the manual. Sometimes these things can be polled with SNMP, if you're lucky you could find a routing table at SNMP OID .1.3.6.1.2.1.4.21 (see RFC1213-MIB)

A: Depending on the connectivity provided by your ISP, your router receives certain IP configuration for its WAN port (ip address, netmask, gateway address, dns servers, the ip address is probably a public one).
What your router does is get the packets it receives from hosts connected to its Ethernet ports (or via WiFi) and sends them over to it's WAN Gateway (which is a default gateway, or gateway of last resort).
RIP is a distance vector routing protocol, which serves as communication protocol between two routers - to exchange information for the routes they know and they have in their routing tables (if they are configured in that way, of course). In order your home router to work with RIP, it needs to be configured to communicate with other RIP enabled routers - you just can't have it use RIP by itself.
To answer your questions:

*

*depending on the router you have you might be able to add static
routes by yourself. In most cases, a SOHO (small office/home office)
device will route and/or NAT traffic from Ethernet ports to WAN
ports.

*that depends on the settings and on the router model, but usually
when you connect a device to the router's Ethernet port, the DHCP
service running on the router sends an IP configuration to the newly
connected hosts - that's all that happens

*That again depends on the router model


text:
Q: Which panel is associated with a particular camera? MEL I know you can query which camera is associated with a particular panel. But, is there a way you can do it the other way around?
I want to be able to see what panel is associate with a particular camera.
Example:

getPanel -q mainCamera;
// modelPanel1

Thanks for the help yall

A: This script returns which panels are associated with a particular camera (in this case: persp).
Mel version:
proc string[] getPanelFromCamera(string $cameraName){
    string $listPanel[];
    for( $panelName in `getPanel -type modelPanel`){
        if( `modelPanel -query -camera $panelName` == $cameraName){
            $listPanel[size($listPanel)] = $panelName;
        }
    }
    return $listPanel;
}

print `getPanelFromCamera("persp")`;

Python version:
import maya.cmds as cmds

def getPanelFromCamera(cameraName):
    listPanel=[]
    for panelName in cmds.getPanel( type="modelPanel" ):
        if cmds.modelPanel( panelName,query=True, camera=True) == cameraName:
            listPanel.append( panelName )
    return listPanel

print getPanelFromCamera("persp")

Note:
I'm usually don't script in mel, so the mel version of this code is a litteral translation from the python version. I also thought that the Python version might be useful for future readers.

A: If you have the panel, and you want the camera associated with it, you can simply query it
import maya.cmds as cmds
cmds.modelPanel("modelPanel1", query=True, camera=True)


text:
Q: Showing uniqueness of solution to IVP under certain conditions Consider the IVP $\mathbf{\dot x} = f(\mathbf{x},t)$ where $\mathbf{x}(0) = 0$, $f$ is continuous in some neighborhood of $(x,t) = (0,0)$ and $|f(x,t)-f(y,t)| \leq \frac{|x-y|}{t^\alpha}$.  I would like to show the uniquenesss of the solution if $\alpha\in (0,1)$.
It seems like I would like to show that $f$ is locally Lipschitz in $x$ when $t = 0$ if $\alpha\in(0,1)$, (since it is clearly locally Lipschitz for all $t > 0$) but I haven't been able to tackle that by elementary methods (or any other, really).  Another idea might be to bound the sequence of Picard iterates, but that seems very messy.  A third idea would be to appeal to general facts about moduli of continuity.  The fact that a solution is unique when the integral $\int_0^x\frac{dx}{\omega(x)}$ diverges for the modulus $\omega$ seems almost useful, except that in this case my modulus is a function of both $x$ and $t$.  Am I in the right ballpark with these approaches, or is there something very obvious that I'm missing?
Also, this is homework, so I would be grateful for a small hint rather than a full solution.  Thanks in advance!


text:
Q: Adding the required jars to the Application under Eclipse This is a general query , but i am asking as you people are experienced and would have come across this type of  situation before .
I have imported an existing Application under Eclipse IDE , which is missing some jars , I need to add some jars to make it get compiled .
Now i have  some 100 jars within a folder . how can i find what jar to add for that missing class ??
Please suggest me any ideas for this , thank you very much .
Thank you very much .

A: If the project comes with a /lib folder containing some jars, add all of them. Right click the project > Build Path > Configure Build Path > "Libraries" tab -> Add jars
If this is your project, or you can do something about it, consider using a dependency management tool like Maven.


text:
Q: Is there a function that returns the zipcode Is there a function that returns the zipcode (or closest zipcode) for a given longitude and latitude.. It needs to scale because I have a long list of latitude by longitude

A: A.1) You can download tables that contain the approximate coordinates of Zip Codes. For small zip codes area, it can be precise, but for large area in less populated zones, the coordinates would just be the middle point.
Maybe look at some search results: http://zips.sourceforge.net/
A.2) Then you can join your list of zip codes to get the coordinates.
B) You can try to use geocode from ggmap package
Further readings: https://gis.stackexchange.com/questions/28035/how-to-convert-zip-codes-to-latitude-and-longitude

A: Actually I was looking for a subroutine in R. I tried zipcode package but it didn't work too well..
I basically have a long list in longitudes and latitudes and need corresponding (or nearest) zip codes


text:
Q: Centering buttons and text in a GridPane (JavaFX) I have a simple display that has a title at the very top, a list in the middle, and then three buttons at the bottom. I want the title at the top and the buttons at the bottom to be horizontally centered.
Here is the code that I've been trying to use:
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.ListView?>
<?import javafx.scene.layout.GridPane?>

<GridPane
    xmlns="http://javafx.com/javafx/8.0.40"
    xmlns:fx="http://javafx.com/fxml/1"
    fx:controller="controllers.SongLibraryController"
>
    <Label
        text="Todo List"
        GridPane.columnSpan="3"
        GridPane.rowIndex="0"
        GridPane.halignment="CENTER"
    />
    <ListView
        prefWidth="300"
        prefHeight="400"
        fx:id="listView"
        GridPane.columnSpan="3"
        GridPane.rowIndex="1"
    />
    <Button
        fx:id="editItem"
        GridPane.halignment="CENTER"
        GridPane.columnIndex="0"
        GridPane.rowIndex="2"
        text="Edit Item"
    />
    <Button
        fx:id="addItem"
        GridPane.halignment="CENTER"
        GridPane.columnIndex="1"
        GridPane.rowIndex="2"
        text="Add Item"
    />
    <Button
        fx:id="deleteItem"
        GridPane.halignment="CENTER"
        GridPane.columnIndex="2"
        GridPane.rowIndex="2"
        text="Delete Item"
    />
</GridPane>

And here is the current output:

I've tried doing various things like using alignment="CENTER" for my GridPane, but nothing seems to be working. Any help would be appreciated!

A: You need to set alignment for your GridPane as alignment="center" and all elements will be aligned in center.
Update
You can align your buttons in center like this.
<HBox GridPane.rowIndex="2" GridPane.columnSpan="3" alignment="CENTER" spacing="25">
    <Button text="b1"/>
    <Button text="b2"/>
    <Button text="b3"/>
</HBox>

After this update you also can delete columnSpan attribute from each node.

A: To align elements inside a grid pane programatically, you will have to call static methods from the GridPane class.
To set horizontal alignment, call GridPane.setHalignment(Node n, HPos p). To set vertical alignment, call GridPane.setValignment(Node n, VPos p).
You can read Oracle's own layout guide here. If you scroll down until you see the pie chart, they show an example of how to manage layouts in grid panes.
To manage it via FXML, you will have to set a certain property. I can't remember of the top of my head, but I think it is alignment="center" in your GridPane node.


text:
Q: s3: How to recursively count files and group them by extensions - on command line in terminal I can recursively count files in an s3 bucket like so:
aws s3 ls 's3://s3bucket_name/folder_name/' --recursive --summarize | grep "Total Objects: "

I want to now do it

*

*by extension ('.jpg') - (you guys helped me there)

*for all the extensions at once. I tried adding '--include "*." to the above but it apparently is only for copy and it failed.  I can't find anything that will do it at the command line. Any suggestions? Thanks!


text:
Q: Where will String::from("") be allocated in a match arm? I am still very new to rust, coming from a C embedded world.
If i have a piece of code like this:
    match self {
        Command::AT => String::from("AT"),
        Command::GetManufacturerId => String::from("AT+CGMI"),
        Command::GetModelId => String::from("AT+CGMM"),
        Command::GetFWVersion => String::from("AT+CGMR"),
        Command::GetSerialNum => String::from("AT+CGSN"),
        Command::GetId => String::from("ATI9"),
        Command::SetGreetingText { ref enable, ref text } => {
          if *enable {
            if text.len() > 49 {
              // TODO: Error!
            }
            write!(buffer, "AT+CSGT={},{}", *enable as u8, text).unwrap();
          } else {
            write!(buffer, "AT+CSGT={}", *enable as u8).unwrap();
          }
          buffer
        },
        Command::GetGreetingText => String::from("AT+CSGT?"),
        Command::Store => String::from("AT&W0"),
        Command::ResetDefault => String::from("ATZ0"),
        Command::ResetFactory => String::from("AT+UFACTORY"),
        Command::SetDTR { ref value } => {
          write!(buffer, "AT&D{}", *value as u8).unwrap();
          buffer
        },
        Command::SetDSR { ref value } => {
          write!(buffer, "AT&S{}", *value as u8).unwrap();
          buffer
        },
        Command::SetEcho { ref enable } => {
          write!(buffer, "ATE{}", *enable as u8).unwrap();
          buffer
        },
        Command::GetEcho => String::from("ATE?"),
        Command::SetEscape { ref esc_char } => {
          write!(buffer, "ATS2={}", esc_char).unwrap();
          buffer
        },
        Command::GetEscape => String::from("ATS2?"),
        Command::SetTermination { ref line_term } => {
          write!(buffer, "ATS3={}", line_term).unwrap();
          buffer
        }
    }

How does it work in Rust? Will all these match arms evaluate immediately, or will only the one matching create a mutable copy on the stack? And also, will all the string literals withing my String::from("") be allocated in .rodata?
Is there a better way of doing what i am trying to do here? Essentially i want to return a string literal, with replaced parameters (the write! macro bits)?
Best regards

A: Only the matching arm will be evaluated. The non matching arms have no cost apart the size of the program.
In the general case, it's not even possible to evaluate other arms, as they depend on data read using destructuring of the pattern.
As for your second question, the location in a program where literals are stored isn't commonly named rodata, and it's neither specified nor guaranteed (it's usually deduplicated but that's just optimization).


text:
Q: Routes messed after implementing Angular Internationalization (i18n) After a lot of research, I finally decided to use Angular Internationalization (i18n).
Current routes (as you can see they are independent of the language):
const routes: Routes = [
  {
    path: '',
    canActivate: [AuthGuardService],
    loadChildren: () => import('./commercial-layout/commercial-layout.module').then(m => m.CommercialLayoutModule)
  },
  {path: 'maintenance', component: MaintenanceComponent},
  {
    path: 'auth',
    loadChildren: () => import('./auth/auth.module').then(m => m.AuthModule)
  },
  {path: '**', redirectTo: 'water', pathMatch: 'full'}
];

I have support for 2 languages right now, en and fr.
NOTE: My website was already in production and I am adding i18n now.
However, I am facing the following problem and could not find any resource to fix it:
If I manually enter "en" or "fr" after my url ends (www.myUrl.com/en OR www.myUrl.com/fr), it works fine.
However if I try to go to the default url without language (www.myUrl.com), the website crashes/does not load.
Also all the routes inside my LAZY LOADED application are not working properly as well.
Error on going to my main route: 403 Forbidden
Do I need to rewrite all my routes for the support for i18n or is there a better way?
Thanks!


text:
Q: Rack session key too long for memcached I am running Rails 3 configured to use memcached for session store. I have the following setup:
development.rb
config.cache_store = :mem_cache_store
session_store.rb
Foo::Application.config.session_store :mem_cache_store, :key => '_foo_session'
I can start the app fine, when I go to any page I get the following error:
ArgumentError (key too long "rack:session:__really_long_session_key__"):
I realize the limit on memcached key is 255. How can I get around this, or am I doing something wrong?

A: You're almost certainly seeing this because you're switching from the cookie store to memcached. Your browser still has the old session cookie, with the long ID. You need to delete this cookie from your browser and the problem will go away.
If you're switching from cookie store to memcached on a production site, this will be a problem because you don't have control over your user's browsers. You'll probably need to change the session key to avoid problems in this case.

A: Is it possible you switched from the cookie store or you run other cookie session store apps on the same domain (e.g. localhost)?
In this case the cookie session store is responsible for the huge session_id string (because it actually stores the whole session in it). Just delete your session cookie and you are fine.

A: If your "key" is more than 255 characters, it sounds like you are doing something wrong. Why is your session key that long? What's wrong with MD5 or SHA1?


text:
Q: if my pc have multiple ip how can i use 2 different ip for 2 windows of program? It is purpose for gaming
this game don't allow to run 2 window on 1 IP
so I think for using 1 IP from  LAN  and another on PCIe card(LTE sim slot)
when I open the game will auto-use main IP right?
how can I set second IP for being used by second window of the game
sorry for my english. it is bad i know

A: Perhaps like this:

*

*Start one instance of the game with your IP

*Start a VPN session

*Start the second instance of the game that will use another IP from the VPN.

The success of this method depends on how this game works.


text:
Q: Convergence in Probability of a sum What are the minimum details that i need to know in order to find the limit in probability of a specific random variable (such as the sum of several random variables)?
For example, suppose i have a sequence of random variables: $X_{1}, X_{2},...,X_{n}$ and i know that: $E(X_{i}) = \mu$ and $Var(X_{i}) = \sigma$ but i dont know which particular distribution has every $X_{i}$.
I can argue that from the Weak Law of Large Numbers, $\bar{X} = \frac {\sum X_{n}}{n}$ converges in probability to $\mu$.
But my question is, can i say anything about the convergence in probability of $\sum X_{n}$???
What else do i need to state something about the convergence of $\sum X_{n}$ ?
Thank's!

A: First, I'll re-cast the variance to standard notation: $Var(X_i) = \sigma^2$.
If $\sigma^2>0$ and the $X_i$ are independent, then we can show that $\sum X_i$ diverges almost surely...
$$\sigma > 0 \implies \exists \epsilon>0: P(|X_i|\geq\epsilon)>0\;\;\forall i\; $$
We know this because each variable is forced to have the same variance. Therefore, the smallest allowable $\epsilon$ is fixed above zero. We can find this value by assuming $X_i$ follows a shifted and scaled Bernoulli(0.5) r.v.:
$$X_i = s\times(Y_i-0.5),\;\;Y_i\sim Ber(0.5) :$$
Here,
$$Var(X_i) = \left(\frac{s}{2}\right)^2 = \sigma^2 \implies s=2\sigma \implies \min \epsilon = \sigma$$
Now, $E_k := |X_k|\geq\epsilon$, then
$$\lim_{k\to\infty}\sum P(E_k) = \infty$$
If we assume the $E_i$ are independent, then we can then use the partial converse Borel-Cantelli Lemma, to conclude that $E_i$ happens infinitely often, hence the sum will not converge (the sum will just keep moving around, since the $X_i \not \rightarrow 0\;$)
An alternative approach, which just establishes divergence in probability if $X_i$ are independent is as follows:
$$S_k = \sum_1^k X_i \implies Var(S_k) = k\sigma^2 \implies P(|S_k|\geq \sqrt{k}\sigma) > 0$$


text:
Q: How to detect touchend event outside of an element I'm trying to handle a button click. The "button" is a custom div that can also contain children. The click callback should fire when the user has both clicked and released inside the element. If the user clicks inside and then drags and releases outside, the handler should not fire. I need to get this working on both desktop and mobile, hence I'm using mousedown/mouseup and touchstart/touchend events.
I need to change the button class from "pressed" to "normal" even if the user releases outside, so I need to add a listener to capture the releasing event over the document:
    var $myElement = $("#myelement"); //This is a div and can also contain children.

    $myElement.on("mousedown touchstart", function(e){

        $(this).addClass("pressed");

        $(document).on("mouseup touchend", function listener(e){
            $myElement.removeClass("pressed");

            $(document).off("mouseup touchend", listener);

            var $target = $(e.target);
            if ($target.is($myElement) || $target.parents().is($myElement)){
                //FIXME
                alert("Inside!");

                //do something here
                return false;
            } else {
                //FIXME
                alert("Outside!");

                //let event bubble
            }
        });

        return false;
    });

It works fine with clicks, but it does not work as expected with touch events. I've tested this in Chrome for Android and when pressing over the element, then dragging out, the "Inside!" alert is shown.
The problem is in this condition:
if ($target.is($myElement) || $target.parents().is($myElement)){

I'm trying to check whether the touchend event has occurred in the button or any of the the children. If the button has no children, when clicking on it and then releasing outside, the first part of the OR clause resolves to true. If the button has children and I click in the children, then release in any other part of the screen, the second part of the clause is true.
What is wrong with this code?
Thanks in Advance.
UPDATE
I've tested it also in BlackBerry 10 with the same results. Apparently the target for the touchend event is the button (or the children), even when I've clicked outside. Is this how it is supposed to work?
UPDATE
And here's why. This is what the W3C docs say about the event:

The target of this event must be the same Element that received the touchstart event when this touch point was placed on the surface, even if the touch point has since moved outside the interactive area of the target element.

It makes no sense to me, but anyway this explain my problem. I was assuming the touchend event would be called over the element where the finger was released. Would it be possible to detect the finger release outside using a different approach?
UPDATE
I've tried to get the coordinates of the touchevent to get the element there using document.elementFromPoint. The problem is this event does not contain the coordinates (the changedTouches and touches lists are empty). I've thorougly inspected the event in the debugger and there's no way to retrieve coords from it other than the original event's. Then I thought I could cache the last touchmove event and get the coords from there, but again this event has no own coordinates! Why on Earth do these two events exist when they are useless? And I've tested this approach in iOS, Android and BB10 with identical results.
I've given up.  I'll call the callback even if the user clicked outside. I can't believe it is 2013 guys and there's no (simple) way of doing this? I could use the drag&drop api but according to this it is unsupported on mobile (Gotta love mobile web development).

A: Finally (almost) got it working in BB10 and Android. I've left a trail of problems in the question updates, so to sum up: the touchend event target is the same as the touchstart, and it comes without coordinates (the API designer for some reason decided to "hide" them in the originalEvent property :) . So I'm retrieving the touch end coordinates from changedTouches[0].pageX and changedTouches[0].pageY and then obtaining the element where the finger is released using document.elementFromPoint. (Before feeding this method with the event coordinates you must add the scroll offset to x and y). Then if the element at that point is the button (or is a child of it), I handle the click.
    var $myElement = $("#myelement"); //This is a div and can also contain children.
    var startEvent = touchDevice() ?  "touchstart" : "mousedown";
    var releaseEvent = touchDevice() ?  "touchend" : "mouseup";

    $myElement.on(startEvent, function(e){

        $(this).addClass("pressed");

        $(document).on(releaseEvent, function listener(e){
            $myElement.removeClass("pressed");

            $(document).off(releaseEvent, listener);

            var $target = null;
            if(e.type === "mouseup"){
                 $target = $(e.target);
            } else {
                var x = e.originalEvent.changedTouches[0].pageX - window.pageXOffset;
                var y = e.originalEvent.changedTouches[0].pageY - window.pageYOffset;
                var target = document.elementFromPoint(x, y);

                if(target){
                    $target = $(target);
                }
            }

            if ($target !== null && ($target.is($myElement) || $target.parents().is($myElement))){
                //FIXME
                alert("Inside!");

                //callback here
                return false;
            } else {
                //FIXME
                alert("Outside!");
            }
        });

        return false;
    });

Now I've a new problem: in iOS somehow the click events are being duplicated. But this deserves a different question (if not existing already).

A: You need a different and neater approach all together.
Implement the onmousemove and ontouchmove for desktop and mobile devices respectively.
btn_obj.onmousemove = CancelOnClick (this);

Implement the CancelOnClick function to set the flag from pressed to normal. It saves you from all your element and its children based conditions.
Hope that helps.


text:
Q: Check if Mobile (.m) website exists Query Issue I'm having trouble checking if a url exists.
I use the below for most checks - its the best method I have found and saves on a full web request but it does;nt allow for checks on address such as:
m.bbc.co.uk
Any mobile site for m., has no effect and breaks.
public static bool Does_URL_Exists(string str_url)
    {
        // using MyClient from linked post
        using (var client = new MyClient())
        {
            client.HeadOnly = true;
            // fine, no content downloaded
            try
            {
                //System.Windows.Forms.MessageBox.Show(str_url);
                string s1 = client.DownloadString(str_url);
                return true;
            }
            catch
            {
                return false;
            }

        }

    }
class MyClient : WebClient
{
    public bool HeadOnly { get; set; }
    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest req = base.GetWebRequest(address);
        if (HeadOnly && req.Method == "GET")
        {
            req.Method = "HEAD";
        }
        return req;
    }
}

Any clues on how I cam make this work. www.bbc.co.uk/m is no good either.

A: you don't need load all string of link to client, only check status when connect to url is OK (200).
with url as: "http://www.bbc.co.uk/". i think mobile like of direct link is: "http://www.m.bbc.co.uk/"
Hope help to you


text:
Q: Magento - cart.phtml - Override issue I have seen several examples of how to override the cart.phtml, but none of them seem to work in my files.
I have a theme at:

*

*app/design/frontend/default/ves_fashion/

The file is located in:

*

*app/design/frontend/default/ves_fashion/template/checkout/cart.phtml

I have created a cart.phtml in:

*

*app/design/frontend/default/ves_fashion/template/customsite/checkout/cart.phtml

I have then checked the layout.xml of the theme in:

*

*app/design/frontend/default/ves_fashion/layout/checkout.xml

And see this:
<layout>
    <checkout_cart_index translate="label">
        <label>Shopping Cart</label>
        <remove name="right"/>
        <remove name="left"/>
        <!-- Mage_Checkout -->
        <reference name="root">
            <action method="setTemplate"><template>page/1column.phtml</template></action>
        </reference>
        <reference name="content">
            <block type="checkout/cart" name="checkout.cart">
                <action method="setCartTemplate"><value>checkout/cart.phtml</value></action>
                <action method="setEmptyTemplate"><value>checkout/cart/noItems.phtml</value></action>
...

I know wanted to override this cart.phtml with my own one and did the following:
I opened the local.xml in

app/etc/local.xml

and inserted:
 <layout>
        <checkout_cart_index translate="label">
            <reference name="content">
                <block type="checkout/cart" name="checkout.cart">
                    <action method="setCartTemplate"><value>customsite/checkout/cart.phtml</value></action>
                    <action method="setEmptyTemplate"><value>customsite/checkout/cart/noItems.phtml</value></action>
                </block>
            </reference>
        </checkout_cart_index>
    </layout>

But this is not working. What do I need to do now? Is the local.xml in app/etc/ the correct one or do I have to use the one in app/design/frontend/default/ves_fashion/layout/local.xml ? I have also seen examples where the  Tag has been left out, the value Tag is named  and the content is set to checkout.cart - Why should I do this if the original xml file says something different?
Would be great if someone can help me out here. Thanks!

A: The app/etc/local.xml file is not what you're after. That contains the environment information for your site.
You can feel free to make changes directly in the theme's layout file:
app/design/frontend/default/ves_fashion/layout/checkout.xml
Or you can add a local.xml in that folder if you prefer, and make layout updates there.

A: As the others have pointed out, adding layout handles to the app/etc/local.xml file is wrong. That is simply for configuration. Your theme should define its own local.xml file in app/design/frontend/{your-package-name}/{your-theme-variation-name}/layout/local.xml, or your module should define its own layout handles in app/design/frontend/base/default/layout/{your-namespace}_{your-module}.xml.
Having written that, however, there is an inherent problem with the layout XML provided in your question. As is, those layout definitions will not work. Calling setCartTemplate and setEmptyTemplate are correct, but they will not work without the essential method call that MUST be called directly after them: chooseTemplate. If you view the app/design/frontend/base/default/layout/checkout.xml file, that method can be seen directly after the first two. This method call alone has been the source of many people's frustrations when modifying the Magento cart templates, made obvious by the number of StackOverflow questions regarding the issue. I've written a thorough explanation of this problem here: https://stackoverflow.com/a/33875491/2973534.


text:
Q: Getting db2 error: ibm_db_dbi::ProgrammingError: The last call to execute did not produce any result set We installed Superset in our development environment and trying to display data in reports format. Reports will be generated form DB2 Database. I am able to access reports properly and i can execute select statements without any issues.
Along with reports, we need to create few tables also. So we created a user with necessary permissions. When I tried to create a table from Superset I am getting the following error message. Same query is working fine from DBeaver (where I connected to the same database with same user name).
Any suggestions/ideas on what I can try?
db2 error:

ibm_db_dbi::ProgrammingError: The last call to execute did not produce
any result set.

Query: MSACCESS is the schema where I am creating MMR1 Table
CREATE TABLE MSACCESS.MMR1(
zip_code VARCHAR(6)
);

Below statement should create a table . Userid has necessary permissions
CREATE TABLE MSACCESS.MMR1(
zip_code VARCHAR(6)
);


text:
Q: Insert new row with specific values In 1 table I need to insert specific rows with specific values, according to other tables values.
UPDATE item_properties2 AS P
INNER JOIN items ON items.id = P.item
INNER JOIN item_groups ON item_groups.idp = items.group_id
SET P.nr = '0'
WHERE P.type = 1140614900 AND items_groups.idp = '1140503406';

This updates the table. But what I need is basically.
(id, type, item, value, shows, nr)  VALUES
(78173, 1336983282, 1352706945, 'test Laisvai pastatomas Sharp', 0, 1)
item_properties2.Id -  just row id,
item_properties2.type - connect to item_property_groups2.id ,
'item_properties2.item' this connects to item.id ,
item.id have another column which is item.group_id ,
item.group_id is connected to item_groups.id which have another column naked  item_groups.idp .
I need to only select items_groups.idp = '1140503406' . And basically i it should add rows in item_properties2 with with specific type value which i entered and only to models with specific item_properties2. item accord to item_groups.idp . I don't know how to do it.

A: there are some ways to insert a bulk of data from 2 tables into a newer table.
this can be done like this:
INSERT INTO item_properties2 (id, type, item, value, shows, nr)
SELECT Yid, Ytype,Yitem,Yvalue, Yshows, Ynr
FROM items
INNER JOIN item_groups ON item_groups.idp = items.group_id
WHERE  items_groups.idp = '1140503406'

Instead of using the VALUES tag, you will now call for a specific select statement. you only need to change the Y values above into your own column names.
Or you could place your input into a stored procedure
the above query will run over your 2 tables and will insert the values that go with the where statement into the 3th table.
    CREATE PROCEDURE sInput
    ( @val1 int, @val2 int, @val3 varchar(10))
    AS
    INSERT INTO MyTable(val1, val2, val3)
    VALUES(@val1, @val2, @val3)
    return


text:
Q: awk ignore delimiter inside single quote within a parenthesis I have a set of data inside the csv as below:
 Given Data:
 (12,'hello','this girl,is lovely(adorable \r\n actually)',goodbye),
 (13,'hello','this fruit,is super tasty (sweet actually)',goodbye)

I want to print the given data into 2 rows starting from ( till ) and ignore delimiter , and () inside the ' ' field.
How can I do this using awk or sed in linux?
Expected result as below:
 Expected Result:
 row 1 = 12,'hello','this girl,is lovely(adorable actually)',goodbye
 row 2 = 13,'hello','this fruit,is super tasty (sweet actually)',goodbye

UPDATE:
I just noticed that there are a comma between the 2 rows. So how can i separate it into 2 rows using the , after ) and before (?

A: You can use the following awk command to achieve your goal:
awk -i.bak '{str=substr($0,2,length($0)-2); gsub("\\\\r ?|\\\\n ?","",str); print "row "NR" = "str;}' file.in

tested on your input:

explanations:

*

*-i.bak will take a backup of your file and

*{str=substr($0,2,length($0)-2); gsub("\\\\r ?|\\\\n ?","",str); print "row "NR" = "str;} will first remove the first and last parenthesis of your string before removing the \r,\n and printing it in the format you want

*you might need to add before the {...} the following condition if you have a header NR>1 -> 'NR>1{str=substr($0,2,length($0)-2); gsub("\\\\r ?|\\\\n ?","",str); print "row "NR" = "str;}'
following the changes in your requirements, I have adapted the awk command to be able to take into account your , as a record separator (row separator)
awk -i.bak 'BEGIN{RS=",\n|\n"}{str=substr($0,2,length($0)-2); gsub("\\\\r ?|\\\\n ?","",str); print "row "NR" = "str;}' file.in

where BEGIN{RS=",\n|\n"} defines your row separator constraint


text:
Q: How does the difference quotient with a square root in the numerator end up with square roots in the denominator? I don't understand when
I apply the difference quotient to: $f(x) = \sqrt{x} $   , to get:
$$\frac{\sqrt{x+h} - \sqrt{x}}{h}$$
To simplify it.. How does it end up like this?:
$$\frac{x + h - x}{h \sqrt{x+h} + \sqrt{x}}= \frac{1}{\ 2\sqrt{x}}$$
How do the sqrt's work when moving them from the numerator to the denominator?
Thanks.

A: $\frac{\sqrt{x+h}-\sqrt{x}}{h}=\frac{(x+h)-x}{h(\sqrt{x+h}+\sqrt{x})}=\frac{1}{\sqrt{x+h}+\sqrt{x}}$
So by letting h go to 0 we get
$\lim_{h\to 0}\frac{\sqrt{x+h}-\sqrt{x}}{h}=\frac{1}{2\sqrt{x}}$

A: You don't necessarily want the square root in the denominator, you want h out of it because it'll be set to 0 to find the limit. Since you can't divide by 0 you must factor h out of the denominator.

A: actually when you want to get $ \frac{\sqrt {x+h}-\sqrt x)} h$ you don't use the limit
it goes like this:

*

*multiply the nominator and denominator by $\sqrt{x+h}+\sqrt x$

which at the end will result in $\frac 1 {\sqrt {x+h} + \sqrt x}$

*

*$h$ shouldn't be treated as approaching zero unless you were told it is OR you're finding the derivative by definition.

Let me know if it helped ya :)


text:
Q: Current url into cookie file Short question is : "How do I save current url into cookie file?"
And the whole problem is as follows. I have to save current filters that client have applied to my grid in his cookie, that next time he logs in the data looks just as he wants it to look like. The service doesn't have any "login" stuff, just provides available data to the user. This whole thing is written in ASP.MVC/C#.
If you have any other solutions to this task I will be happy to discuss them!
Thanks for giving a minute.

A: http://msdn.microsoft.com/en-us/library/ms178194.aspx
In short, you can access the user's cookie data by calling Response.Cookies to get a dictionary of HttpCookie objects keyed by the name you give each cookie (much like Session or ViewState data stores). You can add to this by specifying a cookie name in the indexer as if it were there and setting Value and ExpirationDate properties, or by creating a new HttpCookie and calling Cookies.Add.
It may not be necessary to store the whole URL, although a cookie can contain up to 4k of data. I would instead store the query string (which has the pertinent filter settings) under a unique name that that specific page will know to get its cookie data from ("<page name here>FilterSettings", perhaps). Then, on PreInit, get the Request, and if its QueryString is empty but there's a Cookie with saved filter settings, tack the saved query string onto the current url and redirect.
Remember that the client has control over whether to save cookie data; the browser may accept all, accept from trusted sources, ask on all, or refuse all. In this case, no big deal; it's pure convenience, which is exactly what a cookie should be used for. If this were valuable data, you may have had to persist it server-side based on the user.


text:
Q: Where can I get Angular ui-grid selected items Testing out Angular ui-grid (ng-grid v.3.0). Can not for the life of me find the selected row. I just want to grab the rows or even row ID of row when a user clicks it. Found the top comment here but I think this is outdated:  Getting select rows from ng-grid?
Does anyone know where the gridOptions.selectedItems is being stored in 3.0?

A: Is this what your are looking for ?
http://ui-grid.info/docs/#/tutorial/210_selection

*

*Activate grid selection capabilities with the ui-grid-selection tag (and ui.grid.selection module registration in your app

*register gridApi and use gridApi.selection to access getSelectedRows()

A: In addition to the steps above https://stackoverflow.com/a/26188783/2658127, you might have to invoke it through a ng-click event to get the actual value/object. At least that's how I had it working.
Eg:
$scope.selectRow = function(){
    $scope.gridApi.selection.getSelectedRows();
};

And call selectRow() from the template.
This is for anybody who have been confused like I did, considering the fact that ui-grid does not have the best documentation (specially for this select portion).

A: The easiest approach is:

*

*Register the gridApi by adding this your controller:
$scope.gridOptions.onRegisterApi = function(gridApi) {
   $scope.myGridApi = gridApi;
   };

*Access the array of selected items:
$scope.myGridApi.selection.getSelectedRows();

A: With grid ui you have to use the selection.on.rowSelectionChanged to update a scope variable that store the selectedItem.
In this way you can use the value in a binding expression.
var SelectController = function($scope) {
    ...
    $scope.selectedItem = null;

    $scope.gridOptions = {
            data : 'articles',
            enableRowSelection : true,
            multiSelect : false,
            enableRowHeaderSelection : false,
            ...
        };

        $scope.gridOptions.onRegisterApi = function(gridApi) {
            // set gridApi on scope
            this.$scope.gridApi = gridApi;
        }.bind(this);
        $scope.gridOptions.onRegisterApi = function(gridApi) {
            // set gridApi on scope
            this.$scope.gridApi = gridApi;
            this.$scope.gridApi.selection.on.rowSelectionChanged($scope,
                    function(row) {
                        this.$scope.selectedItem = row.entity;
                    }.bind(this));
        }.bind(this);

Use a an array instead of a plain object if you need multiple selection.


text:
Q: Issue install cordova camera plugin with cordova 4.x I am maintaining a legacy hybrid mobile application using cordova 4.3.0. I have problem installing the cordova camera plugin. I follow install doc but it was failed with these errors:

cordova plugin add org.apache.cordova.camera

Fetching plugin "org.apache.cordova.camera" via plugin registry
npm http GET http://registry.cordova.io/org.apache.cordova.camera
npm http GET http://registry.cordova.io/org.apache.cordova.camera
npm http GET http://registry.cordova.io/org.apache.cordova.camera
Error: connect ETIMEDOUT 50.17.177.14:80
    at Object.exports._errnoException (util.js:849:11)
    at exports._exceptionWithHostPort (util.js:872:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1060:14)

I guess this http://registry.cordova.io/org.apache.cordova.camera no longer exists.
I notice this statement:

Older versions of cordova can still install via the deprecated id

I don't really understand what does this mean.
Is there anyone having experience with this issue and know how to solve it.