__buildin_expect and if condition behaviour - linux

I wonder how they achieved || functionality with (&& and unlikely) in the below piece of code.
if (unlikely(!arch_get_random_seed_long(&v)) && unlikely(!arch_get_random_long(&v))) {
break;
}
As per design, if arch_get_random_seed_long gets value &v there is no need to fill the value again in arch_get_random_long(). This piece of code working fine.
But, how do 'unlikely' achieve this. Skipping the remaining code after && once [unlikely(!0)] is achieved.
Thanks,
Paavaanan

Related

Typescript Multi Dimensional Array's Values Not Updating (to null)

What I am Doing
I am trying to create a Sudoku solver and generator in Vue. Right now, I have the solving algorithm set up, and just need to generate new problems. I am generating problems by creating a completed Sudoku problem (complete with no bugs), then I have to remove nodes so that there is still only 1 solution to the problem.
The Problem
When I try to access a node from the multi-dimensional array that represents the board, and change it to null (what I am using to display a blank node), the board does not update that value. I am changing it with the following code: newGrid[pos[0]][pos[1]] = null; (where pos[0] is the row, pos[1] is the column , and newGrid is grid we want to mutate). Note that the array is an array with 9 arrays inside, and each of those arrays has 9 numbers (or null) which represent the values for that position in the grid. To elaborate on the bug, if I put a console.log(newGrid), there are normal looking values, and no null.
What I Know and Have Tried
I know it has to do with this specific line, and the fact that I am setting the value equal to null because changing null to another value (i.e. newGrid[pos[0]][pos[1]] = 0;) works and changes the array. The reason I don't just use a value other than null is: null renders and nothing and other values (0) render as something (null nodes should be blank), null is simple to understand in this situation (the logic is node has null, node has nothing, node is blank), and null is already implemented throughout my codebase.
Additionally, if I use console.log(newGrid[pos[0]][pos[1]]), null (the correct output) is outputted, even though console.log(newGrid) shows a number there, not null. Also, oddly enough, this works for one specific node. In row 1 (indexing starts at 0), column 8, null is set. Even though the input (completed) grid is always different, this node is always set to null. Edit: this bug had to do with the input grid already having null here, so it actually doesn't let any nulls be set.
To summarize: I expect an array with a null in a few positions I update, but I get a number instead. Also, there are no errors when the Typescript compiles to Javascript or during runtime.
Code
Given that I am not exactly sure where the problem may be (i.e. maybe I create the array wrong) I am including the minimum code with a pastebin link to the whole file (this is the full code). To restate, the goal of this function is to remove nodes from the list (by replacing them with null) in order to create a Sudoku puzzle with one solution. The code on Stack Overflow only includes some of the whole file, and the pastebin link includes the rest.
//global.d.ts
type Nullable<T> = T | null;
type Grid = Array<Array<number | null>>;
import { Solver } from './Solve';
// Inside the function that does the main work
const rowLen: number = grid.length;
const colLen: number = grid[0].length;
let newGrid: Grid = grid; // Grid is a argument for this function
let fullNodes = GetFirstFull(grid, colLen, rowLen);
let fullNodesLen: number = fullNodes.length;
// Some stuff that figures out how many solutions there are (we only want 1) is excluded
if (solutions != 1) {
fullNodesLen++;
rounds--;
} else {
newGrid[pos[0]][pos[1]] = null;
}
Note that if anything seems confusing check out the pastebin or ask. Thank you so much for taking the time to look at my problem!
Also, it isn't just 0 that works, undefined also makes it set correctly. So, this problem seems to be something with the null keyword...
EDIT:
Given that no one has responded yet, I assume: my problem is a bit hard, there isn't enough information, my post isn't good quality, or not enough people have seen it. To control the problem of not enough information, I would like to include the function that calls this function (just to see if that might be related).
generate(context: ActionContext<State, any>) {
let emptyArray = new Array(9);
for (let i = 0; i < 9; ++i)
emptyArray[i] = [null, null, null, null, null, null, null, null, null];
const fullGrid = Solver(emptyArray);
const puzzle = fullGrid ? Remover(fullGrid, 6) : state.gridLayout;
context.commit('resetBoard', puzzle);
},
Note: If you aren't familiar with Vuex, what context.commit does is changes the state (except it is changing a global state rather than a component state). Given that this function isn't refactored or very easy to read code in the first place, if you have any questions, please ask.
To solve other potential problems: I have been working on this, I have tried a lot of console.log()ing, changing the reference (newGrid) to a deepcopy, moving stuff out of the if statements, verifying code execution, and changing the way the point on the newGrid is set (i.e. by using newgrid.map() with logic to return that point as null). If you have any questions or I can help at all, please ask.

