text:
Q: React - Render component based on a generated random hash I'm trying to render a component based on an hash that is generated on a click event.
Simple case : I'm on my localhost:3000 and i got a button that generate a room on my backend with a random hash and for front, i'd like to render my lobby component with the url being localhost:3000/#randomhash. So far I generate the url with window.location.hash but I've no idea how to make him render the lobby with my route
app.js
function App() {
  return (
    <>
      <Routes>
           <Route exact path='/' element={<Menu />}></Route>
          <Route path='/:roomId' element={<Lobby />}></Route>
      </Routes>
    </>
  );
}

export default App;

menu.js
const socket = socketIO.connect('http://localhost:4000');

const Menu = () => {
    useEffect(() => {
        socket.on('lobbyJoined', (...args) => {
            const data = JSON.parse(args[0]);
            //data.id is my generated hash (#fs42f for example)
            window.location.hash = data.id;
        });

        return () => {
            socket.off('lobbyJoined');
        };
    }, []);

    return(
        <>
            <div className='Menu'>
               //button to join a lobby triggering my socket event
            </div>
        </>
    );
}

export default Menu;

and my index.js
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>
);

details:
  "dependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.4.2",
    "react-scripts": "5.0.1",
    "socket.io-client": "^4.5.2",
  },


text:
Q: Require a parent attribute when a child is created I have a model Contact with an attribute name (along with others). When contact records are created they are mostly created with the name attribute left as null. This needs to be permitted.
My Contact class has an association to WaitListMembers
class Contact < ApplicationRecord
  has_many :waitlist_members
  # ...
end

class WaitlistMember < ApplicationRecord
  belongs_to :contact
  # ...
end

When a WaitlistMember is created I now need to impose a validation on Contact that the name not be blank.
How do I accomplish this?

A: You can use Module#delegate to delegate the method call to contact:
class WaitlistMember < ApplicationRecord
  belongs_to :contact
  delegate :name, to: :contact, prefix: true
  validates :contact_name, presence: true
end

A: I would add a validates associated on the contact, then on the contact itself use a lambda or if with a method to apply the validation conditionally on waitlist_members.any?
Class Contact
  #...
  validates :name, presence: true, if: ->(contact) { contact.waitlist_members.any? }
end

Class WaitlistMember
  #...
  validates_associated :contact
  #...
end

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does list iterator point in between the elements returned by next() and previous() methods I was going through JavaDocs and I found out that ListIterator in Java works slightly in a different manner from what we expect.

I thought that after we have used next() or previous() methods the cursor points to the corresponding element (i.e. current element).
But the documentation states that it points in between the elements that will be returned when we use next() or previous():

A ListIterator has no current element; its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next().

Also I have read somewhere that Java does this to prevent loops in the linked lists. But I am not able to get a grasp of this.


text:
Q: Adobe Media Server DVR only 5 second recording I have a strange problem. I have an application built in Flash Builder.
When I record to Flash Media Server I don't have any issues, it'll do DVR for as long as I want. But when I record to Adobe Media Server, the recording is only 5 seconds long.
ns = new NetStream(nc);
    ns.client = new Object();
    userUID = UIDUtil.createUID();
    ns.attachAudio (mic);
    ns.attachCamera (camera);
    ns.publish( "demo" + userUID, "record" );

Later I can play the recording, timestamp says that it's a 5 second archive, but it'll really keep playing the recorded video.
Same code, just different server.
Has anyone had this problem when migrating to Adobe Media Server from Flash Media Server?


text:
Q: InertiaJS loses remember when I'm back on the page I'm using Inertia JS in Vue with the Options API.
I have a single property that needs remembering, so when I set it in a method I'm going:
Inertia.remember(booth, 'active')

Then on a created or mounted hook I'm restoring it like this:
this.active = Inertia.restore('active') ?? 4;

This works ONCE when refreshing the page. On second refresh it loses the remember and goes to the default 4. I guess I have to remember it in the mounted hook as well?
However, when I navigate to a different page (that has nothing to do with this component) and then use an Inertia link to go back to the first page the state is always lost and restore() returns undefined.
What am I missing?

A: You can try to do like this, should work
beforeUnmount() {
 Inertia.remember(booth, 'active')

},
mounted() {
 this.active = Inertia.restore('active') ?? 4;

 },


text:
Q: Searching for an element in a 3d array Hello I was just wondering if anyone would know how the best way to search a three dimensional array for a specific name?
Thank you very much
var players=[["Patrick mahomes","QB",99],["Arron donald","DT",98],["Tyreek hill","Wr",98],["Lamar jackson","Qb",94]]
const value = players.includes("Patrick mahomes")
console.log(value)

A: It is a 2d array and you can use find and includes, to get the array which contain the searched value. Alternatively you can also use some and includes if you just want to know if the searched text is available in any of the nested array

var players = [
  ["Patrick mahomes", "QB", 99],
  ["Arron donald", "DT", 98],
  ["Tyreek hill", "Wr", 98],
  ["Lamar jackson", "Qb", 94]
]
const value = players.find(item => item.includes('Patrick mahomes'));
console.log(value);
const isAvail = players.some(item => item.includes('Patrick mahomes'));
console.log(isAvail)


text:
Q: bluemix node-red flow editor "deploy" button is not enabled I am following the tutorial: "Build a real-time chat app with Node-RED in 5 minutes" http://www.ibm.com/developerworks/cloud/library/cl-rtchat-app/
But the Deploy button is not enabled. So I can not deploy.
I have installed CF command line and run "push" for my app. This is what I learned in the "Start Coding" in the dashboard, under the "CFApp". It was successful.
Is this "push" the same as the "deploy" in the Node-Red editor?
Thanks.
Zheng

A: That tutorial has a slightly misleading screenshot of the editor, with a blank workspace and an enabled deploy button. The deploy button only becomes active when there are changes in the workspace that have not been deployed to the runtime.
A 'push' is used to upload the node-red application into bluemix. This is different to then deploying your flows into the application.

