text:
Q: How can I use Mathematica's graph functions to cheat at Boggle? Boggle is a word game played with 16 dice and a 4x4 tray. This question is inspired by a Stack Overflow question about Boggle that I decided to solve using Mathematica. In addition to Mathematica, I thought I'd use some of the new version's graph-related functionality, which I've never really explored in the past. It seemd like a natural fit, but the further I got into my program, the more awkward everything seemed. First, the board from the orginal question:
F X I E
A M L O
E W B X
A S T U

I use a mix of features to turn this into a Graph; with ImportString I was able to copy and past from my browser directly into a string literal in my notebook.
makeBoggleBoard[s_String] :=
 makeBoggleBoard@ImportString[s]

makeBoggleBoard[mat : {{__String} ..}] /; MatrixQ[mat] :=
 With[{dims = Dimensions@mat,
   cPatt = {_Integer, _Integer},
   dPatt = Alternatives[{1, 0}, {0, 1}, {1, -1}, {1, 1}]
   },
  With[{coords = Tuples[Range /@ dims]},
   With[{
     vertexRules =
      Thread[coords -> Thread[{Range@Length@coords, Flatten@mat}]],
     edgePattern = {c1 : cPatt, c2 : cPatt} /; MatchQ[c1 - c2, dPatt]
     },
    Graph@Cases[Tuples[coords, 2],
      c : edgePattern :> ((UndirectedEdge @@ c) /. vertexRules)]]]]

This already seems a little bit clunky. Most of the difficulty comes about from trying to associate a letter with each vertex in my graph while keeping all the vertices distinct. However, this mostly seems to work well.
Also, it will help to winnow the dictionary so it only contains valid words (they must have more than three letters and only use letters on the board). This part, at least, is pretty easy and quick:
makeBoggleDictionary[board_Graph] :=
  With[{chars =
     ToLowerCase@DeleteDuplicates@(VertexList@board)[[All, -1]]},
   DictionaryLookup[chars ~~ chars ~~ chars ~~ (chars ...)]];