How to prevent loops in jointjs / rappid

I'm building an application which uses jointjs / rappid and I want to be able to avoid loops from occuring across multiple cells.
Jointjs already has some examples on how to avoid this in a single cell (connecting an "out" port to an "in" port of the same cell) but has nothing on how to detect and prevent loops from occuring further up in the chain.
To help understand, imagine each cell in the paper is a step to be completed. Each step should only ever be run once. If the last step has an "out" port that connects to the "in" port of the first cell, it will just loop forever. This is what I want to avoid.
Any help is greatly appreciated.
I actually found a really easy way to do this for anyone else who wishes to achieve the same thing. Simply include the graphlib dependancy and use the following:
paper.on("link:connect", function(linkView) {
if(graphlib.alg.findCycles(graph.toGraphLib()).length > 0) {
linkView.model.remove();
// show some error message here
}
});
This line:
graphlib.alg.findCycles(graph.toGraphLib())
Returns an array that contains any loops, so by checking the length we can determine whether or not the paper contains any loops and if so, remove the link that the user is trying to create.
Note: This isn't completely full-proof because if the paper already contains a loop (before the user adds a link) then simply removing the link that the user is creating won't remove any loop that exists. For me this is fine because all of my papers will be created from scratch so as long as this logic is always in place, no loops can ever be created.
Solution through graphlib
Based on Adam's graphlib solution, instead of findCycles to test for loops, the graphlib docs suggests to use the isAcyclic function, which:
returns true if the graph has no cycles and returns false if it does. This algorithm returns as soon as it detects the first cycle.
Therefore this condition:
if(graphlib.alg.findCycles(graph.toGraphLib()).length > 0)
Can be shortened to:
if(!graphlib.alg.isAcyclic(graph))
JointJS functions solution
Look up the arrays of ancestors and successors of a newly connected element and intersect them:
// invoke inside an event which tests if a specific `connectedElement` is part of a loop
function isElementPartOfLoop (graph, connectedElement) {
var elemSuccessors = graph.getSuccessors(connectedElement, {deep: true});
var elemAncestors = connectedElement.getAncestors();
// *** OR *** graph.getPredecessors(connectedElement, {deep: true});
var commonElements = _.intersection(elemSuccessors, elemAncestors);
// if an element is repeated (non-empty intersection), then it's part of a loop
return !_.isEmpty(commonElements);
}
I haven't tested this, but the theory behind the test you are trying to accomplish should be similar.
This solution is not as efficient as using directly the graphlib functions.
Prevention
One way you could prevent the link from being added to the graph is by dealing with it in an event:
graph.on('add', _.bind(addCellOps, graph));
function addCellOps (cell, collection, opt) {
if (cell.isLink()){
// test link's target element: if it is part of a loop, remove the link
var linkTarget = cell.getTargetElement();
// `this` is the graph
if(target && isElementPartOfLoop(this, linkTarget)){
cell.remove();
}
}
// other operations ....
}

Antlr4 - gated semantic predicates