A: The deploy button is different from the CF push. The node-red deploy button is available in the node-red graphical UI.
Once you create your node-red application you have to launch it.
This is bullet number 3 on step 1 on the tutorial. On the Bluemix dashboard click in the application name to launch it.
The main window for node-red application is displayed (bullet number 4 on step 1 for the tutorial).
Clicking on the big red button "Go to your node-RED flow editor" will open the node-red flow editor (displayed on bullet number 5 on step 1). At this time you should see an empty sheet and the "Deploy" button at the top-right corner should be disabled.
Follow step 2 instructions to import the node-red flow (I included it below for your convenience):
[{"id":"bc740d23.438bf","type":"websocket-listener","path":"/ws/chat","wholemsg":"false"},{"id":"c86da933.379258","type":"websocket in","name":"","server":"bc740d23.438bf","x":112,"y":61,"z":"d46b9957.2b9468","wires":[["f9476129.06b8a"]]},{"id":"f9476129.06b8a","type":"function","name":"","func":"delete msg._session;\nreturn msg;\n\n","outputs":1,"valid":true,"x":286,"y":61,"z":"d46b9957.2b9468","wires":[["bda54943.425ab8"]]},{"id":"bda54943.425ab8","type":"websocket out","name":"","server":"bc740d23.438bf","x":467,"y":61,"z":"d46b9957.2b9468","wires":[]},{"id":"df7af34a.20851","type":"http in","name":"","url":"/chat","method":"get","x":120,"y":129,"z":"d46b9957.2b9468","wires":[["969892ad.69677"]]},{"id":"969892ad.69677","type":"template","name":"","field":"","template":"\n  <meta name=\"viewport\" content=\"width=320, initial-scale=1\">\n  <title>Chat</title>\n\n\n\n
\n

\n\n
\n
\n        <input type=\"text\" id=\"user\" placeholder=\"Who are you?\" />\n        <input type=\"text\" id=\"message\" placeholder=\"What do you want to say?\" />\n        <input type=\"button\" id=\"send_btn\" value=\"Send\" onclick=\"sendMessage()\">\n
\n
\n
\n\n\n\n\n\n","x":286,"y":129,"z":"d46b9957.2b9468","wires":[["82cb0232.7d35"]]},{"id":"82cb0232.7d35","type":"http response","name":"","x":429,"y":129,"z":"d46b9957.2b9468","wires":[]}]

Follow the other steps to import the flow above, deploy and run the application.


text:
Q: When Python circular import is unavoidable, what is the best solution? I first ran into this problem in the context of a larger set of existing libraries which are in serious need of a reorganisation. However, now is not the time and a problem has arisen after a recent set of changes. I've created an abstract example, which has the exact same problem as the real libraries.
We have the following file structure:
|- pack
|  |- sub_a
|  |  |- __init__.py
|  |  |- a_func.py
|  |- sub_b
|  |  |- __init__.py
|  |  |- b_func.py
|  |- __init__.py
|- runit.py

The main program is runit.py, it imports specific stuff it wants from the pack package and runs it.
runit.py:
import pack

print(pack.fa())
print(pack.fb())
print(pack.fab())
print(pack.fba())

The pack package consists of the rest of the files, starting with pack\__init__.py:
from .sub_a import fa, fab
from .sub_b import fb, fba

pack\sub_a\__init__.py:
from .a_func import fa, fab

pack\sub_a\a_func.py:
from ..sub_b import fb

def fa():
    return 0

def fab():
    return fb()

pack\sub_b\__init__.py:
from .b_func import fb, fba

pack\sub_b\b_func.py:
from ..sub_a import fa

def fb():
    return 1

def fba():
    return fa()

Now here is the problem: if you try to run runit.py, it fails with:
Traceback (most recent call last):
  File "C:/adir/runit.py", line 1, in <module>
    import pack
  File "C:\adir\pack\__init__.py", line 1, in <module>
    from .sub_a import fa, fab
  File "C:\adir\pack\sub_a\a_func.py", line 1, in <module>
    from ..sub_b import fb
  File "C:\adir\pack\sub_b\__init__.py", line 1, in <module>
    from .b_func import fb, fba
  File "C:\adir\pack\sub_b\b_func.py", line 1, in <module>
    from ..sub_a import fa
ImportError: cannot import name 'fb' 'fa' from 'pack.sub_a' (C:\adir\pack\sub_a\__init__.py)

However, if you remove the fa import (and change the line using it in fba()), it does work, in spite of the identical import of fb in a_func.py.
The cause is the fact that sub_a needs something from sub_b, but sub_b needs something from sub_a, so what is created is a circular import.
Now, of course for this example, the circular import is silly. The easiest solution would be to put all the functions in one place; then, since there is no circular dependency between the functions, there is no problem.
But for the actual situation, there is good reason for the somewhat circular reference (I say 'somewhat' because there is no actual circular dependency of functions, but of course Python doesn't know that until run-time).
The only options I see:

*

*put everything in one place;

*refactor the modules so that the code that is required by all others sits in a separate module, which does not depend on the rest; in this example, that would be fa() and/or fb();

*move the import statement to where it is needed, instead of at the top; in this example it would move inside of the fba() definition;

*refactor the actual functions / classes to rely on dependency injection; in this example, fba() could have a callback parameter;

*add an initialisation method for the module.

I don't like the first four: option 1. becomes a pain to read an maintain. Option 2. means that code that is currently fairly well-written and makes a lot of sense together will need to be pulled in two or more parts. Option 3. seems very much like an anti-pattern, as this makes it hard to see what dependencies any module has. And in option 4., calling conventions for existing functions change across the board.
Note: initially I worried about option 3. that any code in the body of the module would be executed on every import; however, it was pointed out by @a_guest that "modules are cached (in sys.modules) and will be fetched from this cache when needed, not executing the module's code again"
I'm inclined to use option 5. in this case and rewrite pack\sub_b\b_func.py like so:
def initialise():
    global fa
    from pack import fa as pack_fa
    fa = pack_fa

def fb():
    return 0

def fba():
    return fa()

Update pack\sub_b\__init__.py:
from .b_func import fb, fba, initialise

And then pack\__init__.py becomes:
from .sub_a import fa, fab
from .sub_b import fb, fba

for module in [sub_a, sub_b]:
    if hasattr(module, 'initialise'):
        module.initialise()

This gets around the problem by completing all the imports before actually calling the function that closes the loop - which doesn't cause a conflict because there is no actual loop inside the functions.
The downside here is that the __init__.py of pack now is aware of the need for initialisation of the sub_b module and that module itself has some extra code that is only there as a workaround to this problem, but all the other code works exactly as expected (both new and legacy).
And as long as anyone importing sub_b will always call initialise at least once before using its content, it can even still be used outside of pack, assuming the right dependencies are available.
My question then: is there a sixth, possibly even better option to deal with circular imports?
Note: please, I am not looking for opinions on what is nicer, although if you have a strong, rational argument for why one of these options must be considered superior, it might answer my question - but I'm really after a better option I'm just missing here. I'm not making a case for this type of code design - it should have been avoided, but it wasn't.
Disclaimer: I'm aware of other questions on SO about circular dependencies and circular imports in Python, but I don't think my question duplicates them, as none of them gets this deep into the woods and asks the final question


text:
Q: Applying duality and KKT conditions to LASSO problem I'm having some difficulties understanding how duality leads to the common form of LASSO problem and with Karush-Kuhn-Tucker condition called complementary slackness. I have two questions:

*

*We know that, given an optimization problem
$$
\begin{align*}
&\min_x f(x)\\
&s.t.  \quad h_i(x) \leq 0 \, ,\quad i=1,\dots, m
\end{align*}
$$

solving this is equivalent to solving the dual problem
$$
\begin{align*}
&\max_\lambda \,\, g(\lambda) \\
&s.t. \quad \lambda \geq 0
\end{align*}
$$
with $g(\lambda) = min_\lambda \bigr\{f(x) + \sum_{i=1}^m \lambda_i h_i(x)\bigr \}$
In the LASSO problem, the primal is
$$
\begin{align*}
    &||y-X\beta ||_2^2 \\
    &s.t. \,\,\,\, ||\beta ||_1 \leq t
\end{align*}
$$
so, if my understanding is correct, for the  dual problem we should get
$$
    g(\lambda) = \min_\beta ||y-X\beta ||_2^2 + \lambda( ||\beta ||_1 -t)
$$
However, the LASSO problem is always specified as
$$
\min_\beta ||y-X\beta ||_2^2 + \lambda ||\beta ||_1
$$
what am I missing? Is it related to the derivative of a constant, which is null?

*The second question is:  I saw many authors presenting the solution to the LASSO problem by just solving the stationarity KKT condition
$$ X^T(y-X\beta)=\lambda s $$

I understand that, as the problem is convex, the primal and dual feasibility conditions are satisfied, anyway I don't see why we don't check for complementary slackness condition.

A: 1) You're going the wrong direction by invoking duality directly. To get from
$\text{arg min}_{\beta: \|\beta\|_1 \leq t} \|y - X\beta\|_2^2$
to
$\text{arg min}_{\beta} \|y - X\beta\|_2^2 + \lambda\|\beta\|_1$
you just need to invoke Lagrange multipliers. (See, e.g. Section 5.1 of [1])
LMs are often discussed in the context of duality when teaching them, but in practice you can just switch directly from one to the other without considering the dual problem.
If you are interested in the dual problem of the lasso, it's worked out on Slides 12 and 13 of [2]
2) What you have probably seen is the KKT Stationarity condition for the Lasso:
$\text{arg min}\frac{1}{2}\|y - X\beta\|_2^2 + \lambda \|\beta\|_1 \Longleftrightarrow -X^T(y - X\hat{\beta}) + \lambda s = 0 \text{ for some } s \in \partial \|\hat{\beta}\|_1$
where $\partial \|\beta\|_1$ is called the subdifferential of the $\ell_1$ norm. (This is essentially just the standard "derivative equals zero at minimum" condition from calculus, but adjusted for non-differentiability.)
We know the subdifferential of $|\beta_i| = \text{sign}(\beta_i)$ if $\beta_i \neq 0$ so this equation gives an exact closed form solution for the lasso if we know the support and sign of the solution. Namely,
$\hat{\beta}_{\hat{S}} = (X_{\hat{S}}^TX_{\hat{S}})^{-1}(X_{\hat{S}}^Ty - \lambda * \text{sign}(\hat{\beta}_{\hat{S}}))$
(Aside: this solution makes the "shrinkage" effect of the lasso (as compared to OLS) very clear.)
Of course, the hard part of solving the lasso is finding the support and signs of the solution, so this is not terribly helpful in practice.
It is, however, a very useful theoretical construct and can be used to prove lots of nice properties of the lasso; most importantly, it lets us use the "primal-dual witness" technique to establish conditions under which the lasso recovers the "true" set of variables. See Section 11.4 of [3].
[1] S. Boyd and L. Vandenberghe. Convex Optimization. Available at https://web.stanford.edu/~boyd/cvxbook/bv_cvxbook.pdf
[2] http://www.stat.cmu.edu/~ryantibs/convexopt-F15/lectures/13-dual-corres.pdf
[3] T. Hastie, R. Tibshirani, M. Wainwright. Statistical Learning with Sparsity: The Lasso and Generalizations. Available at https://web.stanford.edu/~hastie/StatLearnSparsity_files/SLS_corrected_1.4.16.pdf


text:
Q: Symmetric groups on an infinite set
(a) If p is a prime number bigger than $n$, show that $S_n$ has no element of order $p$.
  (b) Decide whether or not $S_7$ has an element of order $12$. Either give an example, or give a proof that no such element exists.
  (c) Give an example of an infinite set $S$ and an element $s$ of the group $Sym(S)$ such that $o(s) = 3$.

My attempt:
a) Order of $S_n$ is $n!=n\times (n-1)\times ...\times 2\times 1.$ Since $p$ is prime and greater than $n$, then $\gcd(p,n-i)=1, i = 0,...,n-1.$ Hence, $\gcd(p,n!)= \prod_{i=0}^{n-1}\gcd(p,n-i)=1,$ so $p \nmid n!$ By Lagrange's theorem order of an element must divide order of the group, therefore $S_n$ has no element of order $p$.
b) $|S_7| = 7!,$ and $12\mid 7!$, so by Lagrange's theorem there is an element of order $12$. Example: Consider product of disjoint cycles $(1 2 3)(4 5 6 7)$, then the order is lcm$(3,4) = 12$.
Are there any mistakes in my reasoning?
I don't quite understand part(c). Can someone explain about symmetric groups on an infinite set?

A: If $X$ is any set, the symmetric group $\text{Sym}(X)$ is the set of all bijections $f : X \to X$ where the group operation is composition. The identity element of this group is the identity map on $X$.
So, for example, $f \in \text{Sym}(X)$ has order $3$ if and only if $n=3$ is the smallest natural number having the property that
$$f^n(x) = \underbrace{f \circ f \circ \cdots \circ f}_{\text{$n$ times}} (x)  \,\,\text{is equal to $x$, for all $x \in X$.}
$$
So take your favorite infinite set $X$. Can you write down an order $3$ element of $\text{Sym}(X)$? (Hint: write down some familiar order $3$ elements of finite symmetric groups, express those elements as bijections from a set to itself, and try to find a pattern).


text:
Q: Order of variable names pivot_wider How can you change the order of the variable names in pivot_wider to have he names_from before the values_from?
Using the us_rent_income dataset:
df <- us_rent_income %>%
  pivot_wider(names_from = NAME,
              values_from = c(estimate, moe))

This gives results like 'estimate_Alabama', how do we change the order of the variable so it is 'Alabama_estimate'?

A: Edit: As of tidyr 1.1.0 the order of the variable names can be controlled with the names_glue argument:
us_rent_income %>%
  pivot_wider(
    names_from = NAME,
    values_from = c(estimate, moe),
    names_glue = "{NAME}_{.value}"
  )

Old answer:
The documentation for pivot_wider() states "If values_from contains multiple values, the value will be added to the front of the output column" so there doesn't seem to be any way to control this as part of the reshape.  Instead, it has to be done afterwards.
Assuming there are no other variable names in the dataset that contain _ (if so, the separator can be changed to something unique using the names_sep argument), one approach would be:
library(tidyr)

df <- us_rent_income %>%
  pivot_wider(names_from = NAME,
              values_from = c(estimate, moe)) %>%
  setNames(nm = sub("(.*)_(.*)", "\\2_\\1", names(.)))

head(names(df))

[1] "GEOID"  "variable"  "Alabama_estimate"  "Alaska_estimate"  "Arizona_estimate"  "Arkansas_estimate"

A: A possible solution:
df <- us_rent_income %>%
  pivot_wider(names_from = NAME,
              values_from = c(estimate, moe))

names(df) <- sapply(strsplit(names(df), "_"),
                    function(x) if(length(x)>1) paste0(x[2],"_",x[1]) else x)

names(df)
# [1] "GEOID" "variable" "Alabama_estimate" "Alaska_estimate"
#     "Arizona_estimate" "Arkansas_estimate" "California_estimate" ...


text:
Q: Finding fourier coefficients of dirac comb Let's consider a dirac comb $f(x) = \sum_{n=-\infty}^{\infty} \delta(x-nb)$. I know it has a period of $b$. So, using the definition of finding fourier coefficients, I can write:
$C_n = \frac{1}{b} \int_{0}^{b} f(x) dx = \frac{1}{b} $$\int_{0}^{b} \sum_{n=-\infty}^{\infty} \delta(x-nb) dx$.
Now, since $x$ ranges from $0$ to $b$, only $n = 0$ and $n=1$ in the sum will give non-zero contribution to $C_n$. So, I get,
$C_n = \frac{1}{b} \int_{0}^{b} \delta(x) dx + \frac{1}{b} \int_{0}^{b} \delta(x-b) e^{-ik_{m}x}dx = \frac{1}{b} + \frac{1}{b} = \frac{2}{b}$
But the fourier series section in this wikipedia article on Dirac Comb says that the coefficient is supposed to be $\frac{1}{b}$ as have many other online articles that I have read.
Could anyone explain what I am getting wrong?