Now it's time to traverse the graph, finding all the words along the way. We need to traverse each possible path from each vertex, check to see if the path so far spells a word, and if it does, collect it. In order to keep performance reasonably in hand, we want to cull paths that can't possible spell a word as quickly as possible. Here's the function I came up with:
findWordsInBoggleBoard[graph_Graph, dict : {__String}] :=
 With[{
   makeWord = ToLowerCase@StringJoin[#[[All, 2]]] &,
   lookup =
    Function[pattern,
     Flatten[StringCases[dict,
       StartOfString ~~ pattern ~~ EndOfString]]]
   },
  Module[{extendPaths},
   extendPaths[v_, {}] :=
    With[{adj =
       DeleteCases[VertexList@NeighborhoodGraph[graph, v], v]},
     Join @@ (extendPaths[#, {{v}}] & /@ adj)];
   extendPaths[v_, paths_] :=
    Module[{
      extended = Append[#, v] & /@ paths,
      nexts,
      strings,
      feasible,
      adj = DeleteCases[VertexList@NeighborhoodGraph[graph, v], v]},
     strings = makeWord /@ extended;
     Scan[
      Sow,
      lookup[Alternatives @@ strings]
      ];

     feasible =
      Pick[
       extended,
       Function[string,
         MatchQ[
          Select[lookup[string ~~ __],
           StringLength@# >= 3 &], {__String}]] /@ strings];

     nexts =
      DeleteCases[
       {#, Select[feasible, Function[path, FreeQ[path, #]]]} & /@ adj,
       {{_, _}, {}}];

     extendPaths @@@ nexts
     ];

   Reap[Scan[extendPaths[#, {}] &, VertexList@graph]] /.
    {{Null, {}} -> {}, {Null, {words : {__String}}} :> Union@words}]]

The performance is sort of acceptable (it takes about 3 seconds to find all the words in the sample board), but the entire approach I'm taking here seems very ugly. In particular, the repeated use of NeighborhoodGraph to find adjacent vertices in the recursion for extendPaths seems faintly ridiculous, and the whole approach feels quite low-level compared to some of the other graph functions.
Can anyone suggest some possible ways to speed this up?
EDIT: Part of what I'm interested in seeing is whether Mathematica's graph functions are a good fit for this problem, though of course I'm happy to see the good, fast implementations that people have posted.

A: Preview and comparative results
The implementation below may be not the most "minimal" one, because I don't use any of the built-in functionality (DictionaryLookup with patterns, Graph-related functions, etc), except the core language functions. However, it uses efficient data structures, such as Trie, linked lists, and  hash tables, and arguably maximally avoids the overheads typical in Mathematica programming. The combined use of Trie, linked lists, and recursion allows the main function to copy very little. The use of trie data structure allows me to be completely independent of the system DictionaryLookup function.
Why is this critical here? Because the nature of the problem makes only a single last letter important for the next traversal step, and constructing the whole word (containing all previous letters) just to check that it exists is a waste, and this is arguably the reason why other solutions are both much slower and do not scale so well.
Also, the preprocessing step, while rather costly (takes about 6 seconds on my machine), has to be done only once, to initialize the "boggle engine" (moreover, the resulting trie can be stored in e.g. .mx file for later reuse, avoiding this overhead for subsequent uses), while in other posted solutions some preprocessing has to be done for every particular board.
The main message I want to deliver is that, for the top-level Mathematica code, the choice of efficient data structures is crucial. Our Mathematica programming instincts demand that we reuse as much of the built-in functionality as possible, but one always has to question how well the existing functionality matches the problem. In this particular case, my opinion is that neither the built-in Graph - related functions nor the DictionaryLookup with patterns bring much to the table. To the opposite, these functions force us to use unnatural for this problem data representations and/or algorithms, and this is what leads to the slowdowns. I may be over-emphasizing this point, but this was exactly the essence of the question.
Now, some timing comparisons (note that for the solution of @R.M., I had to include the pieces defining adjnodes, letters and dict variables, into the timing measurements):

*

*Board 4x4 (the original one):

*

*Pillsy   3.3 sec

*R.M.     1.4 sec

*L.S.     0.04 sec

*Board  5x5:
"E I S H R
 B D O I O
 T R O E X
 Z U Y Q S
 I A S U M"

*

*Pillsy   18.8 sec

*R.M.     7.6  sec

*L.S.     0.05 sec

*Board 7x7
"E I E G E O T
 A O B A U R A
 N E I P L A Y
 O O I I C A T
 I I F U N L A
 S T I N G E W
 U H L E O X S"

*

*Pillsy   373.8 sec

*R.M.     191.5 sec

*L.S.     0.18 sec

So, you can see that for larger boards, the difference between the running times is even more dramatic, hinting that the solutions have different computational complexities.
I took the trouble to perform and present all these timings because I think that this problem  is an important counterexample to the "conventional wisdom" to favor shorter implementations utilizing built-ins over the hand-written top-level mma code. While I agree that in general this is a good strategy, one has to always examine the case at hand. To my mind, this problem presents one notable exception to this rule.
Implementation
The following solution will not use Mathematica graphs, but will be about 100 times faster (than the timings you cite), and will rely on this post. I will borrow a function which builds the word tree from there:
ClearAll[makeTree];
makeTree[wrds : {__String}] := makeTree[Characters[wrds]];
makeTree[wrds_ /; MemberQ[wrds, {}]] :=
     Prepend[makeTree[DeleteCases[wrds, {}]], {} -> {}];
makeTree[wrds_] :=
    Reap[If[# =!= {}, Sow[Rest[#], First@#]] & /@
       wrds, _, #1 -> makeTree[#2] &][[2]]

Its use is detailed in the mentioned post. Now, here is a helper function which will produce rules for vertex number to letter conversion, and adjacency rules:
Clear[getLetterAndAdjacencyRules];
getLetterAndAdjacencyRules[letterMatrix_?(MatrixQ[#, StringQ] &)] :=
  Module[{a, lrules, p, adjRules},
    lrules = Thread[Range[Length[#]] -> #] &@Flatten[letterMatrix];
    p =
      ArrayPad[
          Partition[Array[a, Length[lrules]], Last@Dimensions@letterMatrix],
          1
      ];
    adjRules =
      Flatten[
       ListConvolve[{{1, 1, 1}, {1, 2, 1}, {1, 1, 1}}, p] /. Plus -> List /.
         {left___, 2*v_, right___} :> {v -> {left, right}} /. a[x_] :> x];
    Map[Dispatch, {lrules, adjRules}]
  ];

It is pretty ugly but it does the job. Next comes the main function, which will find all vertex sequences which result in valid dictionary words:
EDIT
Apparently, there is a problem with Module-generated inner functions. I used Module in getVertexSequences initially, but, because in my benchmarks I happened to use a previous incarnation of it with a different name (where I did not yet modularize the inner functions), I did not see the difference. The difference is an order of magnitude slow-down. Therefore, I switched to Block, to get back the performance I claimed (You can replace back the Block with Module to observe the effect). This is likely related to this issue, and is something anyone should be aware of IMO, since this is quite insidious.
END EDIT
Clear[getVertexSequences];
getVertexSequences[adjrules_, letterRules_, allTree_, n_] :=
Block[{subF, f, getWordsForStartingVertex},
  (* A function to extract a sub-tree *)
  subF[v_, tree_] :=
    With[{letter = v /. letterRules},
      With[{res = letter /. tree},
        res /; res =!= letter]];
  subF[_, _] := {};
  (* Main function to do the recursive traversal *)
  f[vvlist_, {{} -> {}, rest___}] := f[Sow[vvlist], {rest}];
  f[_, {}] := Null;
  f[vvlist : {last_, prev_List}, subTree_] :=
     Scan[
       f[{#, vvlist}, subF[#, subTree]] &,
       Complement[last /. adjrules, Flatten[vvlist]]
     ];
  (* Function to post-process the result *)
  getWordsForStartingVertex[v_] :=
    If[# === {},
       #,
       Reverse[Map[Flatten, First@#], 2]
    ] &@Reap[f[{v, {}}, subF[v, allTree]]][[2]];
  (* Call the function on every vertex *)
  Flatten[Map[getWordsForStartingVertex, Range[n]], 1]
]

At the heart of it, there is a recursive function f, which acts very simply. The vvlist variable is a linked list of already visited vertices. The second argument is a sub-tree of the main word tree, which corresponds to the sequence of already visited vertices (converted to letters. To understand better what the sub-tree is, see the mentioned post). When the sub-tree starts with {} -> {}, this means (by the way word tree is constructed), that the sequence of vertices corresponds to a valid word, so we record it. In any case, if the subtree is not {}, we Scan our function recursively on adjacent vertices, removing from them those we already visited.
The final functions we need are the one to convert vertex sequences to words, and the one to construct the trie data structure. Here  they are:
Clear[wordsFromVertexSequences];
wordsFromVertexSequences[vseqs_List, letterRules_] :=
   Map[StringJoin, vseqs /. letterRules];

ClearAll[getWordTree];
getWordTree[minLen_Integer: 1, maxLen : (_Integer | Infinity) : Infinity] :=
  makeTree[
     Select[ToLowerCase@DictionaryLookup["*"],
     minLen <= StringLength[#] <= maxLen &]];

The function to bring this all together:
ClearAll[getWords];
getWords[board_String, wordTree_] :=
   getWords[ToLowerCase@ImportString@board, wordTree];
getWords[lboard_, wordTree_] :=
   Module[{lrules, adjrules},
   {lrules, adjrules} = getLetterAndAdjacencyRules[lboard ];
   wordsFromVertexSequences[
       getVertexSequences[adjrules, lrules, wordTree,
          Times @@ Dimensions[lboard]],
       lrules
   ]
];

Illustration
First, construct a full tree of all words in a dictionary. This preprocessing step can take a little while:
largeTree = getWordTree[];

Now, construct the word matrix:
wmat = ToLowerCase@ImportString@
  "F X I E
   A M L O
   E W B X
   A S T U"

{{"f", "x", "i", "e"}, {"a", "m", "l", "o"}, {"e", "w", "b","x"},
         {"a", "s", "t", "u"}}

Next, construct the rules for vertex-to-letter conversion and adjacency rules:
({lrules,adjrules} = getLetterAndAdjacencyRules[wmat])//Short[#,3]&

{Dispatch[{1->f,2->x,3->i,4->e,5->a,6->m,7->l,8->o,9->e,10->w,11->b,
  12->x,13->a,14->s,15->t,16->u},-DispatchTables-],
    Dispatch[{1->{2,5,6},<<14>>,16->{11,12,15}},<<1>>]}

We are now ready to use our function:
(seqs = getVertexSequences[adjrules,lrules,largeTree,16])//Short//AbsoluteTiming

{0.0185547,{{1,5},{1,5,2},{1,5,6,9},{1,6},<<89>>,{15,14},
     {15,16,11},{15,16,11,14},{15,16,12}}}

Note that it took very little time to get the result. We can finally convert it to words:
wordsFromVertexSequences[seqs,lrules]//Short

{fa,fax,fame,fm,xi,xml,xl,<<84>>,twas,tb,ts,tub,tubs,tux}

The way to call a final function:
(* Do this only once per session *)
$largeTree = getWordTree[3];

board = ToLowerCase@ImportString@"F X I E
  A M L O
  E W B X
  A S T U"

getWords[board, $largeTree]

{fax,fame,xml,imf,eli,elm,elma,<<59>>,stub,twa,twa,twas,tub,tubs,tux}

(note that the result differs from that in illustration section, since I am now using the word tree with words with less than 3 letters excluded - using the $largeTree rather than largeTree now).
Discussion
Of course, I was a bit cheating in the sense that the preprocessing time takes a while, but this has to be done only once. My main point is that I think, the Trie data structure (my interpretation of it) is the right one here, and coupled with linked lists and hash tables (Dispatch-ed rules), it leads to a rather simple solution. The essence of the solution is expressed in function f, which is just a few lines long and more or less self-documenting. And, also, the solution itself turns out quite fast (especially given that this uses just the top-level mma, no packed arrays, Compile, etc).
EDIT 2
To address the question in your edit, and generally the question on applicability of Mathematica's new Graph functionality to this problem: I think, that while you can use new Graphs to solve the problem, it is not a natural choice here. I may be wrong, of course, but these are my reasons:

*

*The graph traversal you need for this problem does not fit directly into either one of DepthFirstScan and BreadthFirstScan built-in graph-traversal functions. Rather, it is a kind of enumeration of all possible depth-first traversals starting at a given vertex.

*Those traversals should stop as soon as it becomes clear that no words can be constructed by going to any of the adjacent vertices. This can be also achieved in DepthFirstScan through the use of Catch and Throw, but it is rather inelegant, and will also induce an overhead.

*The general ideology of DepthFirstScan and BreadthFirstScan is somewhat similar to a visitor design pattern used for a tree traversal. The idea is that the traversal is done for you, while you have to supply the functions to be called on tree (or graph) nodes. This approach works well when your traversal matches exactly the one implemented by the pattern. For example, most of the time, a tree is traversed depth-first. However, I had many chances to observe (in other languages) that as soon as I have to modify the traversal even slightly, using the tools like that creates more problems than it solves.
The main question to ask yourself is this: does you traversal (sequence of visited vertices) depend on the content of the vertices (information you get during the traversal)? If yes, then it is more than likely that custom general traversal functions will not give you a good solution, because you then need more control over the way traversal is performed. The whole idea of visitor pattern (used for tree traversals) and the like is that you can separate the traversal itself from the information-processing during the traversal, and it's just not true for data-dependent traversals, where you can not really decouple traversal from the data-processing of the tree (or graph) nodes.
I think that we should separate cases where graphs represent just a useful abstraction to think about the problem, from those where the problem can be solved by means of more or less standard graph-theoretical functionality (in particular that present in Mathematica), once it is reformulated in an appropriate way. The case at hand clearly looks to me like belonging to the first category.

A: My solution is a recursive tree traversal algorithm which seeks and searches neighbouring vertices only if it will lead to a word (e.g., Something starting with ZQ is immediately disqualified), but it's faster than yours because I construct the adjacent vertices list from the adjacency matrix rather than calling NeighborhoodGraph each time. On my machine, yours runs in about 8 s, and mine in under 1 s. Here's the final prettified output that you can use to cheat at boggle :)

Implementation
1. Construct the adjacency matrix for a generic boggle grid.
Boggle grids are square. The adjacency matrix has a nice structure to it, which allows you to construct it neatly for any $n\times n$ grid. Here's the function to create it:
boggleAdjMatrix[n_] := Module[{grid, diag, patt, eye},
  grid = SparseArray[{Band[{1, 1}] -> patt, Band[{2, 1}] -> eye,
      Band[{1, 2}] -> eye}, {n, n}] // Normal;
  diag = SparseArray[{Band[{2, 1}] -> patt, Band[{1, 2}] -> patt}, {n, n}] // Normal;

  patt = SparseArray[{Band[{2, 1}] -> 1, Band[{1, 2}] -> 1}, {n, n}] // Normal;
  eye = IdentityMatrix[n];

  ArrayFlatten[grid + diag] // Unitize
]

Now for the above board of letters, you can create the graph from the adjacency matrix, and simply label the vertices (s is the string in your first code block, just copy-pasted):
With[{letters = StringSplit[s]},
    AdjacencyGraph[boggleAdjMatrix[Sqrt[Length@letters]],
    VertexLabels -> Table[i -> letters[[i]], {i, Length@letters}]]
]

You can also get the matrix from your approach by calling AdjacencyMatrix[graph], but I find this easier to follow.
2. Create helper functions and neighbourhood list
I create some helper functions to create a smaller dictionary of valid words, to check if a word is in that dictionary, to test whether a given path could ever lead to a word, and to sow a word that is legal
Clear[dictionary, wordQ, proceedQ, sowWord]
dictionary[list_List] := With[{chars = DeleteDuplicates@list},
   DictionaryLookup[x : chars ... /; StringLength[x] >= 3, IgnoreCase -> True]];

wordQ[dict_List, word_String] /; StringLength[word] >= 3 := Or @@ StringMatchQ[dict, word]
proceedQ[dict_List, word_String] := Or @@ StringMatchQ[dict, word ~~ ___]
sowWord[dict_List, s_String] /; StringLength[s] >= 3 := Sow[s] /; wordQ[dict, s]

For the adjacent nodes, instead of using NeighborhoodGraph repeatedly, I create a list of adjacent nodes, which you can easily get from the adjacency matrix:
adjNodes = With[{list = First /@ ArrayRules[boggleAdjMatrix[4]] // Most},
    Map[Last, SplitBy[list, First], {2}]]

3. Traverse the graph and find dictionary words
Now you can simply index the $i$th element to get the neighbours. For example, adjNodes[[10]] gives you {5, 6, 7, 9, 11, 13, 14, 15}.
With the above, we're all set to find the words. First a couple of initializations:
letters = {"F", "X", "I", "E", "A", "M", "L", "O", "E", "W", "B", "X", "A", "S", "T", "U"};
dict = ToUpperCase@dictionary[letters];
currentWord[visited_List] := StringJoin @@ letters[[visited]];

The following is the main function that traverses the graph starting from a given vertex. It moves forward only if the word in the current path could ever lead to a word at a future node.
Clear[stepForward]
stepForward[current_, visited_: {}] := Module[{$visited, $currentWord},
    With[{$possibleNodes = DeleteCases[adjNodes[[current]], Alternatives @@ visited]},
       $visited = Append[visited, current];
       $currentWord = currentWord[$visited];
       sowWord[dict, $currentWord];
       stepForward[#, $visited] & /@ $possibleNodes /; proceedQ[dict, $currentWord]
    ]
]

And finally, run it on the entire graph:
wordsFromVertex[v_] := stepForward[v] // Reap // Last
wordsFromVertex /@ Range[16]

(* {"FAX", "FAME", "XML", "IMF", "ELI", "ELM", "ELMA", "AXLE", "AMIE",
    "AMBLE", "AWL", "AWE", "AWES", "MIX", "MIL", "MILE", "MILO", "MAX",
    "MAXI", "MAE", "MAW", "MAWS", "MEW", "MEWL", "MEWS", "MES", "MESA",
    "LIE", "LIMA", "LIME", "LIMES", "LIMB", "LIMBO", "LIMBS", "LEI",
    "LEO", "LOB", "LOBS", "LOX", "OIL", "OLE", "EMIL", "EMILE", "EAST",
    "WAX", "WEST", "WAS", "WAST", "BMW", "BOIL", "BOLE", "BOX", "BUT",
    "BUTS", "AWL", "AWE", "AWES", "SEA", "SEAM", "SEMI", "SEW", "SEA",
    "SWAM", "SWAMI", "SAW", "STU", "STUB", "TWA", "TWA", "TWAS", "TUB",
    "TUBS", "TUX"} *)

Presentation and solution viewer
This part assembles the bogle board and tiles neatly and provides an interactive viewer with which you can move backward and forward to view the solutions and the path that leads to them.
First a couple of slightly modified helper functions:
Clear[sowPath, stepForward2]
sowPath[dict_List, s_String, visited_] /; StringLength[s] >= 3 :=
    Sow[visited] /; wordQ[dict, s]

stepForward2[current_, visited_: {}] := Module[{$visited, $currentWord},
    With[{$possibleNodes = DeleteCases[adjNodes[[current]], Alternatives @@ visited]},
        $visited = Append[visited, current];
        $currentWord = currentWord[$visited];
        sowPath[dict, $currentWord, $visited];
        stepForward2[#, $visited] & /@ $possibleNodes /; proceedQ[dict, $currentWord]
    ]
]

Here's the main function that pretty-prints the boggle board:
With[{coords = (Table[{j, i}, {i, 4}, {j, 4}]~Flatten~1),
    paths = (stepForward2 /@ Range[16] // Reap // Last)~Flatten~1,
    adjMat = boggleAdjMatrix[Sqrt[Length@letters]]},

    Module[{g, vertexFun, edgeFun, list = N@coords[[paths[[#]]]] &},
        vertexFun[v_] := If[MemberQ[list[v], #],
            {LightGreen, EdgeForm[{Thick, Darker@Green}],
                Rectangle[# - 1/2, # + 1/2, RoundingRadius -> .1], Black,
                Text[Style[letters[[#2]], FontSize -> 16], #1]},
            {LightYellow, EdgeForm[{Thick, Darker@Yellow}],
                Rectangle[# - 1/2, # + 1/2, RoundingRadius -> .1], Black,
                Text[Style[letters[[#2]], FontSize -> 16], #1]}
        ] &;

        edgeFun[v_] := {Red, Thick, Arrow[#, 1/4] & /@ Partition[list[v], 2, 1]};

        g[v_] := AdjacencyGraph[adjMat, VertexCoordinates -> coords, Background -> White,
            VertexShapeFunction -> vertexFun[v], EdgeStyle -> Opacity[0],
            ImageSize -> 300, Epilog -> First@Graphics[edgeFun[v]]];

        Panel@DynamicModule[{i = 1},
            Column[{
                Dynamic@
                    Row[{Button["Previous", i -= 1, Enabled -> (i > 1)],
                        Button["Next", i += 1, Enabled -> (i < Length[paths])]}],
                Dynamic@Labeled[g@i, Style[Text@currentWord@paths[[i]], FontSize -> 14], Top]
            }]
        ]
    ]
]


text:
Q: Odoo - one2many relation - updating fields on child table I have a main model with a one2many field, linked to a secondary model, which also has a one2many field, linked to a third model.
How can I update values on the third model using onchange event of a field on the main model?
This is a short version of the question:
ODOO - How to update two levels o2m fileds relation

redpajama_set_name: RedPajamaStackExchange


text:
Q: Svn2Git rebase returns error 'too many arguments' I managed to migrate a repository from SVN to GitLab via svn2git a couple days ago as a test.
I used svn2git because I needed a one way/cut over migration.
There have been some new commits on SVN (the Git repo remains untouched) since and I'm trying to update the resulting Git repository using svn2git {REPO URL} --rebase but it returns Error starting script: Too many arguments
I'd just like to know what might cause this error and how to avoid it and successfully update the Git repo without changing anything in the SVN repo.
I'm on Debian.

A: The svn2git script says:
    def initialize(args)
      @options = parse(args)
      if @options[:rebase]
         show_help_message('Too many arguments') if args.size > 0
         verify_working_tree_is_clean

So if you passed any parameters to a svn2git --rebase call, you would get that error.
A repository update should be:

As of svn2git 2.0 there is a new feature to pull in the latest changes from SVN into your git repository created with svn2git.
This is a one way sync, but allows you to use svn2git as a mirroring tool for your SVN repositories.
The command to call is:
$ cd <EXISTING_REPO> && svn2git --rebase


text:
Q: Math columns in tabularray The package tabularray seems like a good start, but the documentation is really sparse. Is there a way to add math columns? Like X[$] in tabu or \newcolumntype{C}{>{$}c<{$}}in array.

A: Since version 2021P, tabularray package has $ and $$ options for cells/rows/columns.
\documentclass{article}

\usepackage{amsmath}
\usepackage{tabularray}

\begin{document}

\begin{tblr}{colspec={lQ[c,$]Q[r,$$]},hlines}
  text & \frac{1}{2} & -\frac{3}{4} \\
  text & \frac{5}{6} & -\frac{7}{8}
\end{tblr}

\end{document}

A: \documentclass{article}
\usepackage{tabularray}
\NewColumnType{C}{>{$}c<{$}}
\begin{document}

\begin{table}[h]
    \caption{Table caption}
    \begin{tblr}{colspec={l>{$}c<{$}}}
    text & \alpha
    \end{tblr}
\end{table}

\begin{table}[h]
    \caption{Table caption}
    \begin{tblr}{colspec={lC}}
    text & \alpha
    \end{tblr}
\end{table}
\end{document}


text:
Q: Date picker in Magento product custom option gives only date. Need date and time I add a custom option for my product.
Input type for custom option is Date & Time.
To avoid dropdown and display date picker in product page I change:
Use JavaScript Calendar  to "yes" in System > Configuration > Catalog > Catalog > Date&Time Custom Options >
But the datepicker gives date only not time. I need date and time.The drop down box for select time is still shown. I want avoid this dropdown.
Is there any way to give the datepicker both date and time.

Magento version 1.9.0.1

A: Set input type for custom option to Date.
And in app/code/core/Mage/Core/Block/Html/Date.php file change the code as below
var calendarSetupObject = {
                inputField  : "' . $this->getId() . '",
                ifFormat: "%Y-%m-%e %H:%M:%S", //changed line
                showsTime: true,               //changed line
                button      : "' . $this->getId() . '_trig",
                align       : "Bl",
                singleClick : true,

Now we can select both date and time from the date picker and can avoid the drop down for time.


text:
Q: Preview Handlers (Office 2007, Vista & Win7) - issue w/ reisize Greetings,
I'm working on a preview handler for Office 2007, Vista and Windows 7. I'm basing my code off the following
MSDN article.
The "guts" are done as it was pretty straight forward. I've been testing in Windows 7 (64-bit) Explorer. One thing I've noticed is the preview handler appears to "lock" the Explorer window and doesn't allow it to resize.
My handler derives from FileBasedPreviewHandler, the Control from FileBasedPreviewHandlerControl. The #Load override simply does:
MyViewer viewer = new MyViewer();
viewer.Dock = DockStyle.Fill;
viewer.SetFile( file.FullName );
Controls.Add( viewer );

A couple things I've tried, a variety of times is to set, in the design view, the AutoSize and AutoSizeMode to true and GrowAndShrink
Now, the funny thing, i swear it worked once. Now, I can't get it to work at all.
If anyone has any input, that would be great. I think I posted all the relevant info, but if I missed something vital, let me know. I appreciate your attention to this question.
-Cheers!

A: Apparently, by setting the AutoSize and AutoSizeMode as state above, does work. Explorer is simply temperamental.  What I found was if you get strange behavior, you can use task manager to close the explorer process than relaunch it.
For the record, what I found works 99% of the time is to to:

*

*make sure all Explorer windows areclosed (w/ preview panel off)

*unregasm/remove from ga

*build

*add to gac/regasm

*run Explorer and check preview panel

*rinse & repeat

I'm also using a throw-away win forms app to test changes that don't involve the integration.
Hope this helps someone looking.
-Cheers!


text:
Q: mimick google results buttons, can that be done via jquery? when your signed into google, and you search for anything you get the result back.
you then have these buttons where you can bump the result up/down, or even delete it.
when you delete a result, it disappears and then you get this animated image of a cloud that disappears.
How do they inject that image before it disappears?
(BTW, I want to see that image, how can I find out the url to that image?)

A: Developer tools of any decent browser(Chrome, Firefox, Opera, Internet Explorer 8) are able to show you a detailed view of all HTTP requests.
http://www.google.com/images/swxa.png

A: Seems to me you could click the button, the entry would be replaced with a cloud-exploding gif, and then the result would be hidden. Maybe the id of that result would be associated with a "dont-show" list which itself is associated with your ipaddress/userid/session.
# Just an idea - untested
$(".result .deleteButton").click(function(){
  $(this)
    .parent()
    .html($(".cloud").clone())
    .fadeOut();
});


text:
Q: php5-sqlite shows me nothing The following code should display a message but shows me nothing (neither on the screen, nor in the source code). Any idea why this may be?
<?php
   try
   {
      //create or open the database
      $database = new SQLiteDatabase('myDatabase.sqlite', 0666, $error);
      echo 'that works';
   }
   catch(Exception $e)
   {
      die('that doesnt: '.$error);
   }

I'm using:

*

*Ubuntu 11.10

*PHP 5.3.6-13ubuntu3.6 with Suhosin-Patch (cli) (built: Feb 11 2012
02:17:16)

phpinfo() shows me the following:

*

*...

*Additional .ini files parsed: ...
/etc/php5/apache2/conf.d/pdo_sqlite.ini,
/etc/php5/apache2/conf.d/sqlite.ini, ...

*PDO drivers  mysql, sqlite

*SQLite Library   3.7.7

*...

SQLite was installed that way:
sudo apt-get install php5-sqlite

A: SQLiteDatabase is not a valid class name, at least not in this extension.
You're looking for Sqlite3:
$db = new Sqlite3('myDatabase.sqlite');

Since the class is undefined, it's provoking a fatal error, and you probably don't see anything because of either your error_reporting level or display_errors setting.


text:
Q: Query for Number of Messages in Mule ESB VM Queue In a Mule flow, I would like to add an Exception Handler that forwards messages to a "retry queue" when there is an exception. However, I don't want this retry logic to run automatically. Instead, I'd rather receive a notification so I can review the errors and then decide whether to retry all messages in the queue or not.
I don't want to receive a notification for every exception. I'd rather have a scheduled job that runs every 15 minutes and checks to see if there are messages in this retry queue and then only send the notification if there are.
Is there any way to determine how many messages are currently in a persistent VM queue?

A: Assuming you use the default VM queue persistence mechanism and that the VM connector is named vmConnector, you can do this:
final String queueName = "retryQueue";
int messageCount = 0;

final VMConnector vmConnector = (VMConnector) muleContext.getRegistry()
    .lookupConnector("vmConnector");

for (final Serializable key : vmConnector.getQueueProfile().getObjectStore().allKeys())
{
    final QueueKey queueKey = (QueueKey) key;
    if (queueName.equals(queueKey.queueName))
    {
        messageCount++;
    }
}

System.out.printf("Queue %s has %d pending messages%n", queueName, messageCount);


text:
Q: How to create a custom distribution strategy on Tensorflow I', looking to write a custom distribution strategy for tensorflow.
Currently there are several types strategies available (MirroredStrategy,   TPUStrategy, ...), but i would like to implement a new way of distributing training across several machines.
I looked through the documentation and didn't find any tutorial or guide on how to implement a custom strategy
Is there already a predefined way to do this?


text:
Q: Same style for input submit control as @html.ActionLink I am looking to obtain the same style for both @html.ActionLink & a input submot control (both buttons) on a form. I basically want the input control to look the same the ActionLink control.

       @Html.ActionLink("RSVP Now", "RsvpForm")

   <input type="submit" value="Update RSVP" />

I want the bottom button to look the above button
(btn btn-sucess is from the bootstrap library)

A:

    <input class="btn btn-success" type="submit" value="Update RSVP" />

A: Provide the class inside the HTML Attributes parameter of the Html.ActionLink Method.

       @Html.ActionLink("RSVP Now", "RsvpForm", new{@class="btn btn-success"})


text:
Q: Linking .lib and .h files (OpenJDK 1.8) I have a project, that includes jni.h and jvmti.h files
here
theese files are stored in jdk8 folder (already installed on my pc)
here
but the main problem - i dont know how can i correctly link jdk libs and .h files to my visual studio prj

A: I suggest you could follow the following steps to link the static library:
1,Add the path to the header file to the Additional Include Directories(property - >c/c++ -> General -> Additional Include Directories)
2,Add the path to the .lib file to the Additional Library Directories (property -> linker -> General -> Additional Library Directories)
3,Add the name of the .lib file with its extension to Additional Dependencies (property -> linker -> input -> Additional Dependencies)


text:
Q: How to save files via django serializers after processing them in my views? I have a excel/csv file that I read using pandas once the user uploads the file. I process the file in my views.py and save them directly using the command df.to_excel("filename.xlsx") or df.to_csv("filename.csv")
Is there a way to save the files through django serializer?
I've tried df.to_excel("filename.xlsx") directly on the serializer data as shown on the code, but the file ends up writing to my disk directly instead of being saved via the serializer.
data = {
            'file': df_template.to_excel(output_file_name, index=False),
            'created_for': project.id,
        }

outputrecord_serializer = OutputRecordSerializer(data=data)

if outputrecord_serializer.is_valid():
     #print('Check if serializer is valid')
     outputrecord_serializer.save()
     #print('saved')
else:
     print(outputrecord_serializer.errors)


text:
Q: detecting closest line to a object in Action Script 3 I created a shape. It will be a room.
here is the code:
        room = new Sprite();
        room.graphics.beginFill(0xFFFF00, 1);
        room.graphics.moveTo(0, 0);
        room.graphics.lineTo(0, 500);
        room.graphics.lineTo(500, 500);
        room.graphics.lineTo(500, 250);
        room.graphics.lineTo(300, 250);
        room.graphics.lineTo(300, 0);
        room.graphics.endFill();
        addChild(room);

and i have a red rectangle at the middle. I wanna know which wall and two point is close to this rectangle. For example: in this screenshot left wall is nearest.
Thank you

A: This is not an actionscript question at all. You need just an algorithm.
Simple solution: find center of the object and then use any line distance algorithm you can find to check this center point distance to all room edges.
For example this: Shortest distance between a point and a line segment


text:
Q: swift fatal error: unexpectedly found nil while unwrapping an Optional value(lldb)from email -in my code? This is my code here found the fatal error.i try to solve this problem but lot of times it shows,and it shows the EXC_BAD_INSTRUCTION(code=EXC_i386_INVOP,subcode=0*0)
import UIKit
class VerifyProfileViewController: UIViewController,UITextFieldDelegate,FBLoginViewDelegate {
    var liveurl = demo_url

    @IBOutlet weak var f_name: UITextField!
    @IBOutlet weak var l_name: UITextField!
    @IBOutlet weak var email_id: UITextField!
    @IBOutlet weak var mobilenumber: UITextField!
    @IBOutlet weak var myLabel: UILabel!
    @IBOutlet weak var nextOutlet: UIButton!
    override func viewDidLoad() {
        super.viewDidLoad()

        // NSUserDefaults.standardUserDefaults().synchronize()
        var mobile_Number = mobilenumber.text
        var email_Address = email_id.text
        var first_name = f_name.text
        var last_name = l_name.text
        var email1 = isValidEmail(email_Address)
        let email = NSUserDefaults.standardUserDefaults().objectForKey("fb_email") as NSString
        println("The email :\(email)")
        let first_name = NSUserDefaults.standardUserDefaults().objectForKey("fb_name") as NSString
        println("The firstname :\(first_name)")

        let last_name = NSUserDefaults.standardUserDefaults().objectForKey("fb_lname") as NSString
        println("The firstname :\(last_name)")
        //NSUserDefaults.standardUserDefaults().setObject(facebookid, forKey:"id")
        //let facebook_id = NSUserDefaults.standardUserDefaults().objectForKey("fb_id")! as NSString
        //println("The fbID :\(facebook_id)")
        email_id.text = email
        f_name.text = first_name
        l_name.text = last_name

A: NSUserDefaults.standardUserDefaults().setValue("abc@def.com", forKey: "fb_email")
if let email = NSUserDefaults.standardUserDefaults().stringForKey("fb_email") {
    println(email)
}


text:
Q: is it possible to pad a numpy array with a tuple? I'm trying to pad a numpy array with a tuple (the array itself has only tuples)...all I can find is padding an array with 0s or 1s, which I can get to work, but that doesn't help me. Is it possible to pad with a tuple?
The crucial line is :
cells = np.pad(cells, pad_width=1, mode='constant', constant_values=material)

Replacing material, which is a 4-tuple, with a 0 works fine...but I really need it to be a tuple.
I get the error message:

operands could not be broadcast together with remapped shapes [original->remapped]: (4,)  and requested shape (2,2)

Here is the code I am using, but using 0s and 1s instead:
import numpy as np
side_len = 3
a = [1 for x in range(9)]
a = np.array(a)
a = a.reshape(side_len,side_len)
a = np.pad(a, pad_width=1, mode='constant', constant_values=0)

The goal is instead of a list of 1s, to pass a list of tuples, and instead of a constant_values=0, to have constant_values=material, where material is an arbitrary 4-tuple.
A flat list of tuples are passed to this function (the function is not shown here), eg:
[(0, 0, 255, 255), (0, 0, 255, 255), (0, 0, 255, 255), (0, 0, 255, 255), (0, 0, 255, 255), (0, 0, 255, 255), (0, 0, 255, 255), (0, 0, 255, 255), (0, 0, 255, 255)]

Which I convert to a numpy array using:
cells = np.array(cells, dtype='i,i,i,i').reshape(side_len,side_len)

Perhaps this is wonky, but the rest of my program just uses lists, I don't need numpy for it; but for this padding issue, I originally was manually iterating over my flat list and doing the padding, which took forever as the list grew, so I thought I'd try numpy because it might be faster.

A: the solution was:
import numpy as np
side_len = 3
material = (0,0,0,255)
a = [(255,0,0,255) for x in range(9)]
a = np.array(a,dtype='i,i,i,i').reshape(side_len,side_len)
_material = np.array(material,dtype='i,i,i,i')
a = np.pad(a, pad_width=1, mode='constant', constant_values=_material)
a
array([[(  0, 0, 0, 255), (  0, 0, 0, 255), (  0, 0, 0, 255),
        (  0, 0, 0, 255), (  0, 0, 0, 255)],
       [(  0, 0, 0, 255), (255, 0, 0, 255), (255, 0, 0, 255),
        (255, 0, 0, 255), (  0, 0, 0, 255)],
       [(  0, 0, 0, 255), (255, 0, 0, 255), (255, 0, 0, 255),
        (255, 0, 0, 255), (  0, 0, 0, 255)],
       [(  0, 0, 0, 255), (255, 0, 0, 255), (255, 0, 0, 255),
        (255, 0, 0, 255), (  0, 0, 0, 255)],
       [(  0, 0, 0, 255), (  0, 0, 0, 255), (  0, 0, 0, 255),
        (  0, 0, 0, 255), (  0, 0, 0, 255)]],
      dtype=[('f0', '<i4'), ('f1', '<i4'), ('f2', '<i4'), ('f3', '<i4')])


text:
Q: How to use Public Shared Sub to call functionality found in a Protected Sub goToRequestedPage() in Visual Basic Here is my issue:
I have used the Javascript #Next 'on click' function to call the Public Shared Sub NextPage() method and also render my bookviewer in the "If-else" statement.
However, I now need the Public Shared Sub NextPage() method to call Protected Sub goToRequestedPage(). I know that I have to call another Public Shared Sub so I need to do something here to retrieve from the goToRequestedPage() method. Below is the goToRequestedPage() method I would like the 'Public Shared Sub' to call (or at least perform the statements within it).
AutoSaveCheckBox, Label1, and Response, all state the following error:"Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class."
As you can see, I would like a message box to pop up, asking the user to save, on top of allowing the user to go to the next page. The user is able to go to the next page, but how can I implement the goToRequestPage() method, or at least get my msgbox process to compile?
//Here is the Javascript 'on click' function for my next button:

$("#Next").click(function () {
                //PageMethods.NextPage(gbpageno)
                $.ajax({
                    type: "POST",
                    url: "WebForm1.aspx/NextPage",
                    async: true,
                    data: "{'page':'" + gbPageNo + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function () { },
                    error: function () { }
                });

                if (splitType == "v") {
                    RenderBR('#CenterLeft', gbPageNo + 1);
                }
                else {
                    RenderBR('#CenterTop', gbPageNo + 1);
                }
            });

//Here is the Public Shared Sub NextPage() method:

<System.Web.Services.WebMethod()> Public Shared Sub NextPage(ByVal page As Integer, ByVal textboxData As String)
        goToRequestedPage()
End Sub

//Here is the goToRequestedPage() method I would like to call from Public Shared Sub       //NextPage(), or at least retrieve all functionality within it (Originally, this was //Protected Sub goToRequestedPage()):
Public Shared Sub goToRequestedPage()
        ' Declare Variables:
        ' Declare TransTableAdapter
        Dim TransAdapter As New EOL_DataSetTableAdapters.TransTableAdapter
        ' Declare previous page save confirmation
        Dim previousPageSaveConfirmation As MsgBoxResult
        ' Declare next page save confirmation
        Dim nextPageSaveConfirmation As MsgBoxResult
        ' Declare autosave checkbox status as Boolean value
        Dim autoSaveCheckBoxStatus As Boolean
        ' Declare page link as String
        Dim pgLink As String

        ' If autosave checkbox is CHECKED...
        If AutoSaveCheckBox.Checked = True Then
            ' Save (Either Insert or Update) Transcription and go to next page
            TransAdapter.Insert(DataID:="NOT ASSIGNED", ID:=1, Book:="Book1", Page:="Page1", User:="User1", urlPDF:="url1", Transcription:="Transcription1", Transcription_Text:=TranscriptionTextbox.Text, isMaster:=0, isLocked:=0, Timestamp:="2004-11-15 11:37:10", CreateDate:="2004-11-15 11:37:10")
            ' Add the incremented page link back to the String
            pgLink = "http://br.mdsa.net/BookReader/index.html?id=ce425&item=1&format=Bitonal#page/" & gbCurrentPage & "/mode/1up"
            ' Declare Label 1 as The BookViewer on the Requested Page Number
            Label1.Text = "<object id=""BookViewer"" data=""" & pgLink & """ height=""500"" width=""1500""><embed src=""" & pgLink & """ width=""95%"" height=""100%""/>Error: Embedded data could not be displayed.</object>"
            ' Redirect to the Global Current Page Number
            Response.Redirect("~/WebForm1.aspx?page=" & gbCurrentPage)

            ' If the autosave checkbox is UNCHECKED....
        Else
            If AutoSaveCheckBox.Checked = False Then
                'Display Yes/No Save Confirmation
                MsgBox("Would you like to save before continuing to the next page?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Confirm")

                ' For Previous Case:
                If previousPageSaveConfirmation = MsgBoxResult.Yes Then
                    ' Decrement Global Current Page Number by one page if greater than page 1:
                    'If gbCurrentPage > 1 Then gbCurrentPage -= 1
                    ' Save (Either Insert or Update) Transcription
                    TransAdapter.Insert(DataID:="NOT ASSIGNED", ID:=1, Book:="Book1", Page:="Page1", User:="User1", urlPDF:="url1", Transcription:="Transcription1", Transcription_Text:=TranscriptionTextbox.Text, isMaster:=0, isLocked:=0, Timestamp:="2004-11-15 11:37:10", CreateDate:="2004-11-15 11:37:10")
                    ' Add the decremented page link back to the String
                    pgLink = "http://br.mdsa.net/BookReader/index.html?id=ce425&item=1&format=Bitonal#page/" & gbCurrentPage & "/mode/1up"
                    ' Declare Label 1
                    Label1.Text = "<object id=""BookViewer"" data=""" & pgLink & """ height=""500"" width=""1500""><embed src=""" & pgLink & """ width=""95%"" height=""100%""/>Error: Embedded data could not be displayed.</object>"
                    ' Redirect to the Global Current Page Number
                    Response.Redirect("~/WebForm1.aspx?page=" & gbCurrentPage)
                ElseIf previousPageSaveConfirmation = MsgBoxResult.No Then
                    ' Decrement Global Current Page Number by one page if greater than page 1:
                    'If gbCurrentPage > 1 Then gbCurrentPage -= 1
                    ' Go to Previous Page:
                    ' Add the decremented page link back to the String
                    pgLink = "http://br.mdsa.net/BookReader/index.html?id=ce425&item=1&format=Bitonal#page/" & gbCurrentPage & "/mode/1up"
                    ' Add the incremented page link back to the String
                    pgLink = "http://br.mdsa.net/BookReader/index.html?id=ce425&item=1&format=Bitonal#page/" & gbCurrentPage & "/mode/1up"
                    ' Declare Label 1
                    Label1.Text = "<object id=""BookViewer"" data=""" & pgLink & """ height=""500"" width=""1500""><embed src=""" & pgLink & """ width=""95%"" height=""100%""/>Error: Embedded data could not be displayed.</object>"
                    ' Redirect to the Global Current Page Number
                    Response.Redirect("~/WebForm1.aspx?page=" & gbCurrentPage)
                End If

                ' For Next Case:
                If nextPageSaveConfirmation = MsgBoxResult.Yes Then
                    ' Increment global current page number by one page
                    'gbCurrentPage += 1
                    ' Save (Either Insert or Update) Transcription and go to next page
                    TransAdapter.Insert(DataID:="NOT ASSIGNED", ID:=1, Book:="Book1", Page:="Page1", User:="User1", urlPDF:="url1", Transcription:="Transcription1", Transcription_Text:=TranscriptionTextbox.Text, isMaster:=0, isLocked:=0, Timestamp:="2004-11-15 11:37:10", CreateDate:="2004-11-15 11:37:10")
                    ' Add the incremented page link back to the String
                    pgLink = "http://br.mdsa.net/BookReader/index.html?id=ce425&item=1&format=Bitonal#page/" & gbCurrentPage & "/mode/1up"
                    ' Declare Label 1
                    Label1.Text = "<object id=""BookViewer"" data=""" & pgLink & """ height=""500"" width=""1500""><embed src=""" & pgLink & """ width=""95%"" height=""100%""/>Error: Embedded data could not be displayed.</object>"
                    ' Redirect to the Global Current Page Number
                    Response.Redirect("~/WebForm1.aspx?page=" & gbCurrentPage)
                ElseIf nextPageSaveConfirmation = MsgBoxResult.No Then
                    ' Increment global current page number by one page
                    'gbCurrentPage += 1
                    ' Go to next page:
                    ' Add the incremented page link back to the String
                    pgLink = "http://br.mdsa.net/BookReader/index.html?id=ce425&item=1&format=Bitonal#page/" & gbCurrentPage & "/mode/1up"
                    ' Declare Label 1
                    Label1.Text = "<object id=""BookViewer"" data=""" & pgLink & """ height=""500"" width=""1500""><embed src=""" & pgLink & """ width=""95%"" height=""100%""/>Error: Embedded data could not be displayed.</object>"
                    ' Redirect to the Global Current Page Number
                    Response.Redirect("~/WebForm1.aspx?page=" & gbCurrentPage)
                End If
            End If
        End If
    End Sub

A: As the error message says you cannot call an instanced - not shared member from the shared method. So for example consider this setup:
Public Class Testing

  Public Shared Function Test1() As String
      Dim value = Test2()
      return value
  End Function

  Public Function Test2() As String
      return "Some text..."
  End Function

End Class

This will not work since you are trying to invoke a non shared method Test2 from within a shared method Test1. The reason why it will not work is because method Test2 requires an instance of Testing class in order to be invoke - it can only be invoked via that instance. To fix this issue you have 2 options:

*

*Make method Test 2 be shared too.

*Fix the code in the following manner:
Public Class Testing

  Public Shared Function Test1() As String
    Dim instance = New Testing()
    Dim value = instance.Test2()
    return value
  End Function

  Public Function Test2() As String
    return "Some text..."
  End Function

End Class


text:
Q: transition with position absolute I have a div that is positioned absolute to my header-Tag. All is okay. With JavaScript I toggle the classes display_block and display_none, when I click on my button.
All works fine.
The div that gets display: none and display: block with the toggle, gets the position right: -100% when it's display:none, and right: 0 when its display: block.
Also works fine. But there is one problem.
The div got transition: all 1s ease-in-out but I don't get that flow-motion. It's only here or gone. But no effect. Why?

header {
  position: relative;
}

#ware_cart {
  position: absolute;
  top: 80px;
  width: 35%;
  transition: all 1s ease-in-out;

}

.display_none {
  display: none;
  right: -100%;
}

.display_block {
  display: block;
  right: 0;
}

A: As Paulie D said, you can not transition display.
Also, if the element starts at right: 100% there is no need to hide it.
Try this snippet:

$('#toggle').click( function() {
  $('#ware_cart').toggleClass('move_right');
});
header {
  position: relative;
}

#ware_cart {
  position: absolute;
  width: 35%;
  top: 80px;
  right: 100%;
  transition: right 1s ease-in-out;
}

#ware_cart.move_right {
  right: 0%;
}

    stuff i like to show

    Toggle it!


text:
Q: Dynamic array with void pointer So learning pointers in C and i thought that as an exercise i could do some generic array and i got it working when using void** like this:
struct array{
    void **data;
    size_t size, capacity;
};

inserting elements like this:
void array_append(array *a, void *element){
    if(a->size == a->capacity){
        a->capacity += ARRAY_GROW_CONSTANT;
        a->data = realloc(a->data, sizeof(void*)*a->capacity);
    }
    a->data[a->size++] = element;
}

But this is not really good. The array stores pointers to elements so when the scope of element ends, it becomes invalid, and also it makes the content of array to be scattered across entire memory. This i think can be solved by allocating the elements themselves so instead
a->data[a->size++] = element;

i would do something like
a->data[a->size] = malloc(inserted_element_size);
memcpy(a->data[a->size], &element, inserted_element_size);
size++;

but i thought that i could get the same funcionality when using plain void*, instead of void**
struct array{
    void *start;
    size_t element_size, size;
};

and inserting elements like
void array_append(array *a, void *element){
    a->size += 1;
    a->data = realloc(a->data, (a->size*a->element_size));
    memcpy(a->data + (a->size - 1)*a->element_size, &element, a->element_size);
}

but this results into segfault and i don't know why. As i understand it (obviously i don't), pointers are adresses in memory, so if i have a contiguous block of memory, i can store variable of any type in it with offset.
Edit: Thanks for the explanation, it really helped.

What is a->data initialized to?

I used a function to initialize the array and the a->data was initialized to element_size.

the caller will have to cast the resutl into element *

I thought i could use macro to make the typing shorter (i think this is a bad thing?), but i don't know about the performance of typecasting from void* to struct*.

Creating a dynamic array of elements directly seems more practical to me.

But that wouldn't allow me to use the array as generic one? What i wanted was to define a generic array that i could use to store any type, like
array *a1 = create_array(sizeof(int)); // array of int
array *a2 = create_array(sizeof(double)); // array of double
etc...

why do you want your data to be stored in a contiguous block?

Because i thought that you need a contiguous block of memory to use memcpy with offset.

A: What is a->data initialized to? For this to work, it should be set to NULL when the (empty) array is created.
Also, you address computation does not take pointers arithmetics into account. a->data is a pointer (to void *), so the (a->size - 1)*a->element_size offset will be multiplied by the size of a pointer (to void *).
Setting a->data to void * should cause a compiler error since void has no size.
If you really want to do this, better declare a->data as a char *, which is guaranteed to have a size of 1.
Beware: accessing your array will require a cast to (element*). This will prevent you from using square brackets.
You will have to provide an accessor function like
void * array_at(size_t index) { return &a->data[index*a->element_size]; }
and then the caller will have to cast the resutl into element *.
Creating a dynamic array of elements directly seems more practical to me.
You can still call realloc on it if you want.
But the first question that springs to my mind is: why do you want your data to be stored in a contiguous block?
This is not as memory-efficient as you might think, since calling realloc() repeatedly will stress the memory allocator, waste time doing copies and possibly fragment the heap even more than a collection of individual mallocs.

A: Commenting on the last portion of the code using void* as the array for data. The code should work but it has problems:
You are passing the address of the element pointer instead of just the pointer itself, which already pointer to correct( hopefully ) data.
Also you cannot do pointer arithmetic on void, but certain compilers allow it.
The correct version of memcpy would be
memcpy ( ( unsigned char* )a->data + (a->size - 1)*a->element_size, element, a->element_size);


text:
Q: Symmetric Inequality for positive real numbers Show that if $a,b,c$ are positive real numbers such that $S_2 := ab+bc+ca = 3$, then
$$ \cfrac{1}{a+b+2} + \cfrac{1}{a+c+2} + \cfrac{1}{b+c+2} \leq \cfrac{13 \cdot S_1 + 27}{16 \cdot S_1 + 40}$$
where $S_1 = a+b+c$
My road so far
Well, my idea so far was to find some expression "more obviously" between the two sides of that inequality:
$$ \cfrac{1}{a+b+2} + \cfrac{1}{a+c+2} + \cfrac{1}{b+c+2} \leq f(a,b,c) \leq \cfrac{13 \cdot S_1 + 27}{16 \cdot S_1 + 40}$$
An obvious guess would be just set $a=b=c=1$, resuilting $f(1,1,1) = \frac{3}{4}$.
The rightmost inequality is not so hard: it just implies $S_1 \geq3$, a classical result.
But I am stuck in the leftmost inequality...

A: Because $1-\frac{2}{a+b+c}=\frac{a+b}{a+b+2},$ so inequality equivalent to
$$\sum \frac{a+b}{a+b+2} \geqslant \frac{11(a+b+c)+33}{8(a+b+c)+20}.$$
From known inequality (here)
$$\sum \sqrt{(a+b)(b+c)} \geqslant a+b+c+\sqrt{3(ab+bc+ca)},$$
and the Cauchy-Schwarz inequality, we get
$$\sum \sqrt{(a+b)(b+c)} \geqslant \frac{\displaystyle \left(\sum \sqrt{a+b}\right)^2}{\displaystyle \sum (a+b+2)} = \frac{\displaystyle a+b+c+\sum \sqrt{(a+b)(b+c)}}{a+b+c+3}$$
$$ \geqslant \frac{2(a+b+c)+\sqrt{3(ab+bc+ca)}}{a+b+c+3}.$$
Thefore, we will show that
$$\frac{2(a+b+c)+\sqrt{3(ab+bc+ca)}}{a+b+c+3} \geqslant \frac{11(a+b+c)+33}{8(a+b+c)+20}. \tag 1$$
Let $x = a+b+c, \; y = \sqrt{3(ab+bc+ca)}$ then $ x\geqslant y,$ inequality (1) become
$$\frac{2x+y}{x+y} \geqslant \frac{33(x+y)}{4(6x+5y)},$$
equivalent to
$$4(6x+5y)(2x+y) \geqslant 33(x+y)^2,$$
or
$$(15x+13y)(x-y) \geqslant 0.$$
Which is true. The proof is completed.

A: Let $a+b+c=3u$, $ab+ac+bc=3v^2$ and $abc=w^3$.
Thus, since $$\prod_{cyc}(a+b)=9uv^2-w^3$$ and $\sum_{cyc}(a+b+2)(a+c+2)$ and $\frac{13(a+b+c)+27}{16(a+b+c)+40}>0$ are not depended on $w^3$,
we see that our inequality is equivalent to $f(w^3)\leq0,$ where $f$ increases.
Thus, it's enough to prove our inequality for a maximal value of $w^3$,
which by $uvw$ happens for equality case of two variables.
Let $b=a$.
Thus, $c=\frac{3-a^2}{2a}$ and we obtain:
$$(a-1)^2(13a^2+24a+15)\geq0,$$ which is obvious.

A: The pqr method
Let $p = a + b + c, q = ab + bc + ca = 3$ and $r = abc$. We need to prove that
$$\frac{p^2+8p+q+12}{2p^2+pq+8p+2q-r+8} \le \frac{13p+27}{16p+40}.$$
Since $p^2 \ge 3q$, we have $p \ge 3$.
Since $q^2 \ge 3pr$, it suffices to prove that
$$\frac{p^2+8p+q+12}{2p^2+pq+8p+2q-\frac{q^2}{3p}+8} \le \frac{13p+27}{16p+40}$$ or
$$\frac{(p-3)(10p^2+29p+9)}{8(2p^2+5p-1)(2p+5)}\ge 0.$$
We are done.

A: Now I will post my solution after following some ideas above.
Let $a+b+c=S_1, ab+bc+ca=S_2, abc=S3$.
We want to show that
$$\cfrac{1}{a+b+2} + \cfrac{1}{a+c+2} + \cfrac{1}{b+c+2} \leq \cfrac{3}{4} \leq \cfrac{13 \cdot S_1 + 27}{16 \cdot S_1 + 40}$$
First the hard part:
$$\cfrac{1}{4} - \cfrac{1}{a+b+2} = \cfrac{a+b+2-2}{4(a+b+2)} = \cfrac{1}{4} \cdot \cfrac{(a+b-2)}{(a+b+2)}$$
We want to show that $$ \cfrac{(a+b-2)}{(a+b+2)} +  \cfrac{(a+c-2)}{(a+c+2)} +  \cfrac{(a+b-2)}{(a+b+2)} \geq 0$$
Or, opening:
$$ (a+b-2)(a+c+2)(b+c+2) + (a+b+2)(a+c-2)(b+c+2) +  (a+b+2)(a+c+2)(b+c-2) \geq 0$$
But $$(a+b-2)(b+c+2)(c+a+2) =
(a^2b+a^2c+ab^2+ac^2+b^2c+bc^2) + (2a^2+2b^2-2c^2) + (2ab+2ac+2bc) + 2abc -8c-8$$
So, adding them we have
$$(a+b-2)(a+c+2)(b+c+2) + (a+b+2)(a+c-2)(b+c+2) +  (a+b+2)(a+c+2)(b+c-2) =
3(a^2b+a^2c+ab^2+ac^2+b^2c+bc^2) + 2(a^2+b^2+c^2) + 6(ab+ac+bc) + 6abc -8(a+b+c)-24
$$
But $(a^2b+a^2c+ab^2+ac^2+b^2c+bc^2) = (a^2b+ab^2+abc) + (a^2c+ac^2+abc) + (b^2c+bc^2+abc) -3abc = S_1S_2 - 3S_3$
And $(a^2+b^2+c^2) = S_1^2-2S_2$
Substituting and remembering $S_2=3$ we have
$$(a+b-2)(a+c+2)(b+c+2) + (a+b+2)(a+c-2)(b+c+2) +  (a+b+2)(a+c+2)(b+c-2) =
3(S_1S_2 - 3S_3) + 2(S_1^2-2S_2) + 6S_2 + 6 -8S_1 - 24 =
3S_1S_2 - 9S_3 + 2S_1^2-4S_2 + 6S_2 + 6S_3 - 8S_1 - 24 =
9S_1 - 9S_3 + 2S_1^2-12 + 18 + 6S_3 - 8S_1 - 24 =
2S_1^2 + S_1 - 3S_3 - 18 $$
By the Means Inequality, we have $$\cfrac{S_1}{3} \geq \sqrt{\cfrac{S_1}{3}} \geq \sqrt[3]{S_3}$$. Substituting $S_2$, we have $S_1 \geq 3$ and $S_3 \geq 1$.
So our expression is at least $2 \cdot 3^2 + 3 - 3 \cdot 1 - 18 = 0$, as we wish!
The rightmost inequality is just an equivalent form of $S_1 \geq 3$.


text:
Q: Difference between webservice, web methods & server side code? Some questions confusing me guys, I'm just new to web services altogether.

*

*What is the difference between
  web service, web methods and server
  side code ?

*Where is web service
  preferred over server side methods?

*Where are web methods preferred
  to be used ?

*How does web service
  differ from server side post back ?

*Are web services light weight ?
  Can they be used to save long web
  forms as well ?

*In an enterprise
  web application, which one of these
  should I use frequently and why?

A: The term "web method" has several meanings, among them:

*

*In the legacy ASMX web service technology, web service operations were created by adding the [WebService] attribute to a public class, and the [WebMethod] attribute to public instance methods of such a class. these methods would then be exposed as web service operations.

*There is a related technology, "Page Methods" that is part of ASP.NET. It basically allows you to create tiny web services by using the [WebMethod] attribute on a public static method of a page class.

In both cases the term is specific to the implementation technology. The generic term is "web service operation". For example, in WCF, a web service operation is created by placing the [OperationContract] attribute on a method.
Note that ASMX is now considered by Microsoft to be a "legacy technology". All new development should use WCF.

A:
What is the difference between web
  service, web methods and server side
  code ?

A web service is an exposed end point that is normally used as an API, or in other words its end user is typically another application rather than a user interface. A web method is a particular method that is exposed over a web service.
On the other hand, server-side code applies to any ASP.NET web page, web service, or other technology for general implementation of its functionality.

Where is web service preferred over
  server side methods?

Web services excel at making an application compatible with other programming platforms or for serving up AJAX requests to a web page. There are many other uses, but typically using WCF or HttpHandlers are better options in those cases.

Where are web methods preferred to be
  used ?

Web methods can be used in any .aspx page or more typically in a .asmx (web service) file.

How does web service differ from
  server side post back ?

A server-side postback occurs when a web page posts data to the server for processing. A web service is completely different - it is an endpoint that is exposed for consumption by another application (or within the same application).

Are web services light weight ? Can
  they be used to save long web forms as
  well ?

No, web services are not light weight, in fact they are quite the opposite because they generally receive and respond to data using XML (a bulky format). However, this makes them very easy to use with other programming languages.

In an enterprise web application,
  which one of these should I use
  frequently and why?

This is a highly subjective question. Each technology in the .NET framework has a set of features that it excels at and can usually do several other things (but not very well). Each tool has its place, it is just a matter of matching the tools to use with the requirements of your project.
However, judging by the rest of your questioning, it sounds like you are just putting together a typical website that doesn't require an API, in which case it would be best to use .aspx pages and code behind.

A: My taxonomy:
Service - a named piece of functionality the provides some value to another component, delimited by a contract of some description.
Operation - a specifically named piece functionality that a service exposes. Generally services can expose 1 or more operations.
Web service - A Service that is exposed using web technology such as HTTP or over the internet.
Server Side Code - the implementation of the service's functionality. You can consider this to be the code that the service is made from.
Web Method - A particular term referring to an operation on a web service. In some technologies this is also use to describe the technology used to implement an operation. You use these to implement an operation - e.g. the server side code of the operation.
A server side postback is when a service calls back to the original consumer of the service usually asynchronously.
Since web services are just services exposed over internet technology they can be as heavy or light weight as needed. It depends on the requirements of the operations' contracts.
Which one should you use? Can't say each requirement is different.

A: The term "method" or "web method" is strictly a Microsoft terminology. It is not a proper term ever suggested by w3c standard.
Microsoft is known for bastardizing proper software terminology, including the concept of basic Object Oriented programming paradigm.


text:
Q: Padding on tbody I'm using vBulletin to style a forum which primarily uses tables to style the site. How would I go about using padding on a tbody to space the content away from the border?
Here you can see a picture of my main site where the content is pushed 5px away from the border:

Whereas on vBulletin, adding padding on tbody doesn't push the content away:

A: Method 1
You have a couple different options:
tbody:before {
  content: '';
  display: block;
  height: 20px;
}

Adding this basically "inserts" content before the end. It's sort of a "quick-n-dirty" fix.

Method 2
Another option is giving your table a border-collapse: collapse and then giving your tbody a border value:
table {
  border-collapse: collapse;
}
table tbody {
  border-right: 20px solid transparent;
}

Both of these methods have drawbacks, however. The before selector might not work in IE7, and requires a !DOCTYPE to work in IE8. The second method can sometimes be a bit touchy, depending on the rest of your css. Be sure to have a !DOCTYPE

A: Add an empty col and/or row with padded cells.
Adding :before content to tbody may not have the effect you're looking for. It may not push borders around as you think or even other cells or col or row groups. In general do not try to put anything outside a cell in a table, you're asking for trouble.


text:
Q: How to get Result aligned with Result? I have this code
fn get_last_commit () -> String {

    Command::new("git")
            .arg("rev-parse")
            .arg("HEAD")
            .output()
            .map(|output| {
                String::from_utf8(output.stdout).ok().expect("error reading into string")
            })
            .ok().expect("error invoking git rev-parse")
}

I'd like to be able to cut the ok().expect(..) a bit down so that I ideally have something like that:
fn get_last_commit () -> String {

    Command::new("git")
            .arg("rev-parse")
            .arg("HEAD")
            .output()
            .and_then(|output| {
                String::from_utf8(output.stdout)
            })
            .ok().expect("error invoking git rev-parse")
}

However, that doesn't work because the errors don't line up leaving me with:
    mismatched types:
     expected `core::result::Result<_, std::io::error::Error>`,
        found `core::result::Result<collections::string::String, collections::string::FromUtf8Error>`
    (expected struct `std::io::error::Error`,
        found struct `collections::string::FromUtf8Error`)

I know the error handling changed quite a bit within the last month and I have the feeling there should be away to get them aligned without too much hassle. I seem unable to figure it out though.

A: The problem is that the closure passed to the and_then needs to return a Result with the same error type as the Result that and_then was called on; otherwise, there's no single type that and_then could return; and_then maps one Ok type to another, but keeps the error type the same.
Since you are just throwing away the error value by converting it to an option with ok() that you unwrap anyhow, you can do that before calling and_then, and within the closure, as the Option type returned by and_then on an Option only depends on the value returned by the closure:
fn get_last_commit () -> String {

    Command::new("git")
            .arg("rev-parse")
            .arg("HEAD")
            .output()
            .ok()
            .and_then(|output| {
                String::from_utf8(output.stdout).ok()
            })
            .expect("error invoking git rev-parse")
}

If you actually cared about the error value, you would need to define your own error type that could contain either of the two types of errors, and wrap either of the errors up. The FromError trait and try! macro offer a convenient way to is wrap up the value and return it from one of several places in your function, though in this case map_err would probably be a better way to do that as you are doing it all via chained method calls rather than separate statements.
enum MyError {
    Io(IoError),
    Utf8(FromUtf8Error)
}

fn get_last_commit () -> Result<String,MyError> {

    Command::new("git")
            .arg("rev-parse")
            .arg("HEAD")
            .output()
            .map_err(MyError::Io)
            .and_then(|output| {
                String::from_utf8(output.stdout)
                       .map_err(MyError::Utf8)
            })
}

If you notice, this parallels the earlier solution fairly closely, coercing both of the result types into a single common type; in the first solution, it just throws away the error value by using ok(), while in the second, it preserves the error value so you can return it, but you now need the extra machinery of a type that could wrap either.


text:
Q: Setting default value from database in JQuery datetimer picker I tried date time picker in my application with help of the following program:
http://eonasdan.github.io/bootstrap-datetimepicker/
It worked fine.
My problem is, I need to set default value for date time fetched from database.

<input type="text"></input>

When I tried to set the value as:
<input type="text" value="<%=datetimefromdatabase%>"></input>

it didn't worked.
Kindly help.

A: You can set like this
$('#datetimepicker1').data("DateTimePicker").setDate("10/23/2013");

Please read the documentation fully.


text:
Q: HDFS behavior: Datanodes up but all data goes to one node (using -copyFromLocal) I have a cluster configuration.

*

*Master (also a slave)

*Two slaves

*Replication factor = 1

I copied a ~9GB file, movies.txt into hdfs as:
hadoop dfs -copyFromLocal movies.txt /input/

I observed that half of the blocks were saved to Master and other half were distributed on the two slaves.
Then I thought of formatting the hadoop_stores using:
stop-all.sh
rm -rf {hadoop_store}/*
hdfs namenode -format

ssh slave1
rm -rf {hadoop_store}/*
hdfs namenode -format
exit

ssh slave2
rm -rf {hadoop_store}/*
hdfs namenode -format

start-all.sh

Now, when I tried
hadoop dfs -copyFromLocal movies.txt /input/

Shockingly, I got all the blocks on master !
For reference my hdfs_site.xml is:
<configuration>
 <property>
  <name>dfs.replication</name>
  <value>1</value>
 </property>
 <property>
   <name>dfs.namenode.name.dir</name>
   <value>file:///usr/local/hadoop/hadoop_store/hdfs/namenode</value>
 </property>
 <property>
   <name>dfs.datanode.data.dir</name>
   <value>file:///usr/local/hadoop/hadoop_store/hdfs/datanode</value>
 </property>
</configuration>

Any explanation what I am doing wrong?

A: You did nothing wrong. When a file is being written to HDFS the very first replica is always located on a local node. And when replication factor is 1, then all blocks are stored only on a local node. When space on the local node is run out, then, I suppose, HDFS tries to store block on other nodes. It seems that happened the first time you copied the file before formatting HDFS.


text:
Q: mysql query (join) and adding subqueries I've this query, and it displays results correctly. I didn't use join, but it still seems to return correct values, how is that possible?
SELECT connections.id,
       connections.word_id,
       connections.order_id,
       connections.top,
       connections.deleted,
       (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(connections.modified)) AS modified_ago,
       words_en.word,
       (CASE WHEN words_en.user_id = 1 THEN "You" ELSE words_en.user_id END) AS created_by
FROM connections, words_en
WHERE connections.word_id = words_en.id AND connections.user_id = 1
IN (SELECT COUNT(*) connections WHERE /* Result of previous select connections.word_id */ AND connections.user_id != 1)
ORDER BY connections.order_id

*

*Is it enough to do this: connections.word_id = words_en.id to join?

*I would also like to add sub-queries to this. What is syntax for that?
sub-query should count number of times conenctions.word_id appears in connections table where connections.user_id != 1 ergo how many times other users used this word.

*

*I also need another join that would get me users.name_surname for words_en.user_id.

A: To join tables we can use ,(Comma) or join keyword.
If we are using ,(Comma) it will give exact result as per our condition.
If we are using join keyword we can use many types of join like left join right join , and many more. These all joins will give different result.
We can say ,(Comma) join is same as JOIN but not as LEFT JOIN.
Below is the example to write sub query
SELECT connections.id,
       connections.word_id,
       connections.order_id,
       connections.top,
       connections.deleted,
       (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(connections.modified)) AS modified_ago,
       words_en.word,
       words_en.user_id
FROM connections, words_en
WHERE connections.word_id = words_en.id AND connections.user_id IN (select id from connections)
ORDER BY connections.order_id

select id from connections is subquery
For your 3rd point try below
SELECT users.name_surname
FROM users, words_en
WHERE users.user_id = words_en.user_id
ORDER BY users.user_id

A: for a join -operation:
SELECT connections.id,
   connections.word_id,
   connections.order_id,
   connections.top,
   connections.deleted,
   (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(connections.modified)) AS modified_ago,
   words_en.word,
   words_en.user_id
FROM connections
LEFT JOIN  words_en ON connections.word_id = words_en.id AND connections.user_id = 1
WHERE
     words_en.id IS NOT NULL
ORDER BY connections.order_id


text:
Q: MVC controller differences between this.Response and this.HttpContext.Response MVC controller has many object which exists in HttpContext subobject too. What are differences between this objects?
        var res = HttpContext.Response;
        var res1 = Response;

        var req = HttpContext.Request;
        var req1 = Request;

A: The Request and  Response properties of the Controller class are really just returning HttpContext.Request and HttpContext.Response. There is no difference in the two. The presence of the Controller properties is really for succinctness to avoid using HttpContext.Request / HttpContext.Result.
You can see it in the source code:
public abstract class Controller
{
    // ...

    public HttpRequestBase Request
    {
        get { return HttpContext == null ? null : HttpContext.Request; }
    }

    public HttpResponseBase Response
    {
        get { return HttpContext == null ? null : HttpContext.Response; }
    }

    // ...

}

You should, however, use the Controller properties as they are directly related to MVC and not the System.Web.dll stack. If, in the future, there is a change in the MVC framework in regards to the Request / Response object model in such a way that the dependency with the System.Web and HttpContext class is removed, the Request and Response of the Controller itself should reflect directly what is is, and will require less change in code of your part (even though I think it's unlikely we see this kind of breaking change in the near future).


text:
Q: url handling with web.py and extjs I'm porting a program from turbogears to web.py/mod_wsgi with pretty good success.  I've setup the URL handling similar to turbogears, but I'm running into a minor annoyance in how extjs 2.0 handles URLs.
Say my app is named "ack", I can test it by going to either http://localhost/ack or http://localhost/ack/ (note the trailing slash as the only difference).  From a web.py point of view, this doesn't matter.  However, in the template I'm using that was written in extjs, I designate urls to query information from the app using JSON (example below).
var nameListStore = new Ext.data.JsonStore({
url: 'nameList',
root: 'nameList',
autoLoad: true,
fields: ['name'],
});

Here's the trouble.  If I access my app using the trailing slash, than extjs forms the a url query like http://localhost/ack/nameList, which calls my app's function and gets the correct data back.  If I don't have the trailing slash in the address bar, extjs builds the url as http://localhost/nameList, which never makes it to my application and literally every JSON query fails (as shown in my firebug console).
I assume extjs is just ripping off anything trailing the last slash to build the url, but I'd like to fix that.  Right now I'm just telling my users to make sure they run the app with the trailing slash, but this seems like a simple thing to handle.  I just don't know how in extjs.


text:
Q: Kohana V3 Auth module user_token functionality Could anybody brief about user_token functionality in Auth module? What is a use and how this incorporates in Auth module?

A: It is used when a user checks the 'Remember me' box on your site.  A token is generated for the user and stored in the user_tokens table.
If you look at the Kohana_Auth_ORM class in the _login function, you can see how it is created:
    if ($remember === TRUE)
    {
        // Create a new autologin token
        $token = ORM::factory('user_token');

        // Set token data
        $token->user_id = $user->id;
        $token->expires = time() + $this->config['lifetime'];
        $token->save();

        // Set the autologin cookie
        cookie::set('authautologin', $token->token, $this->config['lifetime']);
    }

It is used by the auto_login() function also in the Kohana_Auth_ORM class:
/**
 * Logs a user in, based on the authautologin cookie.
 *
 * @return  boolean
 */
public function auto_login()
{
    if ($token = cookie::get('authautologin'))
    {
        // Load the token and user
        $token = ORM::factory('user_token', array('token' => $token));

        if ($token->loaded() AND $token->user->loaded())
        {
            if ($token->user_agent === sha1(Request::$user_agent))
            {
                // Save the token to create a new unique token
                $token->save();

                // Set the new token
                cookie::set('authautologin', $token->token, $token->expires - time());

                // Complete the login with the found data
                $this->complete_login($token->user);

                // Automatic login was successful
                return TRUE;
            }

            // Token is invalid
            $token->delete();
        }
    }

    return FALSE;
}

It is up to you to correctly use this capability within your authorization controller.    I'm relatively new to Kohana, but I perform a simple check to redirect a user if they go to the login form and are already logged in or can automatically login:
if (Auth::instance()->logged_in() || Auth::instance()->auto_login())
    Request::instance()->redirect('auth/');

The code for the Auth module isn't too difficult to understand.  If you're new to Kohana, it's a good starting point to see how the ORM module works.


text:
Q: Store area as square feet or square meters? In the context of houses, should area be stored as square feet or square meters?
The area of the largest houses in existence are greater than 32000 sqft, so a 4-byte integer may be required to store square feet. For this reason, I'm favouring square meters at the moment.
Are there any other considerations that are not immediately obvious?

A: Square metres stored as an integer may not have enough resolution to capture what you need to know.  Converting to and from square feet or metres will lose information.  Use floating point values to prevent this issue.
Use whichever unit your primary users are likely to want for storage.  If you are only targeting a US/UK market (where square feet is the customary measurement), store that.  Most of the rest of the world prefers metric, however, so for an international market prefer square metres.

A: If your app will potentially be used outside the USA, Myanmar or Liberia, or will it interoperate with other systems, I'd suggest you use the more widely accepted measurement system to store the data and then convert it to whatever local mesurement system the user wants to display. Obviously the columns shouldn't be integers but real.
The metric system is widely accepted in science and enginneering for information exchange:

Source: Wikipedia.
So my suggestion is that you store it in the metric system (square meters for area) and then convert appropiatelly to present it in whatever unit the user prefers (preference settings).
In the other hand, if your app will only be used in the USA, Myanmar or Liberia, store the areas in squared feet.

A: Neither.
Since you are asking this question, you are probably working on a system which uses both (or a system which will be used in different countries). This means that you should be able to store distances expressed in feet or meters.
In your database, do have not one, but two columns: one for the value, the other one for the unit. This would make it straightforward to store and retrieve the measurements, without doing the conversion under the hood (which is usually not what the user wants). Double conversion is especially problematic (for instance meters to feet to meters), since rounding errors will accumulate.
Note that you will probably need to support even more units than that. In the context of houses, I imagine that meters are not very precise: rooms will rather be measured in centimeters, if not millimeters (for electrical installations, it may matter). This makes this approach much more interesting than, say, having two columns, one for feet, another one for meters; with the approach I suggested, adding units won't lead to any schema change.
If you need to either sort the data (for instance larger houses appear first) or filter it (for example get only the houses larger than one hundred square meters), this is not enough: you would need a third column which contains a value converted to a common unit. It doesn't matter which unit exactly is used here, since those values will only be used for ordering and filtering.

A: That's the wrong way to tackle the problem. The question to ask is: what unit will be used elsewhere? Is it one unit only, or are different units possible (don't forget tatami). If only one unit will be used, then use exactly that. If different units may be used, decide for one, and make sure that a value will always be entered together with the unit in the UI, and gets converted to the unit you choose.

A: The reason you give for using a different unit is completely the wrong thing to be concerned with.  A 32 bit number can hold values much larger than that and even if that were the case, no one cares about optimizing on space in 2016.
The main decision point here will depend on what the values are used for.  If you just need to store and display then do as @ArseniMourzenko suggests and keep a units column.  If you need to do calculations on these values, it's going to depend on the specs for your calculations.  If you were doing physics, use SI units, no contest.  However if your app is used to calculate board-feet for flooring or how many studs are required to build the frame, you should problably stick with feet.  Even in Canada where the metric system is used, building codes are still (at least in part) specified in feet.

A: 1 square foot = 0.092903 square meter
1 square meter = 10.7639 square feet
The nearest simple integer conversion is 11
1/11 = 0.0909090909
The error is about 2%
If you use 521 / 5608 then you get integer conversion with  very small conversion error
Say the minimum house is 1000 sq feet
You have to round up or down
.5 / 1000 = 0.05% rounding error
1000 sq feet is about 90 square meters
.5 / 90 = 0.56 % rounding error
If you convert 1000 square feet to meters and back using integer 11 then is comes back 1001
For a 0.1% rounding error.
Using square feet you have 10X better precision
For precision store in square feet and have a computed column for square meters
Always sort on the square feet


text:
Q: How to document a single private attribute with Sphinx autodoc? I'm using sphinx and the autodoc extension to automatically generate documentation from docstrings in my python modules.
I currently using the automodule directive to document all the public members of the module
.. automodule::
    :members:

My module also has a number of private attributes.  I'd like to include one of them in the documentation.
Is there a way to tell automodule to document all public members and also this one private member?  I've tried using the :private-members: option, but that includes all private members.  I've also tried manually specifying the private attribute, but then it doesn't document any of the public members.
.. automodule::
    :members: _PRIVATE_ATTR

I'd like to avoid having to manually list every single public member just to add this one private member.
Is there a way to do this with autodoc?

A: Here is what I would expect to work (tested with Sphinx 1.8.3):
.. automodule:: yourmodule
   :members:
   :private-members: _PRIVATE_ATTR

But it does not quite work. If the :private-members: option is given, with or without arguments, all private members are included (provided that they have a docstring).
The :special-members: option takes arguments, so it is strange that :private-members: doesn't.
Instead you can use autodata:
.. automodule:: yourmodule
   :members:

.. autodata:: yourmodule._PRIVATE_ATTR

Here is a slightly different alternative with autodata "inside of" automodule:
.. automodule:: yourmodule
   :members:

   .. autodata:: _PRIVATE_ATTR

There is also an autoattribute directive but it does not work with module-level "data members". I have found that autoattribute can be used to document private class attributes, but the documentation is not clear on the exact difference between autodata and autoattribute.


text:
Q: self login bot , stay logged, browse site i am creating a bot in PHP that can log in into a site and stay logged. But it's not working.
i am using this code. but it's not working.
<?php
$curl = curl_init("http://www.site.com/login.php");
curl_setopt ($curl, CURLOPT_POST, 1);
curl_setopt ($curl, CURLOPT_POSTFIELDS, "usr=username&pswd=password");
curl_exec($curl);
echo curl_error($curl);
curl_close($curl);
?>

i have also tried this but it's also not working
<?php
$fields = array(
    "login"=>"username",
    "pass"=>"passowrd"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.site.com/login.php");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
?>

A: You'll need to use these to save their cookie:
CURLOPT_COOKIEFILE      => 'data/cookies/x.tmp',
CURLOPT_COOKIEJAR       => 'data/cookies/x.tmp',

Also, some times require a cookie to be set before the login is sent. This is often an issue. Often also worth setting:
CURLOPT_SSL_VERIFYHOST  => 0,
CURLOPT_SSL_VERIFYPEER  => 0,


text:
Q: Scanning char and Combining Switch statement with If statement? switch(time) The code that I've wrote:
#include<stdio.h>
int main()
{
    int yos;
    double salary;
    char time;

    printf("Please enter your employee status, 'P' for Fulltime and 'P' for Parttime: \n");
    scanf_s("%c", &time);
    printf("Please enter your year of service: \n");
    scanf_s("%d", &yos);
    printf("Please enter your current salary: \n");
    scanf_s("%lf", &salary);

    switch (time)
    {
    case 'F':
    case 'f':
        if (yos >= 5)
        {
            salary = (salary*5.0 / 100.0) + salary;
            printf("\nYour new salary is %.2lf", salary);
        }
        else if (yos < 5 )
        {
            salary = (salary*4.0 / 100.0) + salary;
            printf("\nYour new salary is %.2lf", salary);
        }
        break;

    case 'P':
    case 'p':
        if (yos >= 5)
        {
            salary = (salary*3.0 / 100.0) + salary;
            printf("\nYour new salary is %.2lf", salary);
        }
        else if (yos < 5 )
        {
            salary = (salary*2.5 / 100.0) + salary;
            printf("\nYour new salary is %.2lf", salary);
        }
        break;
    default:
        printf("Please put the details correctly\n");
    }

    return(0);
}

for some reason, when I run the program, I get this output:
Please enter your employee status, 'P' for Fulltime and 'P' for Parttime:
F
Please enter your year of service:
6
Please enter your current salary:
200
Please put the details correctly
Press any key to continue

does this problem occur because it cant scan the char? i even tried spacing the %c. i also dont think that putting %s or %[^\n] will be of any use since its only involve 1 character. please somebody help me?
I've also tried different code which involve only if statements such as:
#include<stdio.h>
int main()
{
    int yos;
    double salary;
    char time;

    printf("Please enter your employee status, 'P' for Fulltime and 'P' for Parttime: \n");
    scanf_s("%c", &time);
    printf("Please enter your year of service: \n");
    scanf_s("%d", &yos);
    printf("Please enter your current salary: \n");
    scanf_s("%lf", &salary);

    if (char time == 'F' && yos >= 5)
    {
        salary = (salary*5.0 / 100.0) + salary;
        printf("\nYour new salary is %.2lf", salary);
    }

    else if (char time == 'F' && yos < 5)
    {
        salary = (salary*4.0 / 100.0) + salary;
        printf("\nYour new salary is %.2lf", salary);
    }

    if (char time == 'P' && yos >= 5)
    {
        salary = (salary*3.0 / 100.0) + salary;
        printf("\nYour new salary is %.2lf", salary);
    }

    else if (char time == 'P' && yos < 5)
    {
        salary == (salary*2.5 / 100.0) + salary;
        printf("\nYour new salary is %.2lf", salary);
    }
    return(0);
}

But, this one is giving
error c2143 missing ',' before '==' at line 15, 21, 27...

there is also this:
Warning 11  warning C4553: '==' : operator has no effect; did you intend '='?

A: I opted to use scanf instead of scanf_s, also I prefer using enums and integers in switch statements. The following edit of your code worked for me;
#include<stdio.h>
int main()
{
    int yos;
    double salary;
    char time;

    printf("Please enter your employee status, 'F' for Fulltime and 'P' for Parttime: \n");
    scanf("%c", &time);
    printf("Please enter your year of service: \n");
    scanf("%d", &yos);
    printf("Please enter your current salary: \n");
    scanf("%lf", &salary);

    int status;
    if(time=='F'||time=='f')
        status = 1;
    if(time=='P'||time=='p')
        status = 2;
    switch (status)
    {
    case 1:
        if (yos >= 5)
        {
            salary = (salary*5.0 / 100.0) + salary;
            printf("\nYour new salary is %.2lf", salary);
        }
        else if (yos < 5 )
        {
            salary = (salary*4.0 / 100.0) + salary;
            printf("\nYour new salary is %.2lf", salary);
        }
        break;

    case 2:
        if (yos >= 5)
        {
            salary = (salary*3.0 / 100.0) + salary;
            printf("\nYour new salary is %.2lf", salary);
        }
        else if (yos < 5 )
        {
            salary = (salary*2.5 / 100.0) + salary;
            printf("\nYour new salary is %.2lf", salary);
        }
        break;
    default:
        printf("Please put the details correctly\n");
    }

    return(0);
}

A: When using the %c format specifier, you need to give an additional parameter specifying the number of characters to read.  From the MSDN page for scanf_s:

Unlike scanf and wscanf, scanf_s and wscanf_s require the buffer size
  to be specified for all input parameters of type c, C, s, S, or string
  control sets that are enclosed in []. The buffer size in characters is
  passed as an additional parameter immediately following the pointer to
  the buffer or variable.
...
In the case of characters, a single character may be read as follows:
char c;

scanf_s("%c", &c, 1);

Because you don't pass in the required number of parameters, you invoke undefined behavior.
So when you read in time, do it like this:
scanf_s("%c", &time, 1);

Also, in your second example, this is invalid syntax:
if (char time == 'F' && yos >= 5)

Get rid of the char keyword here.

A: scanf_s is Microsoft-specific are you use that you must use it? If I try with scanf and the gcc compiler then the first version of program seems to work and the default statement is not printed when the program is run.
#include<stdio.h>

int main() {
    int yos;
    double salary;
    char time;

    printf("Please enter your employee status, 'F' for Fulltime and 'P' for Parttime: \n");
    scanf("%c", &time);
    printf("Please enter your year of service: \n");
    scanf("%d", &yos);
    printf("Please enter your current salary: \n");
    scanf("%lf", &salary);

    switch (time) {
        case 'F':
        case 'f':
            if (yos >= 5) {
                salary = (salary * 5.0 / 100.0) + salary;
                printf("\nYour new salary is %.2lf", salary);
            }
            else if (yos < 5) {
                salary = (salary * 4.0 / 100.0) + salary;
                printf("\nYour new salary is %.2lf", salary);
            }
            break;

        case 'P':
        case 'p':
            if (yos >= 5) {
                salary = (salary * 3.0 / 100.0) + salary;
                printf("\nYour new salary is %.2lf", salary);
            }
            else if (yos < 5) {
                salary = (salary * 2.5 / 100.0) + salary;
                printf("\nYour new salary is %.2lf", salary);
            }
            break;
        default:
            printf("Please put the details correctly\n");
    }

    return (0);
}

Test
Please enter your employee status, 'F' for Fulltime and 'P' for Parttime:
F
Please enter your year of service:
6
Please enter your current salary:
200

Your new salary is 210.00


text:
Q: compareGroups table with knitr - how to adjust table head and subtext? I just discovered the wonderful package compareGroups and I think this may help me a lot in the future. So far, it is working brilliantly in combination with Knitr/Sweave:
\documentclass{article}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% LaTeX packages needed for compareGroups

% long tables
\usepackage{longtable}

% multi row
\usepackage{multirow}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\begin{document}

% R code
<<results = "asis">>=

library(compareGroups)

# Very short code for bivariate descriptive table
tab <- compareGroups(vs ~ . , data = mtcars)
export2latex(createTable(tab))

@

\end{document}

produces

I have only two concerns which is i) the modification of the table head (e.g. I want to print "P value" instead of "p.overall") and ii) adding a multicolumn subtext (e.g. "t-test was used to calculate P values."). If I just exported the table to LaTeX Code, it would be easy to modify head and subtext but in combination with Knitr I don't know how to deal with it. I just really would appreciate this wonderful solution over laborious functions in combination with e.g. Xtables package.
Thanks so much for your help!

A: Concern i) can be dealt with by manually reassigning the name of the 3rd column of matrix tab$descr prior to calling export2latex. Concern ii) might be addressed alternatively by placing the text in a caption (it seems to me more appropriate -- and further I have no idea about how to stick that into a multicol subheader).
tab <- compareGroups(vs ~ . , data = mtcars)
tab <- createTable(tab)
colnames(tab$descr)[3] <- "P value"
export2latex(tab, caption="$t$-test was used to calculate $p$ values.",
             loc.caption="bottom")

Regarding your request (below) to add, in fact, two captions (a numbered caption above the table and a non-numbered explanatory sub-text below the table), one way to achieve this is to encapsulate the longtable produced by export2latex within a (possibly centered) minipage environment, and placing the second caption as ordinary text below the table:
\documentclass{article}
\usepackage{longtable}
\usepackage{multirow}

\begin{document}

See Table~\ref{tab:complicated} for the main results of this paper.
\begin{center}
  \begin{minipage}[c]{0.5\textwidth}

<<results = "asis", echo=FALSE>>=

library(compareGroups)

tab <- compareGroups(vs ~ . , data = mtcars)
tab <- createTable(tab)
colnames(tab$descr)[3] <- "P value"
export2latex(tab, caption="Characteristics of the patients at baseline$^*$.",
             label="tab:complicated"
             )
@
{\footnotesize $^*$A two-sided $t$-test was used to calculate the $p$ values.}
\end{minipage}
\end{center}

\end{document}

References:
https://tex.stackexchange.com/questions/15282/tabular-title-above-and-caption-below


text:
Q: Defining a pair of cofixpoints by mutual corecursion Is there an easy way define two cofixpoints in a way that lets you output both of them at the same time? Ideally I would like something like the following:
Require Import Streams.

Definition alts : Stream bool * Stream bool :=
  cofix a := Cons false b with
        b := Cons true a for (a,b).

However, it seems that Coq only allows you to return one of the identifiers from a block of mutual cofixes.  The best I can do right now is the following:
Definition alts2 : Stream bool * Stream bool :=
  let a := cofix a := Cons false b with
                 b := Cons true a for a in (a,Cons true a).

Of course, this is not ideal because I need to then repeat the definition of b.  Is there a better way?

A: A workaround would be to use CoFixpoint to mutually define a and b and then reuse those to define alts.
CoFixpoint a : Stream bool := Cons false b
with b : Stream bool := Cons true a.

Definition alts : Stream bool * Stream bool := (a, b).

The downside of this approach is that we pollute the namespace with new names a and b.