Since Antlr4 no longer supports gated semantic predicates, I came up with a workaround. However, if anyone has run into this, I would like to know if there are any caveats to doing something like this and also am I following best practices.
I'm following the standard 'C' if statement in the form of:
if (evaluation) {
...code block
}
Here is the code in the code block:
if ($result == false) { // If the statement evealuates to false
// Consume tokens until the end of block marker
while (getCurrentToken().getText().compareTo("}") != 0){
consume();
}
// Set the parser state as if it had executed the tokens
_localctx.start = getCurrentToken();
_ctx.start = getCurrentToken();
setState(220);
_errHandler.sync(this);
consume(); // Consume the end of block marker
return _localctx; // Exit the rule
}
I figure that Terrance Parr must have had a good reason to take out the support for a gated semantic predicate and this seems like a simple workaround. I'm just wondering if I'm missing something.
I tested it and it works, even with an 'else'. I have not tried it with compound evaluation statements (ie conditions separated with '&&' or '||'. I have a high confidence that it will work though.

NotesXSPDocument and NotesDocument

I have created a function in SSJS Library. Because I use it in more than one XPages.
When I call this function behind a button I cannot see the value in the field
If I print it out I can see the value at the Admin Console but cannot see it in the form Even if I get page with full refreshed.
Actually my another question is.. is it possible to compare notesXSPDocument and NotesDocument. Maybe someoen can say that what is the best way for that?
function deneme(document1:NotesXSPDocument,otherDocfromOtherDatabase:NotesDocument)
{
//do staff here
if (document1.getItemValueString("field1")==otherDocfromOtherDatabase.getItemValueString("field2"))
{ //do some staff here...
document1.replaceItemValue("fieldName","FieldValue");}
}
You can compare item values from Document and XSPDocument, just be careful with the type you are comparing.
In your code you are comparing 2 javascript strings with == operator.
The code seems to be OK, just remember to save the document1 after the changes and maybe check that the items have some value.
var valueFromXspDoc = document1.getItemValueString("field1");
var valueFromDoc = otherDocfromOtherDatabase.getItemValueString("field2");
if (valueFromXspDoc && valueFromDoc && (valueFromXspDoc === valueFromDoc)) {
// stuff here...
document1.replaceItemValue("fieldName","FieldValue");
document1.save();
}
Don not compare it with == sign. A better way is to document1.getItemValueString("field1").equals(otherDocfromOtherDatabase.getItemValueString("field2"))

Kohana 3.0 - Validate: Error if one of fields aren't empty

I have four fields. Lets call them a, b, c and d. I need to validate them.
Error is when:
One til three fields are not empty;
Error is not when:
All fields are not empty,
All fields are empty;
Any neat solution here? Thanks in advice.
Edit:
Only relationships are that all four variables are prefixed with event_. It gives me event_name, event_description etc..
Edit #2:
At the moment I have something like...
if (
!empty($values['event_date'])
&& !empty($values['event_time'])
&& !empty($values['event_name'])
&& !empty($values['event_description'])
) {
It checks that all fields are filled up and then, if that's true, adds event.
As I said before, I need to display user-friendly error when some field isn't filled up (for example, user had forgot to enter description). Anyway, when all fields are filled up (it means - all okay) or when no fields are filled up (it means - user ignores event adding and don't want to add one) - no error should be displayed.
I could write code with 16 'if' statements, but isn't there any better way? :)
This isn't beautiful, but as long as you have something unique about the fields you want to check (such as "event_..."), you could loop through the variable array ($values, $_POST, etc) and check only the fields that matter. Then, you can easily check for an all or none situation.
Here is a quick example:
$total = 0;
$filled = 0;
foreach($values as $field => $val) {
if(strpos($field,'event_') === 0) {
$total++;
if( ! empty($val)) {
$filled++;
}
}
}
if($filled == 0 OR $total == $filled) {
//PASS VALIDATION
} else {
//FAIL VALIDATION
}
Is there a relationship between one of the entered values and the none entered values??
could you just parse it as an empty value?
if ( ! isset($post->a) ) $post->a = '';

Resources