text:
Q: optimize common parameters across several equations using least squares in python I would like to optimize common parameters among several equations, but i dont know how to fit them simultaneously.
The problem is essentially like this, with four equations to solve and three parameters to optimize:
a+b+c+1750=T
12=a/T*100
15=b/T*100
37=c/T*100
where I would like to find the optimal values of a,b, and c. Does anybody have a suggestion, perhaps using a least squares method? I am only familiar when there is but one equation to solve.

A: This is a system of 4 equations with 4 unknowns. It can be solved algebraically.
solving for a, b, and c and plugging into the first equation. I'm assuming the (*100) is in the denominator of the equations for a, b, and c.
12 x 100 x T + 15 x 100 x T + 37 x 100 x T + 1750 = T
T = 3.66

Then, plug this value of T into the equations for a, b, and c

A: It seems your equations actually have 4 parameters, a, b, c and T, so you have a set of 4 linear equations with 4 parameters:
a + b + c - T = -1750
100 * a - 12 * Y = 0
100 * b - 15 * Y = 0
100 * c - 37 * Y = 0

You can solve this using the coefficients in a matrix:
import numpy as np

a = np.array([[1., 1., 1., -1.],
              [100., 0, 0, -12.],
              [0, 100., 0, -15.],
              [0, 0, 100., -37.]])
b = np.array([-1750., 0, 0, 0])

If there is an analytical solution, you can use
res = np.linalg.solve(a, b)
# res: [  583.33333333   729.16666667  1798.61111111  4861.11111111]

Otherwise (or for a more general case) you can approximate a solution using least-squared algorithm
res, err, _, __ = np.linalg.lstsq(a, b)
# res: [  583.33333333   729.16666667  1798.61111111  4861.11111111]


text:
Q: On a Windows system, where should I put the gemrc file so that Puppet can find it? Running Puppet Enterprise 3.7.
The Agent machine is a Windows 2012 Server R2  box.
Question: Where do I put the gemrc file so that Puppet's internal ruby can find it?
On Linux, the place to put the file seems to be /opt/puppet/etc/gemrc.
The goal: instruct puppet to NOT look on rubygems.org for Gems, but instead look at our internal Gemserver.

A: I've put it in the user's (user that runs Puppet) home (%HOMEPATH%). This should be one of the paths RubyGems looks for the gemrc file.

A: After experimentation, this is where I put the gemrc file:
C:\ProgramData
Be sure to remove the leading dot from the filename.
In this directory, the gemrc applies to all users, not just the currently logged in user, which is the way we want it. If it was just for a single user, Belmin's answer would have been the correct answer.


text:
Q: Why I am having a Segmentation fault? /* This Program generates a file with a pseudo-random number of st_record_t structures. The file is passed by command line arguments. The program must by executed, in UNIX, this way: ./file_gen -path <path> */

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include "types.h"

#define MSG_INVALID_INPUT "Your input was not valid"

#define CMD_FLAG_PATH_POSITION 1
#define CMD_ARG_PATH_POSITION 2

#define CMD_FLAG_PATH "-path"

#define SDM_MAX 10000.0

status_t validate_arguments (int argc, char * argv []);

int main (int argc, char * argv [])
{
    FILE * fi;
    size_t i;
    st_record_t aux_struct, aux2_struct;
    int size;

    if ((validate_arguments(argc, argv))!= OK)
    {
        fprintf(stderr, "%s\n", MSG_INVALID_INPUT);
        return EXIT_FAILURE;
    }

    if((fi = fopen(argv[CMD_ARG_PATH_POSITION], "wb")) == NULL)
        return EXIT_FAILURE;

    srand(time(NULL));
    for (i=0; i<(size=100); i++)
    {
        aux_struct.SDM = (((float)rand()/(float)(RAND_MAX)) * SDM_MAX); /*pseudo-random real number between 0 and SDM_MAX*/
        (aux_struct.ID) = i;
        (aux_struct.coordinates)->latitude.deg = rand()%180;
        (aux_struct.coordinates)->latitude.min = rand()%60;
        (aux_struct.coordinates)->latitude.sec = rand()%60;
        (aux_struct.coordinates)->longitude.deg = rand()%180;
        (aux_struct.coordinates)->longitude.min = rand()%60;
        (aux_struct.coordinates)->longitude.sec = rand()%60;
        if((fwrite (&aux_struct, sizeof(st_record_t), 1, fi))!=1)
            return ERROR_WRITING_FILE;
      }

    if(fclose(fi) == EOF)
        return EXIT_FAILURE

    return EXIT_SUCCESS;
}

The problem is with the (aux_struct.coordinates)->latitude.deg = rand()%180 lines. If instead of using a random number I select one, this won't happen
The st_record_t struct is defined this way:
typedef struct {
        unsigned char deg, min, sec;
        }angle_t;

typedef struct {
        angle_t latitude, longitude;
        }st_coord_t;

typedef struct {
        float SDM;
        size_t ID;
        st_coord_t * coordinates;
        }st_record_t;

A: The segmentation fault has nothing to do with random number, it's because you never allocate memory for aux_struct.coordinates.
To fix the problem, use something like:
aux_struct.coordinates = malloc(sizeof(st_coord_t));

Remember to free the memory when it's not used any more.

A: In addition to the issue of the missing initialization of the "coordinates" member, it should be pointed out that the fwrite() will not do what you want. It will just write the contents of the st_record_t. The value of the pointer "coordinates" has no meaning outside the process that is doing the writing and the data in the st_coord_t structure it points to will not get written at all.
You might want to look at something like hdf5 to write complex binary data structures to file in a portable way.

A: You have
typedef struct {
        float SDM;
        size_t ID;
        st_coord_t * coordinates;
        }st_record_t;

As you can see,coordinates is a pointer of type st_coord_t. You need to allocate memory for it using malloc:
aux_struct.coordinates=malloc(sizeof(st_coord_t));

And you need to free the allocated memory after its use using:
free(aux_struct.coordinates);

Note that you must allocate memory for coordinates in aux2_struct if you want to use it and later free it after its use.


text:
Q: Coloring columns in a table with colortbl and booktabs I have created a rather complicated table with some columns that I want to color. For the table, I chose the booktabs and tabularx packages. For coloring the columns, I use colortbl.
The problem that I have is that \midrules show a white space, and the result does not please me at all. Here is a MWE:
\documentclass[a5paper]{article}
\usepackage{xcolor}
\usepackage{booktabs,colortbl,tabularx}
\begin{document}
\pagestyle{empty}
\begin{table*}[!htb]
  \centering
  \begin{tabularx}{4cm}{>{\columncolor{gray}}cX>{\columncolor{gray}}c}
    \toprule
    1&2&3\\
    \midrule
    one&two&three\\
    one&two&three\\
    \cmidrule{2-3}
    one&two&three\\
    \midrule
    un&deux&trois\\
    \bottomrule
  \end{tabularx}
  \caption{caption}
\end{table*}
\end{document}

Looking around I found that booktabs supports colortbl in its latest version. However, it seems that it only supports colored horizontal lines.
I tried not using booktabs and replacing midrules for hlines. My huge table looks too crowded (once you booktab, you never go back, I guess).
My question is: is it possible to achieve a correct coloring in midrules ? Since I fear that the response is no: what low-cost recommendation do you have in order to color the columns of my table?
(When I say low-cost, I mean that I do not want to re-write my table contents)

A: There's no way to do this given the way booktabs inserts space between above and below its rules.  As Herbert notes inthe comments, it's not clear that rules and colours are really a logical combination.  So probably the best you can do is to increase the row height and set the space above and below the rules to 0.
\documentclass{article}
\usepackage{xcolor}
\usepackage{booktabs,colortbl,tabularx}

\begin{document}
% Your original table
  \begin{tabularx}{4cm}{>{\columncolor{gray}}cX>{\columncolor{gray}}c}
    \toprule
    1&2&3\\
    \midrule
    one&two&three\\
    one&two&three\\
    \cmidrule{2-3}
    one&two&three\\
    \midrule
    un&deux&trois\\
    \bottomrule
  \end{tabularx}
% same table with booktab rules but no above space and making rows bigger
\setlength{\aboverulesep}{0pt}
\setlength{\belowrulesep}{0pt}
\setlength{\extrarowheight}{.75ex}
  \begin{tabularx}{4cm}{>{\columncolor{gray}}cX>{\columncolor{gray}}c}
    \toprule
    1&2&3\\
    \midrule
    one&two&three\\
    one&two&three\\
    \cmidrule{2-3}
    one&two&three\\
    \midrule
    un&deux&trois\\
    \bottomrule
  \end{tabularx}
% same table without booktab rules
\setlength{\extrarowheight}{.75ex}
  \begin{tabularx}{4cm}{>{\columncolor{gray}}cX>{\columncolor{gray}}c}
    \hline
    1&2&3\\
    \hline
    one&two&three\\
    one&two&three\\
    \cline{2-3}
    one&two&three\\
    \hline
    un&deux&trois\\
    \hline
  \end{tabularx}
\end{document}

The middle table still looks marginally better than the third one.

A: Rules and colour in a tabular is not necessary, as it is said in the note, but if you nevertheless insist using it, the package cals is able to handle both:
\documentclass{article}
\usepackage{cals}
\usepackage{xcolor}

\begin{document}

\begin{table*}[!htb]
\begin{calstable}[c]
% Defining columns
\colwidths{{1.5cm}
            {2.25cm}
            {1.75cm}
            }

% Set up the tabular
\makeatletter
\def\cals@framers@width{0.8pt}   % Outside frame rules, reduce if the rule is too heavy
\def\cals@framecs@width{0pt}
\def\cals@bodyrs@width{0.4pt}    % "midrule" - line between heading and body
\cals@setpadding{Ag}
\cals@setcellprevdepth{Al}
\def\cals@cs@width{0pt}             % Inside rules, reduce if the rule is too heavy
\def\cals@rs@width{0.6pt}
\def\cals@bgcolor{}

\def\gray{\ifx\cals@bgcolor\empty     % "Switch" to turn on and off colour
    \def\cals@bgcolor{gray!50}
\else \def\cals@bgcolor{} \fi}

\def\bb{\ifx\cals@borderB\relax     % Bottom border switch (off-on)
\def\cals@borderB{0pt}
\else \let\cals@borderB\relax\fi}

% R1B1
\thead{%
\brow
    \gray\alignC\cell{1}\gray
    \alignL\cell{2}
    \gray\alignC\cell{3}\gray
\erow
}
%R2B2
\brow
    \gray\alignC\cell{\vfil one}\gray
    \alignL\cell{\vfil two}
    \gray\alignC\cell{\vfil three}\gray
\erow
%R3B3
\brow
    \gray\bb\alignC\cell{\vfil one}\bb\gray
    \alignL\cell{\vfil two}
    \gray\alignC\cell{\vfil three}\gray
\erow
%R4B4
\brow
    \gray\alignC\cell{\vfil one}\gray
    \alignL\cell{\vfil two}
    \gray\alignC\cell{\vfil three}\gray
\erow
%R4B4
\brow
    \gray\alignC\cell{\vfil un}\gray
    \alignL\cell{\vfil deux}
    \gray\alignC\cell{\vfil trois}\gray
\erow
\makeatletter
\end{calstable}\par
  \caption{caption}
\end{table*}
\end{document}

A: The environment {NiceTabular} of nicematrix provides tools to color cells, rows and columns in a way compatible with the horizontal rules of booktabs.
\documentclass[a5paper]{article}
\usepackage{xcolor}
\usepackage{booktabs,nicematrix}
\usepackage{lipsum}

\begin{document}

\pagestyle{empty}

\lipsum[1]

\begin{table*}[!htb]
  \centering
  \begin{NiceTabular}[width=4cm,colortbl-like]{>{\columncolor{gray}}cX>{\columncolor{gray}}c}
    \toprule
    1&2&3\\
    \midrule
    one&two&three\\
    one&two&three\\
    \cmidrule{2-3}
    one&two&three\\
    \midrule
    un&deux&trois\\
    \bottomrule
  \end{NiceTabular}
  \caption{caption}
\end{table*}

\end{document}

You need several compilations (because nicematrix uses PGF/Tikz nodes under the hood).


text:
Q: Validate password against previously hashed passwords using NetValidatePasswordPolicy According to Microsoft documentation NetValidatePasswordPolicy has possibility to implement feature to check password history and avoid reuse of previous passwords. I have gone through all the examples of this API but non of them provide me with functional of how to check Password history. Can somebody guide me how to verify password history?
    public static NET_API_STATUS ValidatePassword(string password)
    {
        var outputArgs = new NET_VALIDATE_OUTPUT_ARG();
        var inputArgs = new NET_VALIDATE_PASSWORD_CHANGE_INPUT_ARG();
        var passwordHistory = new NET_VALIDATE_PASSWORD_HASH();

        IntPtr inputPointer = IntPtr.Zero;
        IntPtr outputPointer = IntPtr.Zero;

        try
        {

            inputArgs.PasswordMatched = true;
            inputArgs.ClearPassword = Marshal.StringToBSTR(password);
            //var serverName = System.Environment.MachineName;
            string userNameToCheck = @"usr";
            //inputArgs.ClearPassword = Marshal.StringToBSTR(password);
            inputArgs.UserAccountName = userNameToCheck;

            // If using a secure string
            ////inputArgs.ClearPassword = Marshal.SecureStringToBSTR(secureStringPassword);

            inputPointer = Marshal.AllocHGlobal(Marshal.SizeOf(inputArgs));
            Marshal.StructureToPtr(inputArgs, inputPointer, false);

            NET_API_STATUS status = NetValidatePasswordPolicy("serverdc1", IntPtr.Zero, NET_VALIDATE_PASSWORD_TYPE.NetValidatePasswordChange, inputPointer, ref outputPointer);

            if (status == NET_API_STATUS.NERR_Success)
            {
                outputArgs = (NET_VALIDATE_OUTPUT_ARG)Marshal.PtrToStructure(outputPointer, typeof(NET_VALIDATE_OUTPUT_ARG));
                NET_VALIDATE_PASSWORD_HASH OutPasswordHistory = new NET_VALIDATE_PASSWORD_HASH();
                OutPasswordHistory.Hash = outputArgs.ChangedPersistedFields.PasswordHistory;
                OutPasswordHistory.Length = outputArgs.ChangedPersistedFields.PasswordHistoryLength;

                // Copy the Structure to the IntPtr

                if (outputArgs.ValidationStatus == NET_API_STATUS.NERR_Success)
                {
                    // Ok
                    string emtp;
                }

                return outputArgs.ValidationStatus;
            }
            else
            {
                return status;
            }
        }

A: I don't believe you can ask for a specific component of the policy to be tested - just the sum of the policy against the provided password.


text:
Q: Groupby sum and count on multiple columns under multiple conditions in Python I have a pandas dataframe that looks like this:
import pandas as pd
import numpy as np
data = {
    "Type": ["A", "A", "B", "B", "B"],
    "Project": ["X123", "X123", "X21", "L31", "L31"],
    "Number": [100, 300, 100, 200, 500],
    "Status": ['Y', 'Y', 'N', 'Y', 'N']
}
df = pd.DataFrame.from_dict(data)

I want to group by Type and get count and sum with several conditions and get results as follows:
Type  Total_Count  Total_Number  Count_Status=Y  Number_Status=Y  Count_Status=N  Number_Status=N
 A        2          400              2               400              0               0
 B        5          800              1               200              2              600

I have tried following but not exactly what i need. Please share any ideas that you might have. Thanks!
df1 = pd.pivot_table(df, index = 'Type', values = 'Number', aggfunc = np.sum)
df2 = pd.pivot_table(df, index = 'Type', values = 'Project', aggfunc = 'count')
pd.concat([df1, df2], axis=1)

A: Start with pivot_table:
pv = (df.pivot_table(index='Type',
                     columns='Status',
                     values='Number',
                     aggfunc='sum')
        .add_prefix('Number_Status='))

print(pv)
Status  Number_Status=N  Number_Status=Y
Type
A                   NaN            400.0
B                 600.0            200.0

Next, groupby:
totals = df.groupby('Type').Number.agg([
    ('Total_Count', 'count'),  ('Total_Number', 'sum')])

print(totals)
      Total_Count  Total_Number
Type
A               2           400
B               3           800

Finally, status counts with OHEs:
cnts = (df.set_index('Type').Status
          .str.get_dummies()
          .sum(level=0)
          .add_prefix('Count_Status='))

      Count_Status=N  Count_Status=Y
Type
A                  0               2
B                  2               1

Putting it all together:
pd.concat([pv, totals, cnts], axis=1).sort_index(axis=1)

      Count_Status=N  Count_Status=Y  Number_Status=N  Number_Status=Y  \
Type
A                  0               2              NaN            400.0
B                  2               1            600.0            200.0

Total_Count  Total_Number
          2           400
          3           800

A: Doing with
s1 = df.groupby('Type').Number.agg(['count', 'sum'])
s2 = df.groupby(['Type', 'Status']).Number.agg(['count', 'sum']).unstack(fill_value=0).sort_index(level=1, axis=1)
s2.columns = s2.columns.map('_Status='.join)
s1 = s1.add_prefix('Total_')
s = pd.concat([s1, s2], axis=1)
s
      Total_count  Total_sum  count_Status=N  sum_Status=N  count_Status=Y  \
Type
A               2        400               0             0               2
B               3        800               2           600               1
      sum_Status=Y
Type
A              400
B              200

A: You can use the margins argument of pd.pivot_table. Drop the column total at the end as you only want row-wise margins.
import pandas as pd

df1 = df.pivot_table(index='Type', columns='Status', values='Number',
                     aggfunc=['sum', 'count'],
                     margins=True,
                     margins_name='Total').fillna(0).drop('Total')
#          sum              count
#Status      N      Y Total     N    Y Total
#Type
#A         0.0  400.0   400   0.0  2.0     2
#B       600.0  200.0   800   2.0  1.0     3

If needed, rename the columns:
d = {'Y': 'Status=Y', 'N': 'Status=N', 'Total': 'Total'}
df1.columns = [f'{x}_{d.get(y)}' for x,y in df1.columns]

Output df1:
      sum_Status=N  sum_Status=Y  sum_Total  count_Status=N  count_Status=Y  count_Total
Type
A              0.0         400.0        400             0.0             2.0            2
B            600.0         200.0        800             2.0             1.0            3

A: If you want to create a Function:
def my_agg(x):
    names = {
        'Total_Count': x['Type'].count(),
        'Total_Number': x['Number'].sum(),
        'Count_Status=Y': x[x['Status']=='Y']['Type'].count(),
        'Number_Status=Y': x[x['Status']=='Y']['Number'].sum(),
        'Count_Status=N': x[x['Status']=='N']['Type'].count(),
        'Number_Status=N': x[x['Status']=='N']['Number'].sum()}

    return pd.Series(names)

df.groupby('Type').apply(my_agg)

    Total_Count   Total_Number  Count_Status=Y  Number_Status=Y Count_Status=N  Number_Status=N
Type
A      2           400                2                400            0             0
B      3           800                1                200            2            600

A: You can use pandas.core.groupby.GroupBy.apply to complete this task. For example, you can write a function to process your data on each column after getting Groupby object.
def compute_metrics(x):
    result = {'Total_Number': x['Number'].sum(), 'Count_Status=Y': len(x['Status'] == "Y")}
    return pd.Series(result)

Then the df.groupby('Type').apply(compute_metrics) will return the dataframe like this:
Type  Total Number Count_Status=Y
A     400          2
B     800          3

Hope this will be helpful.
Cheers.


text:
Q: What is undefined times zero? Einstein's energy equation (after substituting the equation of relativistic momentum) takes this form:
$$E =   \frac{1}{{\sqrt {1 - {v^2}/{c^2}} }}{m_0}{c^2}
% $$
Now if you apply this form to a photon (I know this is controversial, in fact I would not do it, but I just want to understand the consequences), you get the following:
$$E = \frac{1}{0}0{c^2}% $$
On another note, I understand that after dividing by zero:

*

*If the numerator is any number other than zero, you get an "undefined" = no solution, because you are breaching mathematical rules.

*If the numerator is zero, you get an "indeterminate" number = any value.

Here it seems we would have an "indeterminate" [if (1/0) times 0 equals 0/0], although I would prefer to have an "undefined" (because I think that applying this form to a photon breaches physical/logical rules, so I would like the outcome to breach mathematical rules as well...) and to support this I have read that if a subexpression is undefined (which would be the case here with gamma = 1/0), the whole expression becomes undefined (is this right and if so does it apply here?).
So what is the answer in strict mathematical terms: undefined or indeterminate?

A: I don't think you've quite come to terms yet with what undefined means. It means quite literally this expression has no meaning. So $1/0$ is literally meaningless even though it might look like it has meaning to our human brains, we haven't defined it, so it really has no meaning. For this reason, while we know that $x\cdot 0 = 0$ for any real number $x$, since $1/0$ is undefined, we don't even know that it is a real number, so we can't say $(1/0)\cdot 0 = 0$ nor can we say it is anything else for that matter. It is also undefined, because if we don't know what $1/0$ is, we can't know what anything made out of it is either.
Now of course one can try to extend definitions to define expressions that are currently undefined. However, for expressions such as the one you've given, the reason no one has done this is because there isn't a good way to do so.
Now the phrase "indeterminate form" is honestly not a great phrase. Either something has a value or it doesn't. Usually it's used to describe limits that don't obviously exist and/or whose value isn't obvious. For example while
$$\lim_{x\to 0} \frac{\sin x}{x} = 1,$$
people often say that it has an indeterminate form, since $$\lim_{x\to 0} \sin x = 0 = \lim_{x\to 0} x.$$
Thus a naive approach to the limit would seem to give you that the limit is $0/0$, which is undefined. However, it turns out the limit is quite well-defined, it's just that the naive approach to taking limits of fractions doesn't work when the denominator goes to 0.
Point being, your expression is undefined, and I would not describe it as indeterminate (though of course this depends on your definitions and where you're from). As I was taught, the phrase indeterminate form (if used at all) should be reserved for well-defined expressions such as limits whose existence or values are not obvious because a naive approach to taking such limits results in an undefined expression.

A: Undefined is not a number. There is no such number as undefined, for which you could define the multiplication operation.
You could extend a set of a numbers (the set of the real numbers or the set of the complex numbers) with a new element, what you call "undefined", and then define a multiplication on this set as usual. It might be possible (although there are major problems solve).
However, from this moment, you have a defined value what you still call "undefined". Well, paper can hold everything, but it does not really sound as useful mathematics.


text:
Q: WPF DataGrid not populating with information from viewmodel (DataBinding not working) I have a UserControl named TagGridView, and a corresponding TagGridViewModel which holds an ObservableCollection<TagViewModel> to be displayed in the DataGrid using data binding. TagViewModel exposes some properties that I am trying to display in a DataGrid.
I created a button that adds an item to the ObservableCollection<TagViewModel> and shows a messagebox with the collection's item count and the data grid's item count. The collection is getting all of the items, except the DataGrid consistently says 0 for its count.
Here is the XAML code with the data binding:
<UserControl x:Class="Company.TagVisualizer.Views.TagGridView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d" Width="Auto" Height="Auto" Name="TagGrid" DataContext="{Binding Source=TagGridContext}">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <DataGrid Name="DataGridTag" Grid.Column="0" Grid.Row="0" ItemsSource="{Binding Path=TagsCollection}" Margin="0" CanUserReorderColumns="False" CanUserResizeColumns="True" CanUserAddRows="True" CanUserDeleteRows="True">
            <DataGrid.Columns>
                <DataGridCheckBoxColumn Width="*"  Header="Selected" />
                <DataGridTextColumn Width="3*" Binding="{Binding Path=TagName}" Header="Tag Name"/>
                <DataGridTextColumn Width="3*" Binding="{Binding Detections.Count}" Header="Detections"/>
                <DataGridTextColumn Width="3*" Binding="{Binding EarliestDetection}"  Header="Earliest Detection"/>
                <DataGridTextColumn Width="3*" Binding="{Binding LatestDetection}" Header="Latest Detection"/>
            </DataGrid.Columns>
        </DataGrid>
        <Button Grid.Column="0" Grid.Row="1" Content="Add" Click="Add_OnClick"/>
    </Grid>

</UserControl>

Here is the codebehind file for the TagGridView:
public partial class TagGridView : UserControl
    {
        private TagGridViewModel _tagGridViewModel = new TagGridViewModel();

        public TagGridView()
        {
            InitializeComponent();

        }

        public TagGridViewModel TagGridContext { get { return _tagGridViewModel; } set { _tagGridViewModel = value; } }

        private void Add_OnClick(object sender, RoutedEventArgs e)
        {
            TagGridContext.TagsCollection.Add(new TagViewModel("Boogie", 134.5, 145.8));

            MessageBox.Show(string.Format("Items in collection: {0}\nItems in Grid: {1}", TagGridContext.TagsCollection.Count, DataGridTag.Items.Count));
        }
    }

Here is the TagGridViewModel class:
public class TagGridViewModel
    {
        private ObservableCollection<TagViewModel> _tagsCollection = new ObservableCollection<TagViewModel>();

        public ObservableCollection<TagViewModel> TagsCollection
        {
            get { return _tagsCollection; }
            set
            {
                _tagsCollection = value;
            }
        }
    }

I'm not sure what's going on. I have tried setting the DataContext in the UserControl tag and the DataGrid tag. No matter what I do, the DataGrid does not add any items to itself.

A: It is usercontrol Datacontext problem. Please refer the below code for databinding.
<UserControl x:Class="Tags_Learning.TagGridView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         mc:Ignorable="d"
         d:DesignHeight="300" d:DesignWidth="300" **DataContext="{Binding Path=TagGridContext, RelativeSource={RelativeSource Self}}"**>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <DataGrid Name="DataGridTag" Grid.Column="0" Grid.Row="0" ItemsSource="{Binding Path=TagsCollection}" Margin="0"
              CanUserReorderColumns="False" CanUserResizeColumns="True" CanUserAddRows="True" CanUserDeleteRows="True">
        <DataGrid.Columns>
            <DataGridCheckBoxColumn Width="*"  Header="Selected" />
            <DataGridTextColumn Width="3*" Binding="{Binding Path=TagName}" Header="Tag Name"/>
            <DataGridTextColumn Width="3*" Binding="{Binding EarliestDetection}"  Header="Earliest Detection"/>
            <DataGridTextColumn Width="3*" Binding="{Binding LatestDetection}" Header="Latest Detection"/>
        </DataGrid.Columns>
    </DataGrid>
    <Button Grid.Column="0" Grid.Row="1" Content="Add" Click="Add_OnClick"/>
</Grid>


text:
Q: Switch with range of values So I am to determine the base salary for an employee based on an inputed number of years the employee has worked for the company.
I have to do this using switch structures and I am given ranges as follows:
Number of years worked____Base Salary
 0 – 5                  $ 9,500
 6 – 11                 $12,700
12 – 17                 $15,300
18 – 29                 $22,600
 >= 30                  $26,800

So, how do I do ranges for the cases if I don't want to right case for all of the numbers?
It isn't too much of a hassle with this one, but then I have to figure out commission based on sales and that has ranges like $0-3,999.99 and $16,000-23,999.99.

A: If you are forced to use switch statement then consider the fact that multiple cases can be chained together:
switch (years) {
  case 0:
  case 1:
  case 2:
  ..
    return 9500;
  case 6:
  case 7:
  ..
}

But an if statement seems more suitable to the problem:
if (years >= 0 && years <= 5)
  ..
else if (years >= 6 && years <= 11)
  ..

A: So for part one, you just need to declare a switch where multiple cases follow one code path. Like this:
int baseSalary
switch (yearsWorked)
{
  case 0:
  case 1:
  case 2:
  case 3:
  case 4:
  case 5:
    baseSalary = 9500;
    break;

  case 6:
  case 7:
  case 8:
  case 9:
  case 10:
  case 11:
    baseSalary = 12700;
    break;

  ... etc ...
}

For the second part, a switch for every single number in a range of thousands is pretty unfeasible, but with a bit of smart division, it can be made equally easy. If you divide 2000 by 1000, you get 2, and if you divide 2500 by 1000, you also get 2 (with remainder 500). Using this, you can generate a switch statement:
int sales = 2100;
int salesRange = sales / 1000; // (salesRange = 2)

int commission
switch (salesRange)
{
  case 0:  // $0-999 sales
  case 1:  // $1000-1999 sales
  case 2:  // $2000-2999 sales
  case 3:  // $3000-3999 sales
    commission = <some number here>;
    break;

  ... etc ...
}

That being said, this assumes that "have to use a switch" is part of a school assignment or similar. As the other people have mentioned, you're better off using if statements with a range (e.g. if (sales >= 0 && sales <= 3999)) than using a switch for this kind of thing.

A: If you need dynamical creation of your ranges w/o hardcoding,
you can use this snippet
struct BaseSalary
{
    int requiredExperience; // years in company
    int amount;             // salary amount
};

struct SortCondition
{
    bool operator()(const BaseSalary& lhs, const BaseSalary& rhs)
    {
        return lhs.requiredExperience < rhs.requiredExperience;
    }
};

struct SearchCondition
{
    bool operator() (const BaseSalary& s, int exp)
    {
        return s.requiredExperience < exp;
    }
};

// Fill base salary list in any appropriate way

BaseSalary s1;
s1.requiredExperience = 3; // [0 - 3]
s1.amount = 3500;

BaseSalary s2;            // (3 - 7]
s2.requiredExperience = 7;
s2.amount = 7000;

BaseSalary s3;              // (7-10]
s3.requiredExperience = 10;
s3.amount = 11000;

std::vector<BaseSalary> salaries;
salaries.push_back(s2);
salaries.push_back(s3);
salaries.push_back(s1);

// Sort salaries in ascending order of experience

std::sort(salaries.begin(), salaries.end(), SortCondition());

// Get base salary based on experience

int exp_to_search = 5;

std::vector<BaseSalary>::iterator it = std::lower_bound(salaries.begin(), salaries.end(), some_exp, SearchCondition());
if(it == salaries.end())
{
    // > 10 years
}
else
{
    int amount = it->amount;
}


text:
Q: R ggplot Colors Don't match between different plots I'm new to ggplot, but cannot figure out why this is happening.  I have am trying to generate geom_bar plots with each column a different color within a facet, but the same for different facets.  It is doing that for me, but the problem is when I run these two similar codes my color scheme changes.  I've researched colorschemes and manually modifying it, but nothing is working.  Below are my codes and the different outputs I'm getting.
ggplot(dat.m,aes(x = `Prod Zone`,y = Average, fill = `Prod Zone`)) +
geom_bar(stat = "identity") +
facet_wrap(~variable, scales = "free") +
theme(axis.text.x=element_text(angle = 90,hjust = 1,vjust = .4),
      text = element_text(size = 15,face = "bold")) +
      guides(fill=FALSE)

ggplot(dat.m, aes(x = VintageComp, y = value, fill = `VintageComp`)) +
guides(fill = FALSE) +
geom_bar(stat = "identity") +
facet_wrap(~variable, scales = "free_y") +
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust =.4),
      text=element_text(size = 30, face = "bold"))

Everything is exactly how I want it to look, but the coloring.  For this example I want the first color scheme (rainbow looking) for both plots, I'd like to be able to choose a color scheme manually if someone could help me with that in this type of format.


text:
Q: Future-proof way to detect iPhones with a notch (like the iPhone X) I have an application that I want to go full screen (hiding the status bar) on iPhones that do not have a notch, but stick to the safe area (keeping the status bar visible) on iPhones that have a notch, like the iPhone X.
I cannot just restrict my application to the safe area on all devices, since the safe area includes the status bar on iPhones that do not have a notch.
The approaches I can think of are:

*

*Checking the device model, or

*Looking at the safe area insets for the main UIWindow and trying to infer something from the actual values (e.g. "if top inset is >22, then it has a notch")

None of the above is very clean, not future-proof.

A: I was not able to find any "future-proof" way to do this, so I am finally relying on the safe area insets.
One important note, though, is that this should not be done by checking the top inset alone, as the top inset may vary, for example, when the in-call status bar is being shown. It is better to check either the bottom inset or both bottom and top.


text:
Q: Exporting item version check in comments I have followed this answer to extract the list of versions in my document library to excel:
However, while the table lists all the versions it only displays (and repeats) the most recent check-in a comment.
Is there any other parameter I can add to the .iqy file that will pull out the comment for each version of the document? (or any other method to achieve the same thing)

A: You can use this parameter$($version['Check In Comment']) in the PowerShell script to get the 'Check In Comment'. but unfortunately, it gets only the comment of the current item (last version).
So to get the comment for each previous version of the document, try this

$($item.File.Versions.GetVersionFromLabel($version.VersionLabel).CheckInComment)

So try to Mix both parameters to get what exactly you need :)

$($item.File.Versions.GetVersionFromLabel($version.VersionLabel).CheckInComment),$($version['Check In Comment'])

OR Download the full script from Export the Version Comments and Version Details for each Document in SharePoint that handle this issue.


text:
Q: Gaps in table boundaries I am using tablesgenerator to generate tables, and the effect is not bad. But there are some flaws. For example, there is a gap at the corner of the boundary of the table.

And the border thickness does not keep the same thickness. Is there a good solution to modify the generated latex codes from tablesgenerator?
\documentclass{article}

\begin{document}
\begin{table}[]
    \begin{tabular}{clll}
        & a                     & b                     & c                    \\ \cline{2-4}
        \multicolumn{1}{c|}{1} & \multicolumn{1}{l|}{} & \multicolumn{1}{l|}{} & \multicolumn{1}{l|}{} \\ \cline{2-4}
        \multicolumn{1}{c|}{2} & \multicolumn{1}{l|}{} & \multicolumn{1}{l|}{} & \multicolumn{1}{l|}{} \\ \cline{2-4}
        \multicolumn{1}{c|}{3} & \multicolumn{1}{l|}{} & \multicolumn{1}{l|}{} & \multicolumn{1}{l|}{} \\ \cline{2-4}
    \end{tabular}
\end{table}
\end{document}

A: The direct answer to your question is : load the package array.
\documentclass{article}
\usepackage{array}

\begin{document}
\begin{table}[]
    \begin{tabular}{clll}
        & a                     & b                     & c                    \\ \cline{2-4}
        \multicolumn{1}{c|}{1} & \multicolumn{1}{l|}{} & \multicolumn{1}{l|}{} & \multicolumn{1}{l|}{} \\ \cline{2-4}
        \multicolumn{1}{c|}{2} & \multicolumn{1}{l|}{} & \multicolumn{1}{l|}{} & \multicolumn{1}{l|}{} \\ \cline{2-4}
        \multicolumn{1}{c|}{3} & \multicolumn{1}{l|}{} & \multicolumn{1}{l|}{} & \multicolumn{1}{l|}{} \\ \cline{2-4}
    \end{tabular}
\end{table}
\end{document}

However, there is other ways to create your table. Here is an example with nicematrix (which, in particular, loads array).
\documentclass{article}
\usepackage{nicematrix}

\begin{document}
\begin{table}[]
    \begin{NiceTabular}{lll}[first-row,first-col,hvlines]
        & a & b & c \\
      1 \\
      2 \\
      3 \\
    \end{NiceTabular}
\end{table}
\end{document}

The output is the same.


text:
Q: core-data consistency error I have an application that uses core-data.
The data model contains tables with names article,category, audio, images,channel.
Here article table is connected to all other tables.
Now in article table there is one relationship named related_articles which relates to the table itself(as you can see in the image belove), means it is given a recursive relationship(that is one article can be related to other article(s))..
it contains No Action as its delete rule and so it is giving this warning: "Consistency Error: Setting the No Action Delete Rule on  is an advanced setting".
So, here my question is what delete rule should I apply here so that it does not give consistency error at same time also does not affect app..

I found about this on net, but could not make out what should I do..:( :(
Any help would be appreciated.
Thanks and Regards

A: Why are you using No action delete rule?
If your app can afford the performance penalty, use Nullify instead (assuming that related_article relationship is optional).
No action makes you responsible of maintaining the consistency of the object graph, because the inverse relationship of a deleted object still believes the object exists.
This rule makes sense in to-many relationships with a large number of objects at the destination, where the cost of the Nullify is bigger than the complexity of manually tracking the inverse relationship.


text:
Q: How to return the keyboard to its original state after the completion of the script? This script is part of a telegram bot. The task of this script is to provide the user with a multiple choice of options.
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import (
    Updater,
    CommandHandler,
    CallbackQueryHandler,
    ConversationHandler)

import logging

green_check = '\u2705'
grey_check = '\u2714'

FIRST, ANSWER = range(2)
TEXT_1 = 'Click'
CHECK = grey_check
CLICK = False

KEYS = {'1': (0, 0), '2': (0, 1), '3': (1, 0), '4': (1, 1)}

keyboard = [
[
    InlineKeyboardButton(f'1 {grey_check}', callback_data='1'),
    InlineKeyboardButton(f'2 {grey_check}', callback_data='2'),
],
[
    InlineKeyboardButton(f'3 {grey_check}', callback_data='3'),
    InlineKeyboardButton(f'4 {grey_check}', callback_data='4'),
],
[
    InlineKeyboardButton('Next \u27A1', callback_data='next'),
],
]

def start(update, context):
    CHECK = grey_check
    reply_markup = InlineKeyboardMarkup(keyboard)
    update.message.reply_text(TEXT_1, reply_markup=reply_markup)
    for i in range(1,5):
        context.user_data[f'BUTTON_{i}'] = False

    return FIRST

def clicked(click=None, data=None):
    global keyboard
    global CHECK
    if click == True:
        CHECK = green_check
    else:
        CHECK = grey_check

    keyboard[KEYS[data][0]][KEYS[data][1]] = InlineKeyboardButton(
        f'{data} {CHECK}', callback_data=f'{data}')

    reply_markup = InlineKeyboardMarkup(keyboard)

    return reply_markup

def press(update, context):
    data = update.callback_query.data
    global CLICK
    if context.user_data[f'BUTTON_{data}'] == False:
        context.user_data[f'BUTTON_{data}'] = True
    else:
        context.user_data[f'BUTTON_{data}'] = False

    reply_keyboard = clicked(context.user_data[f'BUTTON_{data}'], data)
    update.callback_query.edit_message_text(text=TEXT_1, reply_markup=reply_keyboard)
    return FIRST

def send(update, context):
    text = ''
    for i in range(1, 5):
        text += f'{i} - ' + str(context.user_data[f'BUTTON_{i}']) + '\n'
    context.user_data[ANSWER] = text
    update.callback_query.edit_message_text(text=context.user_data[ANSWER])
    return ConversationHandler.END

def main():
    updater = Updater(
        'TOKEN', use_context=True)
    dp = updater.dispatcher
    conv_handler = ConversationHandler(
        entry_points=[CommandHandler('start', start)],
        states={
            FIRST: [
                    CallbackQueryHandler(press, pattern='^'+str(1)+'$'),
                    CallbackQueryHandler(press, pattern='^'+str(2)+'$'),
                    CallbackQueryHandler(press, pattern='^'+str(3)+'$'),
                    CallbackQueryHandler(press, pattern='^'+str(4)+'$'),
                    CallbackQueryHandler(send, pattern='^'+'next'+'$'),
                    ],
        },
        fallbacks=[CommandHandler('start', start)]
    )

    dp.add_handler(conv_handler)
    updater.start_polling()
    updater.idle()

if __name__ == "__main__":
    main()

After selecting the option, the color of the button changes to green, after sending the data and the next run of the /start script, the keyboard does not return to its original form. The buttons pressed by the user remain green, while the data change, when the buttons are pressed, occurs as expected.

A: After several attempts, I found this solution:
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import (
    Updater,
    CommandHandler,
    CallbackQueryHandler,
    ConversationHandler)

import logging

green_check = '\u2705'
grey_check = '\u2714'

FIRST, ANSWER = range(2)
TEXT_1 = 'Click'
CHECK = grey_check
CLICK = False
BUTTONS = []
KEYS = {'1': (0, 0), '2': (0, 1), '3': (1, 0), '4': (1, 1)}

keyboard = [
[
    InlineKeyboardButton(f'1 {CHECK}', callback_data='1'),
    InlineKeyboardButton(f'2 {CHECK}', callback_data='2'),
],
[
    InlineKeyboardButton(f'3 {CHECK}', callback_data='3'),
    InlineKeyboardButton(f'4 {CHECK}', callback_data='4'),
],
[
    InlineKeyboardButton('Next \u27A1', callback_data='next'),
],
]

def start(update, context):
    global CHECK
    global keyboard
    global BUTTONS
    CHECK = grey_check
    for data in BUTTONS:
        keyboard[KEYS[data][0]][KEYS[data][1]] = InlineKeyboardButton(
            f'{data} {CHECK}', callback_data=f'{data}')
    reply_markup = InlineKeyboardMarkup(keyboard)
    update.message.reply_text(TEXT_1, reply_markup=reply_markup)
    for i in range(1,5):
        context.user_data[f'BUTTON_{i}'] = False
    BUTTONS = []
    return FIRST

def clicked(click=None, data=None):
    global keyboard
    global CHECK
    global BUTTONS
    if click == True:
        CHECK = green_check
    else:
        CHECK = grey_check

    BUTTONS.append(data)
    keyboard[KEYS[data][0]][KEYS[data][1]] = InlineKeyboardButton(
        f'{data} {CHECK}', callback_data=f'{data}')

    reply_markup = InlineKeyboardMarkup(keyboard)

    return reply_markup

def press(update, context):
    data = update.callback_query.data
    global CLICK
    if context.user_data[f'BUTTON_{data}'] == False:
        context.user_data[f'BUTTON_{data}'] = True
    else:
        context.user_data[f'BUTTON_{data}'] = False

    reply_keyboard = clicked(context.user_data[f'BUTTON_{data}'], data)
    update.callback_query.edit_message_text(text=TEXT_1, reply_markup=reply_keyboard)
    return FIRST

def send(update, context):
    text = ''
    for i in range(1, 5):
        text += f'{i} - ' + str(context.user_data[f'BUTTON_{i}']) + '\n'
    context.user_data[ANSWER] = text
    update.callback_query.edit_message_text(text=context.user_data[ANSWER])

    return ConversationHandler.END

def main():
    updater = Updater(
        'TOKEN', use_context=True)
    dp = updater.dispatcher
    conv_handler = ConversationHandler(
        entry_points=[CommandHandler('start', start)],
        states={
            FIRST: [
                    CallbackQueryHandler(press, pattern='^'+str(1)+'$'),
                    CallbackQueryHandler(press, pattern='^'+str(2)+'$'),
                    CallbackQueryHandler(press, pattern='^'+str(3)+'$'),
                    CallbackQueryHandler(press, pattern='^'+str(4)+'$'),
                    CallbackQueryHandler(send, pattern='^'+'next'+'$'),
                    ],
        },
        fallbacks=[CommandHandler('start', start)]
    )

    dp.add_handler(conv_handler)
    updater.start_polling()
    updater.idle()

if __name__ == "__main__":
    main()

Perhaps this is not the best solution. Do you have any ideas how to improve this code?


text:
Q: What is the best way of recognizing handwritten symbols and texts? I am new to the image processing subject. I'm using opencv library for image processing with python. I need to extract symbols and texts related to those symbols for further work. I saw some of developers have done handwritten text recognitions with Neural network, KNN and other techniques.
My question is what is the best way to extract these symbols and handwritten texts related to them?
Example diagram:

Details I need to extract:

*

*No of Circles in the diagram.

*What are the texts inside them.

*What are the words within square brackets.

*Are they connected with arrows or not.

A: Of course, there is a method called SWT - Stokes Width Transform.
Please see this paper, if you search it by its name, you can find the codes that some students have written during their school project.
By using this method, text recognitions can be applied. But it is not a days job.
Site: Detecting Text in Natural Scenes with
Stroke Width Transform
Hope that it helps.

A: For handwritten text recognition, try using TensorFlow. Their website has a simple example for digit recognition (with training data). You can use it to implement your own application for recognizing handwritten alphabets as well. (You'll need to get training data for this though; I used a training data set provided by NIST.)

A: If you are using OpenCV with python, Hough transform can detect circles in images. You might miss some hand drawn circles, but there are ways to detect ovals and other closed shapes.
For handwritten character recognition, there are lots of libraries available.
Since you are now to this area, I strongly recommend LearnOpenCV and and PyImageSearch to help you familiarize with the algorithms that are available for this kind of tasks.


text:
Q: Trouble getting NuGet to work on XP I have Powershell 2 installed on the box.
I can run ISE and load modules. The command test-path PathAndFileName works fine.
The box is 64bit running 32bit XP Pro SP3 with VS2008 and VS2010 Premium edition loaded.
I installed the Nov8 version of Nuget using the .vsix.
I have downloaded the NuGet Command Line Tool.
When I try and open a "Add Library Package Reference" no packages are listed.
I can open the package manager console as Scott Hanselman showed off in PDC 2010.
I can type "list" press the tab key and it auto fills List-Package.
I read some articles about deleting previous copies however I do not think that is the issue. I have read where there was a "package" directory at the same level as the solution file. I do not have one.
I have read where the feed from CP1 has changed for CP2. I deleted all my feeds and added one called MicroDefault with a url of http://go.microsoft.com/fwlink/?LinkID=204820.  The url is from the NuGet download page.
The problem is when I execute List-Package I get the following.
PM> List-Package
Get-Package : Expected an absolute, well formed http URL without a query or fragment.
Parameter name: serviceRoot
At line:1 char:13
+ List-Package <<<<
    + CategoryInfo          : NotSpecified: (:) [Get-Package], ArgumentException
    + FullyQualifiedErrorId : NuGet.VisualStudio.Cmdlets.GetPackageCmdlet

Any further clues or hints would be awesome.

A: I know that NuGet had a problem with Reflector plug-in for Visual Studio.  Downloading the latest Reflector plug-in should fix the problem.
Also you can check out this article that tells how to create a package.

A: When you open the dialog, it shows the list of Installed packages by default. Did you click on the Online tab?
The official OData feed is located at: http://go.microsoft.com/fwlink/?LinkID=206669
Also, be sure to visit our Known Issues page: http://nuget.codeplex.com/documentation?title=Known%20Issues
WinXP doesn't have PowerShell 2.0 installed by default. You'll need to make sure that's installed.

A: What ended up fixing it was the advice in this link. At first I thought it was getting my IT to lower the firewall settings this proved to be incorrect.
http://weblogs.asp.net/jgalloway/archive/2011/02/02/downloading-a-local-nuget-repository-with-powershell.aspx


text:
Q: How to import and use luxon in a vuejs project? I'm facing this error when I try to use luxon in my vuejs2 project.
Uncaught TypeError: Cannot read property 'local' of undefined

I installed the lib using npm, and imported in my component :
import DateTime from 'luxon'
const exmpl = DateTime.local()

Can you guys show me what I did wrong or even propose an other librairie for time manipulation that can work easily with vuejs.

A: Importing
I'd like to make an explanation with general ES6 syntax.
Let's import those amazing helpful helper functions:
import { sayName, sayAnimal } from './Helpers';
import whatsYourFlava from './Helpers';
sayName('Sam');
//Hello Sam
sayAnimal('Giraffe');
//What animal? Giraffe
whatsYourFlava('grapes');
//I'm liking grapes

When importing named exports, you'll have to wrap them in curly braces. If you're importing multiple exports from the same module, you can concatenate them, comma based, and use them in the same wrapping curly braces. This looks a lot like destructuring in ES6, but actually doesn't have anything to do with it.
When you import, and omit the curly braces, it will look for the default export in the module you're importing from. Because it knows it has to look for the default export, you can use any random name for your import. This will work too:
import bruhGetMoney from './Helpers';
bruhGetMoney('money');
//I'm liking money

I hope this would be a clearer thing for you. Thanks.

A: Because DateTime is not correctly imported.
import { DateTime } from 'luxon'


text:
Q: Odoo MissingError on Button Click I  have  a  button  in  odoo  and  when  clicked  it  throws an  error  as  shown  in the  image  below  ,  kindly  would i  need  some  assistance  to  make this  work

class ratecard_multiple(models.Model):
    # pudb.set_trace()
    _name = 'ratecard.multiple'
    _rec_name = 'display_name'
    name = fields.Char(string='Multiple RateCard Product  Name ', required=True)
    code = fields.Char(string='Multiple RateCard Code ', readonly=True)
    scheduled_for = fields.Integer(string='SCHEDULED FOR', default=1, track_visibility='always', store=True)
    # scheduled_for  = fields.Integer(string='SCHEDULED FOR',  compute='_compute_scheduled_for',default=1 ,track_visibility='always',store=True)
    min_weeks = fields.Integer(string="MINIMUM NO OF WEEKS", default=1, store=True)
    max_weeks = fields.Integer(string="Maximum NO OF WEEKS", default=1, track_visibility='always', store=True)

    multiple_ratecard_id = fields.Many2many(comodel_name='ratecard.sin.radio',
                                            relation='ratecard_multiple_singular_rel',
                                            column1='ratecard_multiple_id',
                                            column2='ratecard_sin_radio_id',
                                            string='RATECARDS')

class ratecard_sin_radio(models.Model):
    _name = 'ratecard.sin.radio'
    _description = 'RATECARD SINGULAR RADIO  '

    code = fields.Char(string='RADIO SINGULR RATECARD CODE', readonly=True)
    name = fields.Char(string='NAME')
    outlet_id = fields.Many2one(comodel_name='outlet', string='Outlet')
    timeband_id = fields.Many2one(comodel_name='timeband', string='TimeBand')

    def action_four_weeks_schedule_form(self,cr,uid,ids,context):
        order_obj = self.pool.get('ratecard.multiple').browse(cr,uid,ids)[0]
        print  'order_obj.scheduled_for' , order_obj.scheduled_for
        print  'default_code  order_obj.code' ,  order_obj.code
        return {
            'name':_("Four  Week Schedule to Process"),
            'view_mode': 'form',
            'view_id': False,
            'view_type': 'form',
            'res_model': 'four.weeks.schedule',
            'context':{'default_scheduled_for': order_obj.scheduled_for, 'default_code': order_obj.code},
            'type': 'ir.actions.act_window',
            'nodestroy': True,
            'target': 'new',
            'domain': '[]',
            'flags': {'form': {'action_buttons': True}}

    }

In  the  view  of the  ratecard.multiple i  have this
<tree  editable="bottom">
    <group colspan="2"  col="2" >
        <field name="name"/>
         <field name='display_name'/>
        <field name='code'/>
        <field name="validity_date"/>
        <field name="scheduled_for"/>
        <field name="min_weeks"/>
        <field name="max_weeks"/>
        <!--<field name="multiple_ratecard_id_count"/>-->
        <field name="multiple_ratecard_id_count" widget="statinfo"/>

         <!--<field name="allocate_schedule_count"/>-->
         <!--<field name='company_id'/>-->
          </group>
    <field name='multiple_ratecard_id' nolabel="1" options="{'reload_on_button': true}">  <!-- widget="many2many"-->
    <tree  string="ALLOCATE SPOTS" editable="bottom" >
             <button name="action_four_weeks_schedule_form" string="CREATE SCHEDULE" type="object" />

                       <field name="code"/>
                        <field name="name"/>
                        <field name="outlet_id" on_change="onchange_outlet(outlet_id)" placeholder="OUTLET"/>
          </tree>
  </field>
</tree>

In  the  terminal  in debug  mode  this  error  is  thrown
 2015-12-14 09:53:50,615 13824 ERROR ragtimeorder openerp.http: Exception during JSON request handling.
Traceback (most recent call last):
  File "/home/daniel/CRUCIAL/odoo/openerp/http.py", line 537, in _handle_exception
    return super(JsonRequest, self)._handle_exception(exception)
  File "/home/daniel/CRUCIAL/odoo/openerp/http.py", line 574, in dispatch
    result = self._call_function(**self.params)
  File "/home/daniel/CRUCIAL/odoo/openerp/http.py", line 310, in _call_function
    return checked_call(self.db, *args, **kwargs)
  File "/home/daniel/CRUCIAL/odoo/openerp/service/model.py", line 118, in wrapper
    return f(dbname, *args, **kwargs)
  File "/home/daniel/CRUCIAL/odoo/openerp/http.py", line 307, in checked_call
    return self.endpoint(*a, **kw)
  File "/home/daniel/CRUCIAL/odoo/openerp/http.py", line 803, in __call__
    return self.method(*args, **kw)
  File "/home/daniel/CRUCIAL/odoo/openerp/http.py", line 403, in response_wrap
    response = f(*args, **kw)
  File "/home/daniel/CRUCIAL/odoo/addons/web/controllers/main.py", line 948, in call_button
    action = self._call_kw(model, method, args, {})
  File "/home/daniel/CRUCIAL/odoo/addons/web/controllers/main.py", line 936, in _call_kw
    return getattr(request.registry.get(model), method)(request.cr, request.uid, *args, **kwargs)
  File "/home/daniel/CRUCIAL/odoo/openerp/api.py", line 256, in wrapper
    return old_api(self, *args, **kwargs)
  File "/home/daniel/CRUCIAL/rag_modules/ragtimeorder_modules/ragtimeorder/models/ragdefaults.py", line 1055, in action_four_weeks_schedule_form
    print  'order_obj  ' , order_obj
  File "/home/daniel/CRUCIAL/odoo/openerp/fields.py", line 825, in __get__
    return record._cache[self]
  File "/home/daniel/CRUCIAL/odoo/openerp/models.py", line 6024, in __getitem__
    return value.get() if isinstance(value, SpecialValue) else value
  File "/home/daniel/CRUCIAL/odoo/openerp/fields.py", line 55, in get
    raise self.exception
MissingError: ('MissingError', u'One of the documents you are trying to access has been deleted, please try again after refreshing.')

A: This error occurs when you try to search for or access a record id that doesn't exist, i suspect that your problem might be from here
order_obj = self.pool.get('ratecard.multiple').browse(cr,uid,ids)[0]

check the id you pass to the function it probably doesn't exist in the database you can print it out to the console or a log file and then inspect your database with psql and see it it exists.


text:
Q: Where can I find the Templar Dens in Constantinople? Where are the Templar Dens?
Ideally I'd like to have a map of all of them in Constantinople.

A: All of the maps I can find of all of Constantinople seem to be focused on finding the Animus fragments, and not the Templar Dens, unfortunately.
The templar dens are pretty easy to locate, however.  Each one is marked on your map from the start of the game, I believe.  The icon looks a little odd, like a castle with three spires.  (I almost think they look like tiny top-down spaceships, like in Galaga or similar)  They often overlap with the "eagle" viewpoint icon.

If you go into the map's filter options, you can see what each icon represents, and you can toggle off all of them except for the Templar Dens, which should make finding them on the map super easy.  When you're in the area of a Templar Den, you'll know for a number of reasons:

*

*Shop icons are replaced by padlock icons, indicating that you can't buy the shop until you remove the den

*You'll see "castle tower" icons (similar to the rook in chess) which indicate sniper hideouts

*The map area around the den is in red, indicating it is a restricted area.

Here's a screenshot provided by Jeff Mercado and poorly edited by me.  We've cleared the dens, so they show up with a different icon (an Assassin logo) - if you haven't cleared the dens yet, they'll show up like the icon above:


text:
Q: Scroll to position WITHIN a div (not window) using pure JS PURE JS ONLY PLEASE - NO JQUERY
I have a div with overflow scroll, the window (html/body) never overflows itself.
I have a list of anchor links and want to scroll to a position when they're clicked.
Basically just looking for anchor scrolling from within a div, not window.
window.scrollTo etc. don't work as the window never actually overflows.
Simple test case http://codepen.io/mildrenben/pen/RPyzqm
JADE
nav
  a(data-goto="#1") 1
  a(data-goto="#2") 2
  a(data-goto="#3") 3
  a(data-goto="#4") 4
  a(data-goto="#5") 5
  a(data-goto="#6") 6

main
  p(data-id="1") 1
  p(data-id="2") 2
  p(data-id="3") 3
  p(data-id="4") 4
  p(data-id="5") 5
  p(data-id="6") 6

SCSS
html, body {
  width: 100%;
  height: 100%;
  max-height: 100%;
}

main {
  height: 100%;
  max-height: 100%;
  overflow: scroll;
  width: 500px;
}

nav {
  background: red;
  color: white;
  position: fixed;
  width: 50%;
  left: 50%;
}

a {
  color: white;
  cursor: pointer;
  display: block;
  padding: 10px 20px;
  &:hover {
    background: lighten(red, 20%);
  }
}

p {
  width: 400px;
  height: 400px;
  border: solid 2px green;
  padding: 30px;
}

JS
var links = document.querySelectorAll('a'),
    paras = document.querySelectorAll('p'),
    main  = document.querySelector('main');

for (var i = 0; i < links.length; i++) {
  links[i].addEventListener('click', function(){
    var linkID = this.getAttribute('data-goto').slice(1);
    for (var j = 0; j < links.length; j++) {
      if(linkID === paras[j].getAttribute('data-id')) {
         window.scrollTo(0, paras[j].offsetTop);
      }
    }
  })
}

PURE JS ONLY PLEASE - NO JQUERY

A: What you want is to set the scrollTop property on the <main> element.
var nav = document.querySelector('nav'),
    main  = document.querySelector('main');

  nav.addEventListener('click', function(event){
    var linkID,
      scrollTarget;
    if (event.target.tagName.toUpperCase() === "A") {
      linkID = event.target.dataset.goto.slice(1);
      scrollTarget = main.querySelector('[data-id="' + linkID + '"]');
      main.scrollTop = scrollTarget.offsetTop;
    }
  });

You'll notice a couple of other things I did different:

*

*I used event delegation so I only had to attach one event to the nav element which will more efficiently handle clicks on any of the links.

*Likewise, instead of looping through all the p elements, I selected the one I wanted using an attribute selector
This is not only more efficient and scalable, it also produces shorter, easier to maintain code.
This code will just jump to the element, for an animated scroll, you would need to write a function that incrementally updates scrollTop after small delays using setTimeout.
var nav = document.querySelector('nav'),
    main  = document.querySelector('main'),
    scrollElementTo = (function () {
      var timerId;
      return function (scrollWithin, scrollTo, pixelsPerSecond) {
        scrollWithin.scrollTop = scrollWithin.scrollTop || 0;
        var pixelsPerTick = pixelsPerSecond / 100,
          destY = scrollTo.offsetTop,
          direction = scrollWithin.scrollTop < destY ? 1 : -1,
          doTick = function () {
            var distLeft = Math.abs(scrollWithin.scrollTop - destY),
              moveBy = Math.min(pixelsPerTick, distLeft);
            scrollWithin.scrollTop += moveBy * direction;
            if (distLeft > 0) {
              timerId = setTimeout(doTick, 10);
            }
          };
        clearTimeout(timerId);
        doTick();
      };
    }());

nav.addEventListener('click', function(event) {
  var linkID,
    scrollTarget;
  if (event.target.tagName.toUpperCase() === "A") {
    linkID = event.target.dataset.goto.slice(1);
    scrollTarget = main.querySelector('[data-id="' + linkID + '"]');
    scrollElementTo(main, scrollTarget, 500);
  }
});

Another problem you might have with the event delegation is that if the a elements contain child elements and a child element is clicked on, it will be the target of the event instead of the a tag itself. You can work around that with something like the getParentAnchor function I wrote here.

A: I hope I understand the problem correctly now: You have markup that you can't change (as it's generated by some means you have no control over) and want to use JS to add functionality to the generated menu items.
My suggestion would be to add id and href attributes to the targets and menu items respectively, like so:
var links = document.querySelectorAll('a'),
    paras = document.querySelectorAll('p');

for (var i = 0; i < links.length; i++) {
    links[i].href=links[i].getAttribute('data-goto');
}

for (var i = 0; i < paras.length; i++) {
    paras[i].id=paras[i].getAttribute('data-id');
}


text:
Q: hibernate doesnt save entries to postgresql database I had setup hibernate with postgresql by this hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

         <hibernate-configuration>
            <session-factory>
<!-- <property name="connection.url">jdbc:postgresql://localhost:5432/school</property>   -->
<property name="connection.url">jdbc:postgresql://localhost:5432/school</property>
<property name="connection.username">postgres</property>
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="connection.password">root</property>
<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<!-- thread is the short name for
org.hibernate.context.ThreadLocalSessionContext
and let Hibernate bind the session automatically to the thread
-->
<property name="current_session_context_class">thread</property>
<!-- this will show us all sql statements -->
<property name="hibernate.show_sql">true</property>
<!-- mapping files -->
                    <mapping resource="model/Student.hbm.xml" />
                   <mapping resource="model/link.hbm.xml" />
                <mapping resource="model/Course.hbm.xml" />
</session-factory>
</hibernate-configuration>

But I get this error and I cant figure out what the error means...
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)
Caused by: java.sql.BatchUpdateException: Batch entry 0 insert into student (name, id) values ('asdfgh', '4') was aborted.  Call getNextException to see the cause.
    at org.postgresql.jdbc2.AbstractJdbc2Statement$BatchResultHandler.handleError(AbstractJdbc2Statement.java:2619)
    at org.postgresql.core.v3.QueryExecutorImpl$1.handleError(QueryExecutorImpl.java:457)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1835)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:405)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeBatch(AbstractJdbc2Statement.java:2752)
    at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)
    at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:246)
    ... 78 more
name asdfgh
returning
outside
org.hibernate.exception.SQLGrammarException: Could not execute JDBC batch update
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:67)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
    at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:253)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:237)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:141)
    at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
    at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
    at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
    at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
    at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
    at dao.StudentSave.addstudent(StudentSave.java:28)
    at action.ActionClass.adds(ActionClass.java:49)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:453)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:292)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:255)
    at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:176)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:265)
    at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:138)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:211)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:211)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:190)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:90)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:243)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:145)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:176)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:192)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:187)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
    at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:510)
    at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
    at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1001)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)
Caused by: java.sql.BatchUpdateException: Batch entry 0 insert into student (name, id) values ('asdfgh', '4') was aborted.  Call getNextException to see the cause.
    at org.postgresql.jdbc2.AbstractJdbc2Statement$BatchResultHandler.handleError(AbstractJdbc2Statement.java:2619)
    at org.postgresql.core.v3.QueryExecutorImpl$1.handleError(QueryExecutorImpl.java:457)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1835)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:405)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeBatch(AbstractJdbc2Statement.java:2752)
    at or2012-07-16 19:06:26,272 DEBUG org.apache.struts2.dispatcher.ServletDispatcherResult.debug:68 - Forwarding to location result.jsp
2012-07-16 19:06:26,272 DEBUG com.opensymphony.xwork2.conversion.impl.InstantiatingNullHandler.debug:68 - Entering nullPropertyValue [target=[action.ActionClass@44b635, com.opensymphony.xwork2.DefaultTextProvider@1e45e75], property=struts]

Do I have to create a table and columns myself in the database? the code runs perfectly fine usinf mysql database.

A: nevermind
I didnt add the hbm2ddl.auto property to config file. Now this works fine.
<property name="hbm2ddl.auto">update</property>

A: I ran into the same issue with Hibernate 3.4 and Postgres 9.1. The problem was that I was trying to store a text string longer than 255 inside a varchar(255) column. The solution was to change the type of the column to be text.
alter TABLE persistentmessage ALTER COLUMN payload TYPE text;

A: org.hibernate.exception.SQLGrammarException: Could not execute JDBC batch update
insert into student (name, id) values ('asdfgh', '4')
Is id column VARCHAR?
Maybe you can post the java code from where you call the DB?

A: This statement:
insert into student (name, id) values ('asdfgh', '4');

is invalid if id is a numeric column (integer, bigint, serial, or any other numberic datatype)
A number literla must be specified without single quotes:
insert into student (name, id) values ('asdfgh', 4);

MySQL's sloppy data type checking allows for such an error, but PostgreSQL (and other DBMS) doesn't. So you need to change your code to make sure that the literal 4 is passed as a number not a string literal.
If your column is a text/varchar/char column, than it must be something different.