what kind of relationship is there between a common wall and the rooms that located next to it?

Question: I want to know whats the Relationship between a common wall (that are located In an adjoining  room ) and the rooms.
As i know the relationship between a room and its walls is Composition not Aggregation (am i right ?)
And according to the definition of Composition the contained object can't be shared between two containers, whereas in aggregation it is possible.
now i am confused that whats the best modeling approach to represent the relationship between a common wall and the rooms located next to it ?
It would be highly Appreciated if you could provide your advices with some code.
|--------|--------|
Approch1:
(wall class ---- room class) /Composition

Approach2:
wall class ----- room class /Aggregation

Approch3:
we have a wall class and a Common wall class , Common wall class inherits from wall class
adjoining room class ---- (1) Common wall class /Aggregation
adjoining room class ---- (6) wall class / composition

Approach4:
I am a developer not a designer :) so this is my idea :
class Room
{
  private wall _firstwall  ;
  private wall _secondtwall;
  private wall _thirdwall  ;
  private wall _commonwall ;

public Room( CommonWall commonwall)
 {
 _firstwall=new Wall();
 _secondtwall=new Wall();
 _thirdwall=new Wall();
 _commonwall=commonwall;
 }

}

Class CommonWall:Wall
{
 //...
}

//   in somewher :
 static void main()
{
  Wall _commonWall=new Wall();
  Room room1=new Room(_commonWall);
  Room room2=new Room(_commonWall);
  Room [] adjacentRoom =new Room[2]{room1,room2};
}

Edit 1: I think this is a clear question but just for more clarification :
The point of the question is to find out  whats the best pattern or approach to model a relationship  for an object that is a component of two other  objects in the same time.
and about my example : waht i mean by a "room" ?,surely i mean an enclosed square room   with 4 walls and one door.but in this case one of these walls is a common wall and is shared between two adjacent rooms.
Comment: I guess I am confused. in this scenario, can a room only have one common wall?
Comment: Why does it really matter whether it's composition or aggregation?
Comment: The appropriate solution might depend on what you need to do with the data. Is there an RDBMS involved? Relate rooms and walls via a many-to-many relationship? Maybe you only track walls, and derive rooms based on distinct sets of walls. Common walls are walls that appear in more than one set? Room.Walls; Wall.Rooms; Track both all the parent rooms a wall belongs to and all that walls that make up each room. Do rooms have to be enclosed spaces?
Comment: This question may be better suited to http://programmers.stackexchange.com/ as this question isn't a specific 'solvable' problem, but more one of programming theory.
Comment: @Don it matters if you're worried about the lifecycle of your objects, quite a lot. Composition implies that all child objects may be disposed when the parent is disposed but aggregation is the opposite; think of the difference between your database code getting a connection from a pool rather then creating/destroying one each time your database class is instantiated.
Comment: It would be helpful to understand what you are trying to achieve. It looks like you are trying to understand real world environments using the language of programming. In the real world, a room does not have a **reference** to four walls as shown in approach 4. And my lounge room and dining room are both rooms but they don't have 4 walls each because they join without a common wall.
Comment: @Michael I believe he's referring to an old metaphor that conceptualises the wheres and whys of a good OO design. See: http://is.gd/x1T0vS
Comment: @NathanTregillus : if we could address this issue with only one common wall ,its possible to extend the solution for more of them, any way whats your suggestion for this specific case ? thanks
Comment: @ulty4life: you mentioned to an important point , we need a bidirectional relationship ,as the room knows about its walls , the walls or at least the common wall must know about its room(s), and about your question , if i understand it well , i must say yes , i mean  two rooms that are conjoined to each other and and separated by a common wall.anyway based on this information whats your suggestion?thanks
Comment: @Michael : dear michael what do u  mean by that ? as you know many of OO Concepts are inspired by the real world , could u please remember the first time that u heard about composition Agg and Asso , i am not sure but i know for many people it came with some real world example such as  Car , Company ,University, department , Room , and ..., and in many books we can see them , so i think its a normal thing to think about them elaborately.and based on my knowledge one of the best way to implement  composition is creating the part objects in the whole object do u know any better way ?
Comment: Hello @siamak - I didn't mean offence, just trying to understand what your question is about. OO is often explained in terms of real world things (Man and Woman both subclass Person), but you can come unstuck trying to explain real world things using OO. In the real world some people have only one arm, or no legs, or eleven fingers. Stack Overflow is meant for concrete programming questions, not discussions. Discussions tend to get closed pretty quickly by moderators. As mentioned by Russ, maybe you should post the question on [Programmers StackExchange](http://programmers.stackexchange.com/).
Comment: @Michael , Hi , U are right , but i think my question is clear , please look at this issue as a problem , how do u model such a thing ? is that ok? , i think Uml  definitions of Relationships is  poor , incomplete and imperfect , if not could u please guide me , i am interested in finding a good explanation for such a thing thanks
Comment: I think rooms should always be fully enclosed spaces. E.g. a square room would always have 4 walls. One of those walls however, could just have a really large "door" opening defined in the wall. That would cover the square room with 3 walls case, and allow you to model the empty wall as common between two rooms.
Comment: Can you tell us, once you have the rooms and walls modeled, what you need to do with them? What you need to do will help define what kind of data structure you need. Extreme flexibility likely has trade-offs of a more complex data structure and increased processing time.
Comment: @ulty4life :Yes , what u described about a room is  exactly what i meant by a room and about your next command , The question is result of a discussion that i had with one of my colleague .just out of curiosity , its important for me to find out the answer .
Answer: The answer to your question about the room and the wall is the answer to this question: "Can the wall exist without the room?"
I believe your scenario is using aggregation. Can the wall exist without the room? Sure it can. One could destroy the room by destroying three walls, but that remaining wall stands on its own. I think we're down to semantics now. This answer can change depending on how you view the walls in your scenario.
This link shows a concise way to think about it:

A "owns" B = Composition : B has no meaning or purpose in the system without A
A "uses" B = Aggregation : B exists independently (conceptually) from A

Same here:
Aggregation implies a relationship where the child can exist independently of the parent. Example: Class (parent) and Student (child). Delete the Class and the Students still exist.
Composition implies a relationship where the child cannot exist independent of the parent. Example: House (parent) and Room (child). Rooms don't exist separate to a House
From wikipedia:
Aggregation differs from ordinary composition in that it does not imply ownership. In composition, when the owning object is destroyed, so are the contained objects. In aggregation, this is not necessarily true. For example, a university owns various departments (e.g., chemistry), and each department has a number of professors. If the university closes, the departments will no longer exist, but the professors in those departments will continue to exist. Therefore, a University can be seen as a composition of departments, whereas departments have an aggregation of professors. In addition, a Professor could work in more than one department, but a department could not be part of more than one university.
Comment: I think I know the concepts that u mentioned , but based on This Concepts its hard to make a good decision for modeling such a problem,I think there is so many paradoxes here , if you destroy or delete the whole object (I mean the Room )the wall will no longer exist ,in fact it dosnt make sense so the relationship could be Composition from this point of view , on the other hand,in this example  we can see that there is one Common instance at part section that is shared between two whole objects ,and as far as i know this is not permitted in the composition,so which option is correct to choose?
Comment: @siamak I believe your scenario is using aggregation. Can the wall exist without the room? Sure it can. One could destroy the room by destroying three walls, but that remaining wall stands on its own. I think we're down to semantics now. This answer can change depending on how *you* view the walls in *your* scenario.
Answer: There is many to many relationship between Room and Wall. (one wall can be used in two rooms and one room can have many walls.
Instead of having a class like "CommonWall", I would suggest resolve this many to many with with Mapping object and two 1-Many relationships.
public class Room
{
public List<Wall> Walls{get;set;}

}

public class Wall
{
decimal length;
decimal width;
public List<Room> Rooms{get;set;}
}

public class RoomWallMapping
{
public int MappingID;
public Wall {get;set;}
public Room{get;set;}
}

Answer: Bob Horn made a point here, when a wall can exist independently from the room it has to be an aggregation.
But remember that you model how you want to see / manipulate them, so you can also decide that you mainly care about your rooms and see the walls as a side effect of the room, then this is a composition.
Aggregation model
You build the wall and that defines your rooms, your room is the just the space between the walls.
Thinking that way, the room does not need to have 4 walls, it's just an arbitrary set of walls: an open room can have 3 walls and a L shapes closed room might have 6.
This is the representation an architect or a builder will adopt.
Composition model
You want to see a room as a space with walls, then what you really care about is the view of the wall from the inside side of the room. In that case you do not car if the other room has a common wall, when you destroy your room, the inside side of the wall disappears with it.
A shared wall becomes an aggregation of two room-walls.
This might be the correct representation if you are planning an exhibition and want define where paintings will be placed.
Model what best fit your needs
In the end you model a representation and thus a simplification. Similarly there is no correct or best answer when modeling your representation, you should model your representation after your needs.
If you want to buy a car you tend to define book as composed of its pages, when you dispose it you dispose every pages.
If you want to print a book you tend to spare parts you as aggregating folios composed of pages, if a folio is misprinted you can take another from the stock to assemble to final book.
Answer: It depends.  There is always two sides to a wall. ;-)
In this sort of scenario I would use either use property injection or constructor injection, e.g.
public class Room
{
    public List<Wall> Walls { get; set; }
    public Room ( IEnumerable<Wall> walls )
    {
        Walls = new List<Wall>(walls);
    }
}

And then use a creational pattern such as a builder pattern to construct the rooms using the shared walls.
Answer: How you deal with Rooms and Walls depends on the task at hand.
I'll illustrate this with two examples, and then I'll get back to giving my answer to the actual "point" of your question.
First Approach (Navigating a 1 story Building):
Objective: I want to tell a Robot to move from its current location to the Copy Room.
I determine the dimensions of the building, say 100 ft, by 100 ft. Choose an axis, and make a grid of points. The robot may start at location (50,50). Next, I create a Graph where each edge represents one step to North, East, South, or West from that node to the corresponding node. Nodes separated by a wall have infinite weight, i.e. can't be passed through.
The Graph is represented in an adjacency-list.
Now I define a Room to be a polygon and list its verticies. To test if the robot is in the room, it must be within the area defined by the room's polygon. In this case rooms can overlap, especially since in real life standing in the doorway could mean you are in either room.
My robot can now navigate the building, move furniture, and whatever else it wants to do.
Second Approach: (Object Oriented)

Building

Properties

Width, Length, Height, Geo-Spacial Coordinates, Age, etc.

OuterWalls

may be BrickWall, GlassWall, ConcreteWall, etc inherited from OuterWall
Properties: location, thickness, etc
Methods: DemolishWall(), PaintExterior( Color C ), etc.

InteriorWall

May be NorthSouthWall or EastWestWall.
Properties: hasDoorway, N/E color, S/W color, etc.

Room

Properties: Name, Location, Width, Length, etc.

Notice that in neither of these examples do the rooms directly refer to their walls.
Now to the actual point of your question. If two objects have a shared resource how should that be taken care of.
Parallel programming deals with shared resources in a variety of different ways.

Give each object a reference to the shared resource, make sure to synchronize or otherwise deal with concurrent behavior on the shared resource.
Make the shared resource available to each object as a global variable or through a singleton object, or a static resource in another class, or even a specific location in memory or file system.
Pass the shared resource between the concurrent parts in a predefined order or at predefined times.

Imagine a hotel with a shared bathroom between each two rooms:
HotelGuest A = new HotelGuest( new BusinessMan() );
HotelGuest B = new HotelGuest( new Programmer() );

A.Room = 101;
A.Bathroom = 7;
A.BathroomKey = getBathroomKey(7);

B.Room = 102;
B.Bathroom = 7;
B.BathroomKey = getBathroomKey(7);

//Asynchronously
A.RunDoBusinessStuff();
B.RunProgrammerStuff();

//but each has to lock bathroom7 when they use it, or it could be embarrassing.

But in the above example, how does the bathroom know which two HotelGuests have its key?

create a database with the current guests and the keys they have, and the bathroom can query the database (or list).
store references to A and B in the bathroom properties. (imagine a white-board in the bathroom listing its 'tenants').
Answer: If this was anything close to real problem, I don't think I'd want to compose the Room from plain Walls. It's more likely I'd have collection of RoomComponents or IRoomComponents that would be injected using constructor injection or property injection. There is also possibility of using injection framework for composing the Room, so that the framework takes care of lifetime of the objects.
If for a second I'd imagine that the problem was really so simple that there were just Room and Walls, then I guess your approach #4 looks like the way to go. I am not sure what would be a proper name to that, as you have both Aggregation and Composition in there. Another way is to set the common wall as a property(property injection as mentioned above), instead of passing through constructor.
And finally if I go into fantasy world like some others in this thread, then I quickly come to realize all your walls should be common walls! Say someone build another three walls around one of the walls of an existing room -> bam you have a new a room, and a new common wall. What to do now? You would probably want to change the existing wall to a new CommonWall right? So it seems inevitable having walls as properties in this case, otherwise every time you decide to construct a neighbor room, you'd have to recreate all neighboring rooms.


Split IProgressMonitor Asynchronously

Question: I want to create my own ISearchQuery that delegates the actual search to a couple other searches. I'm expecting that only one of the other searches will actually find something, that's why I want to run them asynchronously.
However I'm struggeling with how to achieve that goal. The standard way in Eclipse would probably be to use jobs:
@Override
public IStatus run(final IProgressMonitor monitor) throws OperationCanceledException {
    for (Delegate delegate : delegates) {
        Job job = new Job(delegate.getName()) {

            @Override
            protected IStatus run(IProgressMonitor monitor) {
                delegate.run(monitor);
                return Status.OK_STATUS;
            }
        };
        job.schedule();
    }
    return Status.OK_STATUS;
}

That's asynchronously alright, but the problem here is that since each job has its own IProgressMonitor, the parenting search can't get any information about how the progress is coming along (except for "finished" when the job is done). Also I'm not sure if these jobs even get executed at the same time, from what I've seen they get executed one after the other normally.
I found the SubMonitor and it looks promissing:
@Override
public IStatus run(final IProgressMonitor monitor) throws OperationCanceledException {
    SubMonitor subMonitor = SubMonitor.convert(monitor, delegates.size());
    for (Delegate delegate : delegates) {
        SubMonitor delegateMonitor = subMonitor.split(1);
        delegate.run(delegateMonitor);
    }
    return Status.OK_STATUS;
}

However now I'm struggeling with how to get this to work asynchronously.
I might be able to combine both of these approaches, ignoring the job's IProgressMonitor, but it feels like cheating.
What is the best way to split a IProgressMonitor into asynchronous tasks?
Answer: I haven't run into such situation myself, so my thoughts are not backed by practical experience.
My first choice would be to schedule a single Job and share a single progress monitor among all asynchronous tasks. A task would only be allowed to report the amount of work done (i.e. call worked()). beginTask() and done() would only be called from the Job, like sketched in your second snippet.
With the exception of FutureProgressMonitor, none of the IProgressMonitor implementations that I have come across seems to be thread safe.
Therefore, you would need to implement a thread-safe wrapper.or look into FutureProgressMonitor whether that fits.
In addition, the Job would need to wait for all tasks to finish. Maybe returning Job.ASYNC_FINISH from the Job's run() method also works, but I haven't used that myself so far.

Split IProgressMonitor Asynchronously


Linux command piping in openssl to use string input

Question: I have a shell script where a file path $path have some text which I encrypt as below and it works:
content_sha256="$(openssl dgst -binary -sha256 < $path | openssl enc -e -base64)";
The value of variable content_sha256 works correctly.
Now, I have a string $body which I want to encrypt. I am trying below but it gives me entirely different result.
content_sha256="$(echo $body | openssl dgst -sha256 | openssl enc -e -base64)";
Am I piping something wrong or option for openssl should be different?
Comment: `echo` adds a newline after the text. try `echo -n $body`
Comment: Tried without -n also. No success.
Comment: **it's the `-binary`.** Your first command has `dgst` with `-binary` and the second doesn't, so it outputs totally different output resullting in totally different base64.
Answer: Correct answer below
content_sha256="$(echo $body | openssl dgst -binary -sha256 | openssl enc -e -base64)";
Points to note:

Include -binary option.
Instead of redirection of file content as input, use echo $body with pipe .


Finding $p^\textrm{th}$ roots in $\mathbb{Q}_p$?

Question: So assume we are given some $a\in\mathbb{Z}_p^\times$ and we want to figure out if $X^p-a$ has a root in $\mathbb{Q}_p$. We know that such a root must be unique, because given two such roots $\alpha,\beta$, the quotient $\alpha/\beta$ would need to be a non-trivial $p^\textrm{th}$ root of unity and $\mathbb{Q}_p$ does not contain any.
Now we can't apply Hensel, which is the canonical thing to do when looking for roots in $\mathbb{Q}_p$. What other approaches are available?
Comment: Start with the direct sum decomposition: $$\mathbf{Q}_p^*\simeq \langle p\rangle\times\mu_{p-1}\times U_1,$$ where $U_1$ consist of $p$-adic integers congruent to 1 modulo $p$. The first two factors are easy. The last one you need to work on.
Answer: Let $p$ be an odd prime. Then $\mathbb{Z}_p^{\times} \cong \mathbb{Z}/(p-1) \oplus \mathbb{Z}_p.$ The pro-$p$ sylow of $\mathbb{Z}_p^{\times}$ is $1 + p\mathbb{Z}_p$ and is isomorphic (as a topological group) to $p\mathbb{Z}_p$ via the $p$-adic logarithm. Since $1 + p^2\mathbb{Z}_p$ is a closed subgroup of $1 + p\mathbb{Z}_p$ of index $p$ it must be the case that $1 + p^2\mathbb{Z}_p$ is the pullback of $p^2\mathbb{Z}_p$ under the logarithm. From this it follows
$$ 1 + p^2\mathbb{Z}_p = (1 + p\mathbb{Z}_p)^p.$$
And therefore,
$$(\mathbb{Z}_p^{\times})^p = \mu_{p-1}(1 + p^2\mathbb{Z}_p).$$
Now consider an element $x \in \mathbb{Q}_p^{\times}$ and recall $x = ap^n$ for some $a\in\mathbb{Z}_p^{\times}$ and $n\in\mathbb{Z}.$ Then $x$ has a $p$-th root in $\mathbb{Q}_p$ if and only if $a$ has a root in $\mathbb{Z}_p^{\times}$ and $p|n.$
Hence,
$$(\mathbb{Q}_p^{\times})^p = \mathbb{Z}_p^{\times}\langle p^p \rangle = \mu_{p-1}(1 + p^2\mathbb{Z}_p)\langle p^p \rangle.$$
Now try to answer the question for $p =2.$
Answer: Since $a^p \equiv a\ ({\rm mod}\ p)$, we can replace $a$ by $a/a^p$ and just consider the case $a \equiv 1 ({\rm mod}\  p)$.  Now we can still use Hensel's Lemma, just not in the trivial form.  We need the general form that if we can find an approximation with $|f(a_0)| < |f'(a_0)|^2$, then $f$ has a root.  See the example at Wikipedia in which the case $p=3$ is worked out.  In general, if $c \in \mathbb{Z}_p$ and $c \equiv 1 ({\rm mod}\ p)$ then $c$ has a $p$th root in $\mathbb{Z}_p$ iff it has a $p$th root mod $p^2$, except when $p=2$, where you have to check mod 8.
Answer: Let's take $\alpha\equiv 1\mod p^2$. Then $\alpha = 1 + p^2\beta\in\mathbb{Z}_p$, where $\beta\in\mathbb{Z}_p$. What we want to do is make Hensel's lemma work for us, after changing the equation a bit. We have $f(x) = x^p - \alpha = x^p - (1 + p^2\beta)$. We see that if $x$ is to be a solution, it must satisfy $x\equiv 1\mod p$, so $x = 1 + py$ for some $y\in\mathbb{Z}_p$. Now we have a new polynomial equation:
$$
f(y) = (1 + py)^p - (1 + p^2\beta) = \sum_{i = 0}^p \begin{pmatrix} p \\ i\end{pmatrix}(py)^i - (1 + p^2\beta),
$$
which reduces to
$$
f(y) = \sum_{i = 1}^p \begin{pmatrix} p \\ i\end{pmatrix}(py)^i - p^2\beta.
$$
So long as $p\neq 2$, we can set this equal to zero and cancel a $p^2$ from each term, and get
$$
0 = p^2 y + \begin{pmatrix} p \\ 2\end{pmatrix}(py)^2 + \ldots + (py)^p - p^2\beta = y + \begin{pmatrix} p \\ 2\end{pmatrix} y^2 + \ldots + p^{p-2}y^p - \beta.
$$
Mod $p$, we can solve this equation:
$$
y + \begin{pmatrix} p \\ 2\end{pmatrix} y^2 + \ldots + p^{p-2}y^p - \beta \equiv y - \beta \equiv y - \beta_0\mod p,
$$
where $\beta = \beta_0 + \beta_1 p + \beta_2 p^2 + \ldots$ by $y = \beta_0$. Mod $p$, our derivative is always nonzero:
$$
\frac{d}{dy}\left[y - \beta_0\right] \equiv 1\mod p,
$$
so we can use Hensel's lemma and lift our modified solution mod $p$ to a solution in $\mathbb{Q}_p$. Therefore, if $\alpha\in 1 + p^2\mathbb{Z}_p$ and $p\neq 2$, there exists a $p$th root of $\alpha$ in $\mathbb{Q}_p$.


How to soften half-diminished IV in a minor key

Question: I've read that in a minor key iim75b can be softened to bVII7 and vii° can be softened to V7. What do I do with a ivm75b? Can it be softened to bII7? Are there cases where this approach results in something that clearly sounds worse?
UPDATE (some context added):
The original chord progression is the following (key of A minor):
Am/E Dm75b/F C/G Dm75b/Ab Em/B Bm75b Am
I see Bm75b can be exchanged with a G7/B, but what about the Dm75b?
UPDATE2: I've added the first half of the melody line.
Comment: @herman - I'm not sure what you mean by logical.  Not all of the chords need to be from the key for a piece or section to be considered as in a key.
Comment: It depends more on which chords are either side of the 'offending' one. Soften doesn't really explain what you want to do - it's subjective anyway. m7b5 is half diminished.
Comment: I'm not sure what you mean by "softening", but "Dm7b5", or "D half diminished", is not a chord in the key of A minor, since it contains an Ab (this the b5).  So the chord progression as written isn't logical.
Comment: Welcome @Basstickler, the bass line was inspired by your teachings.
Comment: Glad to be of service!  Can you clarify what you mean by soften as well?  I assume it basically means that you would like the same function for a chord but have less dissonance, is that accurate?
Comment: @Basstickler I mean that there's no functional explanation for it, so you can't reason about another chord with the same function.  However now that he added three score, it's clear that it's not Dm7b5 but an in-between dominant.
Comment: Yes, that's correct. However for the parts with Dm75b I have Ab in the melody line.
Answer: The nature of any diminished chord is going to be harsh as just the natural spelling of the chord outlines the tritone used in it. Simple voice leading and making sure the tritone does not show up in the outer voices. This is why it is rather typical to see a diminished chord in an inversion
As to why going from iim75b to bVII7 and vii° to V7 you have to understand how these chords are related. Dominant 7ths  naturally have a diminished chord in them between the 3rd, 5th, and 7th and like I talked about earlier, the tritone is not as exposed as it is in just a diminished chord.  For example in the key of C major  vii° is B° (spelled B, D, F) and V7 is G7 (spelled G, B, D, F). The iim75b and bVII7  follow the same logic.
For the ivm75b changing it to bII7 will create the same effect as before, but this chord in general would seem out of place in most progressions as with both chords you are altering the tonic so the harshness (dissonance) of it will tend to show though even if voiced well. If that's what you're going for then it will work fine and could even lead to a modulation in the right context. If this is not what you are trying to go for, I suggest rethinking the progression at least for that one chord.
Comment: @AndrásHummer even with the edits, I'm not really understanding the progression with respect to the tonic as the progression seems to more based around E than A.
Comment: I got the iim75b->V7 and vii°->V7 part, and since you and @Holaf wondered I've added the imagined chord progression. For the first half I can draw a sheet music about how I imagine the arrangement, just give me a few hours :)
Comment: The melody would eventually land on A, only an octave higher, and the final Am has A in the bass as well. I agree it starts off a bit unstable, more like as if it were a C6/E followed by an Fm/D.
Comment: Come to think about it, though half-diminished chords tend to have a dominant taste, in the case of the IVth degree they also preserve their subdominant role, so for Dm75b an Fm borrowed from the C minor key sounds like a reasonable approach for softening.
Answer: Such softenings typically require an underlying key that enable to replace a chord by an other one that has common notes, but that makes you stay into the key. The softenings iim75b -> bVII7 and vii° -> V7 presuppose an underlying minor key in which these chords are included. However, ivm75b chords don't imply a key as clearly. It might then be necessary to have more context (surrounding chords, melody, etc.) to soften such a chord by an other.
Edit : thanks for the chord sequence. I am not sure if there are some well defined rules for this kind of cases, and you might then have to count more on your personal aesthetic criteria. That said, I would say that your first softening (Bm75b -> G7/B) would fit with the idea of privileging the A natural minor key rather than A harmonic minor (because it removes the G#). Staying on this direction, you might want to soften your Dm75b in a Dm7.
Comment: After some time thinking I realized that a iim75b (in the key of A minor, a Bm75b) can also be interpreted as a Dm6/B. In this approach for the Dm75b I can't use Bb7/D for the softening (as its root note is not part of the A minor key), but I can borrow an Fm from the C minor key, making it an Fm6/D chord.
Answer: The second chord is not D half diminished as there's no C in the score at that point.  However there's a B there, so this is F dim, which is an inversion of B dim.  So this is a dominant function to C (normally the F in the bass would resolve down to an E), which means it can be replaced by G7.  The Ab in the melody automatically makes it a G7b9.
Comment: Sure, if you wish to keep the F in the bass it would be, in proper notation, G7b9/F.  (I notice you often put the b behind the number, it's normally in front like b9 or b5, pronounced as "flat nine" or "flat five")
Comment: So you say it could be replaced with a G9b/F?
Comment: Note that the 2nd Dm7b5 is different.  I think it's also not really Dm7b5 in the first place.  Thinking in Am, the bass note makes more sense when interpreted as G# instead of Ab.  Then it's just G# diminished, having a dominant function and being almost the same as E7b9/G#.  Only the Em/B after that is a bit "weird": going from a dominant function to V minor.
Answer: So among the alterations that diminished chords go under, let's assume that your "softening" means to lower the seventh of the chord diatonically to create a dominant seventh chord. This fits all three of your example cases. In Am:
diminished chord | diminished spelling | softened chord | softened spelling
 iim7b5          |  B, D, F, A         |  bVII7         |  B, D, F, G
 vii°7           |  G#, B, D, F        |  V7            |  G, B, D, E
 ivm7b5          |  D, F, Ab, C        |  bII7          |  D, F, Ab, Bb

So let's look at other fully diminished chords. Note that there are really only three of them and most of these are enharmonic spellings to fit our definition of softening. I've tried to keep the sharps an flats as non-ridiculous as possible and general chosen to spell the diminished chords in a way that the softened chord has a more useful function if any function at all.
diminished chord | diminished spelling | softened chord | softening spelling
 im°7            |  A, C, Eb, Gb       |  bVI7          |  A, C, Eb, F
 biii°7          |  B#, D#, F#, A      |  VII7          |  G#, B#, D#, F#,
 #iv°7           |  D#, F#, A, C       |  II7           |  D#, F#, A, B
 vi°7            |  F#, A, C, Eb       |  IV7           |  F#, A, C, D
----------------------------------------------------------------------------
 #i°7            |  A#, C#, E, G       |  VI7           |  A#, C#, E, F#
 iii°7           |  C#, E, G, Bb       |  I7            |  C#, E, G, A
 v°7             |  E, G, Bb, Dd       |  bIII7         |  E, G, Bb, C
 bvii°7          |  G, Bb, Db, Fb      |  bV7           |  G, Bb, Db, Eb
----------------------------------------------------------------------------
 ii°7            |  B, D, F, Ab        |  bVII7         |  B, D, F, G
 iv°7            |  D, F, Ab, Cb       |  bII7          |  D, F, Ab, Bb
 #v°7            |  E#, G#, B, D       |  III7          |  E#, G#, B, C#
 vii°7           |  G#, B, D, F        |  V7            |  G#, B, D, E

You could do a much more in depth analysis of these chords and what scales they're associated with, but right off hand, I notice a few things. First, all of your examples are form the third group. This is to be expected as it is the most function of the three chords and is usually a dominant function. The bVII7 is in the scale, the bII7 could be considered a Neapolitan 6th chord (I'm not sure if dominant seventh disqualifies it), the III7 modulates to the relative minor if we're in a major key, and the V7 speaks for itself. As for the other chords, all of them have the obvious function of modulating to related keys. bIII7, I7, and II7 look good for that. As for functional chords within the key, I like bVI7 as an augmented sixth chord and the II7 and the IV7 look good for some modal flavor. Honestly, it may take some oddness or trickery to get these diminished chords in a progression in the first place and there definitely chords on here that sound odd, but most of the common functional diminished chords (ie the third group) can be resolved in interesting ways. Also for reference, here is the same chart with half diminished instead of whole diminished chords.
diminished chord | diminished spelling | softened chord | softening spelling
 im7b5           |  A, C, Eb, G        |  bVI7          |  A, C, Eb, F
 biii7b5         |  B#, D#, F#, A#     |  VII7          |  G#, B#, D#, F#,
 #iv7b5          |  D#, F#, A, C#      |  II7           |  D#, F#, A, B
 vi7b5           |  F#, A, C, E        |  IV7           |  F#, A, C, D
----------------------------------------------------------------------------
 #i7b5           |  A#, C#, E, G#      |  VI7           |  A#, C#, E, F#
 iii7b5          |  C#, E, G, B        |  I7            |  C#, E, G, A
 v7b5            |  E, G, Bb, D        |  bIII7         |  E, G, Bb, C
 bvii7b5         |  G, Bb, Db, F       |  bV7           |  G, Bb, Db, Eb
----------------------------------------------------------------------------
 ii7b5           |  B, D, F, A         |  bVII7         |  B, D, F, G
 iv7b5           |  D, F, Ab, C        |  bII7          |  D, F, Ab, Bb
 #v7b5           |  E#, G#, B, D#      |  III7          |  E#, G#, B, C#
 vii7b5          |  G#, B, D, F#       |  V7            |  G#, B, D, E

In general, if you're not using one of the diminished chords from the third group, the dominant function diminished chords, softening is going to be odd. But it could be very useful for modulation. Hope this gives some food for thought and I hope I didn't make too many mistakes in my charts.


How can I access a remote server with a full disk?

Question: There is a remote network which I can VPN to. On this network is a Windows Server 2008 install which I would like manage but the server's disk is full. I have tried:

Remote Desktop - fails.
Windows Explorer - fails.
net use - fails with disk space error.
Remote shutdown - fails with disk space error.

Some other things which I thought about but aren't installed are: VNC, telnet server, etc. I cannot restart the server physically.
The server is on a domain which I have administrator rights to, can I do something via Active Directory that would cause the computer to free space? Any other ideas?
Answer: Try to use some out of band management like HP ILOM or Dell DRAC.
Or may be you have a serial console enabled on the server? See: SAC
A random person with console access can be helpful too...
Answer: Try PsExec from Sysinternals' PsTools to see if you can get a remote command prompt and delete some files.
Also can you still use tasklist command line tool to access the remote system's list of running processes?  If so, then you might be able to use taskkill to terminate a program that might be holding some files one and possibly free up enough disk space to wedge in there with RDP.  Unlikely but worth a shot.
Comment: psexec copies itself over via the admin$ share and starts up as a service - it should fail on the same grounds that Windows explorer / RDP fail.
Answer: I guess the Net Use/RDP/Explorer (I assume you mean start -> run -> \\servername\c$ ? if not, try that) fail because you are trying to logon with an account which has not been logged on before / isn't currently logged on, so it's trying to write either a new account folder or update an existing one.
Do you know if an account is logged on to it which you can try logging in as or connecting as? (Even a service account). Is there anyone, e.g. a desktop user, who has a current open connection to the server who could move a file off it temporarily?
If you cannot even browse to files on it or logon at all, how do you know the disk is full? How full is it? Is there any space at all? Are there any other disks or partitions with space? Is there anybody there who can, e.g. plug in a thumbdrive or USB drive?
Does it run SQL Server? If you install the management studio locally, connect to the server, does that work? Then try http://www.kodyaz.com/articles/delete-file-from-sql-server-xp-cmdshell-ole-automation-procedures.aspx
Answer: query user /server:SERVERNAME
logoff SESSIONID /server:SERVERNAME
Should get you a little bit of space if there's a lingering user logged onto the box. The below command may be a little old, but it could work...?
AT \\SERVERNAME TIME powercfg.exe -h off
This should remove the hybernation file at a given time, then it should be accessible. Should get you 4 or more GB of space. Enough to log in at any rate.
Read more about AT here: https://support.microsoft.com/kb/313565
Comment: If you're using AT from a windows 8 or 2012 box, it won't work, but I did try it on my windows 7 VDI with success. Good luck!


What are the functionality of δ symbol and $δr^T$?

Question:
I got two questions here:

Does anybody know what is the functionality of the small delta letter δ here? Is it simply the same as the rate of change just like the big delta letter Δ?
And for the $δr^T$, does T have any special definition in mathematics or should we simply treat it as usual power variable?
Answer: The $\delta r$ is the differential of $r$. So $r_0 + \delta r$ represents a very small change away from $r_0$. See this page for more on infinitesimal differentials. When differentials are usually small, $\delta$ is used instead of $\Delta$.
The $T$ is the transpose of a matrix. In this case, $r$ is a vector and in order to get the matrix multiplication to line up correctly, it's necessary to take the transpose of $r$.


Not able to reference Javascript functions inside jQuery wrapper

Question: I have custom module called interface, through which I'm adding a javascript file. This code is in plain old javascript, no jQuery, and has been working for me.
I now want to be able to add some jQuery functions to this code, I thought this would be possible since jQuery and javascript should be compatible with each other, right?
So here's a simplified example of what I'm doing inside the .js file:
(function ($) {
    Drupal.behaviors.interface = {
    attach: function()
    {
        function foofunction() {
        // execute some code
        }
    function WelcomeScreen()
    {
        Screen.apply( this );
        this.html = function(){
        return "

";
        };
this.activate = function(){
document.getElementById("main").innerHTML = "Test";
        };
        }

    }
    }
})(jQuery)

This code results in the following error in Chrome dev tools:
Uncaught ReferenceError: foofunction is not defined

My guess is that somehow the required jquery wrapper or the drupal behaviors wrapper are causing the functions to no longer be 'global'.
One obvious answer, I think, is rewriting everything in proper jQuery syntax. But I'm interested in how to make these javascript functions compatible with jQuery.
Answer: First off, onClick misses an = sign. Secondly, Chrome is right. From the point of view of the  element, the function is not visible even though it seems to be in scope of WelcomeScreen function. That's because it's not the function that invokes it, but the element on a page. Try onClick="Drupal.behaviors.interface.foofunction()". But better off - make it unobtrusive by removing the onClick attribute and saying at the document.ready level:
(function ($) {
    Drupal.behaviors.interface = {
    // code
    }

    $(function(){
      $('#button').live('click', Drupal.behaviors.interface.foofunction);
    });
})(jQuery)

Of course this is just a rudimentary suggestion, you might want to optimize the code further. If you're using jQuery 1.7+, you'd rather use .on() than .live().
Comment: By the document.ready level, you mean inside the Drupal.behaviors? This is giving me `Uncaught TypeError: Object # has no method 'foofunction'`
Comment: adding the code to my answer for better formatting
Comment: Thanks for your help so far. So this is outside the Drupals.behaviors {} and the subsequent attach: function() {}? It's still giving me `Uncaught TypeError: Object # has no method 'foofunction' `
Comment: Oops, I guess we're missing invoking `Drupal.attachBehaviors(document)` before the `#button` line.
Comment: I'm still getting the same error.
Comment: I'm sorry, I think I should get a rest today rather than mess up someone's code. I bet it's something simple.
Comment: Arthur don't worry. Good idea, just wrong code ;)
Answer: Artur is basically right - "Drupal way " is to attach events in behaviors. Here is code I'm using without problems:
(function($) {
  Drupal.behaviors.mymodule= {
    attach: function (context, settings) {

      function test(param) {
        alert($(param).attr('token'));
      }

      $(':input', context).on('keyup change', function(){
        test(this);
      });
    }
  };
})(jQuery);

Or simpler:
(function($) {
  Drupal.behaviors.mymodule= {
    attach: function (context, settings) {

      function test() {
        alert($(this).attr('token'));
      }

      $(':input', context).on('keyup change', test);
    }
  };
})(jQuery);

Rewrite your code to that syntax, make sure you are using jQuery Update, and you should be good.


Multiple linear regression - interpretation diagnostic plots

Question: I am learning so bear with me.
Aim: I am trying to figure out if my data fit the criteria for multiple linear regression.
Context: My model has two numeric and four categoric variables.
kiva_model <- lm(lender_count ~
                   loan_usd+ #Numeric
                   sector+ #Categoric 11 levels
                   term_in_months+ #Numeric
                   borrower_genders+ #Categoric 5 levels
                   repayment_interval+ #Categoric 3 levels
                   country_code, #Categoric 59 levels
                    data=kiva_omit)

Sample size is 504,528.
I checked the correlation between the three numeric variables as follows:

loan_usd is a strong predictor or lender_count.
I have made plots to assess:
a) Linearity of numerical variables
b) nearly normal residuals
c) constant variability.
The images show the before (above) and after (below) of outlier removal using cooks_distance<4/n.
I cannot figure out if this is acceptable enough to proceed with my analysis or if I have to further manipulate the data prior the final regression.
To summarise my main concerns:

Conical shape in term_in_months vs. residuals.
Slight S-shape in Normal probability plot.
Strong line in Residuals vs. predicted.

a) Linearity of numerical variables

b) Nearly normal residuals

c) Constant variability
Residuals vs. predicted

Absolute value of residuals vs. predicted
Answer: I am unable to see the images. Based on what you have mentioned, Conical shape between term_in_months(variable) and residuals implies violation of linearity. Try to use non linear relationship between target variable (lender_count) and term_in_months. for example: use some polynomial form of order 2,3 for term_in_months. Slight S-Shape may be ignored if it is not statistically significant.If your features(Variables) are correlated (causing multicollinearity), you can use Principal component analysis to decorrelate them.
You can check all the assumptions by doing statistical test as well. for instance, Kolmogorov-Smirnov test and Anderson-Darling test are used for normality. For independents residuals, you can use Durbin-Watson test. You can check
https://www.analyticsvidhya.com/blog/2016/07/deeper-regression-analysis-assumptions-plots-solutions/.
In nutshell, try to transform your data. Box-cox transformation may help you in resolving this.


Java with AutoIt and Jacob library

Question: I'm trying to integrate AutoIt with Java using Eclipse. I have configured project and java build path properly - probable ;). The problem is that when I tried to run the project I've received and error presented below:

Exception in thread "main" com.jacob.com.ComFailException: Can't co-create object
      at com.jacob.com.Dispatch.createInstanceNative(Native Method)
      at com.jacob.com.Dispatch.(Dispatch.java:99)
      at com.jacob.activeX.ActiveXComponent.(ActiveXComponent.java:58)
      at autoitx4java.AutoItX.(AutoItX.java:181)
      at com.mainPackage.windowsGUIHandler.bleble(windowsGUIHandler.java:23)
      at com.mainPackage.windowsGUIHandler.main(windowsGUIHandler.java:39)

My code in code looks like that (quite simple but enough to run and test if AutoIT works)
<code>package com.mainPackage;

import java.io.File;
import com.jacob.com.LibraryLoader;
import junit.framework.Assert;
import autoitx4java.AutoItX;

public class windowsGUIHandler {

public static void thisIsTestFunction() {
    File file = new File("lib", "jacob-1.17-M2-x64.dll");
    System.setProperty(LibraryLoader.JACOB_DLL_PATH, file.getAbsolutePath());
    LibraryLoader.loadJacobLibrary();

    AutoItX x = new AutoItX();
    String notepad = "Untitled - Notepad";
    String testString = "this is a test.";
    x.run("notepad.exe");
    x.winActivate(notepad);
    x.winWaitActive(notepad);
    x.send(testString);
    Assert.assertTrue(x.winExists(notepad, testString));
    x.winClose(notepad, testString);
    x.winWaitActive("Notepad");
    x.send("{ALT}n");
    Assert.assertFalse(x.winExists(notepad, testString));

}

public static void main(String[] args) {
    thisIsTestFunction();
}

}
</code>
I made a research and I have found this article which describes what to do if eclipse returns Can't co-create object but when I type in cmd

regasm /verbose /nologo /codebase C:\jacob-1.17-M2-x64.dll

After this command I get an error RegAsm :  error RA0000 : Failed to load 'C:\jacob-1.17-M2-x64.dll' because it is not a valid .NET assembly
In addition I'm running on Windows 7 x64 with JRE and JDK 6 x64 installed.
Answer: Are you using
Windows 7 32 bit in a 32 bit processor machine
or Windows 7 64 bit in a 64 bit machine.
I tried registering the jacob-1.17-M2-x86.dll in my Windows 7 32 bit in a 32 bit processor machine with
regsvr32   and it worked successfully
but in my another machine with
Windows 7 64 bit in a 64 bit processor machine
neither jacob-1.17-M2-x86.dll or  jacob-1.17-M2-x64.dll got registered successfully.
and I had to use AutoItX3.dll which gets downloaded with latest AutoIT installation.
Check your configuration and try the correct files and see.

Java with AutoIt and Jacob library


Validating form data that it is a weekday

Question: I'm trying to validate a custom form field from an Ubercart module (in the checkout process). The field would specify a delivery date. The delivery date must be a business day.
How does one determine if it is a business day or not?
Are there given functions within Drupal that provide which day of the week when a response is given? Or would native php functions be the route to go with?
Answer: <code>date('w'[, $timestamp]);
</code>
gives you the days of the week as an integer from 0 (Sun) to 6 (Sat).
So you could check to see whether the chosen delivery date is 1 - 5.
I am not aware of any existing Drupal function to do this, but it's a fairly simple function to write oneself.
Comment: $timestamp is a unix timestamp?
Comment: Yes, defaults to time()


Big O notation for complex-valued functions of a real variable

Question: Let $f,g:\mathbb R\to\mathbb C$.  Is there a standard notion of $f = O(g)$?
If I had to take a stab at a definition, I'd try something like

$f = O(g)$ provided there exists $M>0$ and $x_0\in\mathbb R$ such that $|f(x)| \leq M |g(x)|$ for all $x>x_0$.

where $|\cdot|$ denotes the complex mod.
Comment: This is right, although sometimes we're interested in behavior as $x\to 0$ rather than as $x\to\infty$. Ordinarily it is clear from the context.
Comment: @TedShifrin Thank you.
Answer: You can write it like that, no problem. Even  Wikipedia is on your side: it defines $f=O(g)$ as $|f|\le M|g|$ (in an appropriate domain, for some $M$).
Some people  prefer writing $f=O(|g|)$, so that the function inside of $O$ is always nonnegative. But there is no mathematical difference here, only a matter of preference.


multiple usage of require() in Node.js return undefined results

Question: I've got really strange behavior of require() in node.js.
I have simple common.js:
module.exports = common = {
    config: require('./config/config'),
    errorCodes: require('./config/errorCodes'),
    server: require('./server/server').server,
    dbManager: require('./db/dbManager').dbManager,
    idGenerator: require('./utils/idGenerator').idGenerator
};

my server.js:
var http = require('http'),
    url = require("url"),
    common = require('../common');

var server = (function ()
{
    var server = http.createServer(function (request, response)
    {

    });

    // running server
    function startServer()
    {
        server.listen(common.config.port);
        console.log('Tracking server running at :' + common.config.port);
    }

    return {
        startServer: startServer
    };
})();

module.exports.server = server;

So, Case 1, - I'm reqiuring common only in server.js, it works:
start.js:
//var common = require('./common');
var server = require('./server/server').server;

// initialize whole server
var init = function ()
{
//    common.dbManager.init();
    server.startServer();
};

init();

And, Case 2, I'm requiring common in both modules - doesn't work:
start.js
var common = require('./common');
var server = require('./server/server').server;

// initialize whole server
var init = function ()
{
    common.dbManager.init();
    server.startServer();
};

init();

The error is that in the second case certain properies common.config and common.dbManager are undefined. Does anybody have an idea why?
Thanks in advance.
Update
Thanks guys, the following solution works:

Your 'common' model is not needed: just require modules you need
  explicitly
Answer: You have a cycle: server -> common -> server.
Node.js require() returns undefined (by design) when module that is being loaded is required again, in cycle.
Solve your cycle.
Comment: If you can't live without the cycle, than at least move actual code (like the `init`) in process.nextTick(), or even better, have one place where you call the initialization manually. Your 'common' model is not needed: just require modules you need explicitly. They are cached, so no performance loss.
Comment: I believe you're right. I'll check tomorrow and let you guys know the result.


Não contar em duplicidade os inteiros 1 e 0 quando estes estiverem acima, abaixo ou ao lado de um inteiro 2?

Question: Este código conta quantos setores ferteis (1) e inferteis (0) estão cobertos por pelo menos um irrigador (2). A matriz a[m][n] representa um terreno com irrigadores (2), terras ferteis (1) e terras inferteis:
#include <stdio.h>

int main() {
    int m, n, i, j, dx, dy, qtdFertil, qtdInfertil;
    int a[10][10];
    scanf("%d %d", &m, &n);
/*ex. de entradas:
4 6
0 0 0 1 1 0
0 2 2 1 1 0
1 0 2 1 2 0
1 1 1 0 0 0
4 5
Obs.: a saida deveria ser 4 e 5 mas está saindo 5 7
*/
    //leitura da matriz
    for (i = 0; i < m; i++) {       //varre as linhas m
        for (j = 0; j < n; j++) {   //varre as colunas n
            scanf("%d", &a[i][j]);
        }
    }
    //calcula setores ferteis/inferteis irrigados
    qtdFertil = 0;
    qtdInfertil = 0;
    for(i = 1; i < m-1; i++) {              //varre as linhas da matriz Aij
        for (j = 1; j < n-1; j++) {         //varre as colunas da matriz Aij
            if (a[i][j] == 2){
                if(a[i-1][j] == 1) {        //elemento a norte de aij
                    qtdFertil++; }
                if(a[i-1][j] == 0) {
                    qtdInfertil++; }
                if(a[i+1][j] == 1) {        //elemento a sul de aij
                    qtdFertil++; }
                if(a[i+1][j] == 0) {
                    qtdInfertil++; }
                if(a[i][j+1] == 1) {        //elemento a leste de aij
                    qtdFertil++; }
                if(a[i][j+1] == 0) {
                    qtdInfertil++; }
                if(a[i][j-1] == 1) {        //elemento a oeste de aij
                    qtdFertil++; }
                if(a[i][j-1] == 0) {
                    qtdInfertil++; }
            }else{
                continue;   //passa para a próxima iteração
            }
        }
    }
    //escreve a quantidade de setires ferteis e inferteis cobertos
    //por pelo menos um irrigador
    printf("%d %d\n", qtdFertil, qtdInfertil);
    return 0;
}

Answer: Seu programa está certo, a menos que não se possa contar os mesmos setores mais de uma vez,
Setores com zeros
  0 0
0 2 2
  0 2   2 0
        0

Se você contar as ocorrências no mapa em destaque para os zeros, verá que terão 7 ocorrências.
Setores com uns
(linha faltante)
    2 1 1
    2 1 2
    1

Verá que tem 5 ocorrências de uns.
Para que não ocorra isso, você pode ir substituindo os valores já levados em consideração, conforme exemplo abaixo:
#include <stdio.h>

#define JACONTADO  3
#define IRRIGADOR  2
#define FERTIL     1
#define INFERTIL   0

int main()
{
    int m, n, i, j, dx, dy, contagem[4];
    int a[10][10];
    fflush(stdin);
    scanf("%d %d", &m, &n);

    for (i = 0; i < m; ++i)
    {
        fflush(stdin);
        for (j = 0; j < n; ++j)
            scanf("%d", &a[i][j]);
    }

    contagem[INFERTIL] = 0;
    contagem[FERTIL] = 0;
    contagem[IRRIGADOR] = 0;
    contagem[JACONTADO] = 0;

    for (i = 1; i < m - 1; ++i)
        for (j = 1; j < n - 1; ++j)
        {
            if (a[i][j] == IRRIGADOR)
            {
                // Norte.
                ++contagem[a[i - 1][j]];
                // Sul.
                ++contagem[a[i + 1][j]];
                // Leste.
                ++contagem[a[i][j + 1]];
                // Oeste.
                ++contagem[a[i][j - 1]];

                // Substituicao dos setores ja contados.
                a[i - 1][j] = a[i - 1][j] == IRRIGADOR ? IRRIGADOR : JACONTADO;
                a[i + 1][j] = a[i + 1][j] == IRRIGADOR ? IRRIGADOR : JACONTADO;
                a[i][j - 1] = a[i][j - 1] == IRRIGADOR ? IRRIGADOR : JACONTADO;
                a[i][j + 1] = a[i][j + 1] == IRRIGADOR ? IRRIGADOR : JACONTADO;
            }
        }

    printf("%d %d", contagem[FERTIL], contagem[INFERTIL]);

    return 0;
}


Display field collection items by using twig

Question: I'm using the field collection module in Drupal 8 to encapsulate event informations so I've got a field collection with six sub fields (place, starting time, etc.).
In my twig template field--field-event.html.twig, I'd like to extract each item of the field collection and bring it separately to the view - but I can't figure it out. What's the right way to get the content of each field collection item and process it individually?
{% for item in items %}
  {{ kint(item) }}
{% endfor %}

Iterating through the field collection with above code gives me an impression that the field collection items have got a content (with #markup) and attributes but how do I get to the core/values of the field items?
Comment: I had similar 'issue' in my site. I can solve this demand by creating my own field using Field API. In my case I had to mix autocomplete (taxonomy terms), select and number fields to compound one field. Its not too hard will depend with fields you need to compound. This way you have full control of you markup and print whatever you want. I never used field-collection module, check if you have an option in module settings to render each field instead just one '#markup' element. If you have just one markup element to all sub-fields just left string manipulation to get them.
Comment: Ok, your approach sounds good and interesting to create an own field with sub fields using the Field API and not to use the field-collection module (which firstly seemed to me to be the most conveniently way to implement fields with sub fields). Do you've got some advices / URLs where to start best with implementing such an own field / module?
Comment: Sure, take a look in 'telephone' module from Drupal core. Basically you will need 3 classes, `FieldItem` - Store data, `Widget` - Configure data (when you create a field from UI), `Formatter` - Create a render element and displays data (here you can define some options to how to display too).
Answer: That is not a good idea to use kint() to collect the values somewhere in #markupkeys or other render elements. You can get the values from the field object, which is in a field collection an entity which then refers to the children fields. But if you use field collection, you should try first to use the theming, that is provided by this module. That is configure the format of the field collection in ui and then look in twig debug for the templates that are used by doing this and modify them.


A $C$-closed but non-Zariski-closed subgroup of an algebraic group

Question: Let $G$ be an algebraic group, i.e., a topological group homeomorphic to an algebraic variety. In particular, $G$ is a topological manifold. Let $H\subset G$ be a subgroup which is a closed submanifold in the manifold topology, not Zariski topology.
Questions:

How far is $H$ from being Zariski-closed, i.e., an algebraic subgroup?
How far is the homogeneous space $G/H$ from being an algebraic variety? Maybe projective variety?

It is known that a Lie group can be defined as a smooth group, but then the group structure forces it to be necessarily analytic. Because the multiplicative law in $H$ is still algebraic (that of $G$), I thought maybe this forces $H$ to be Zariski closed.
Note that I am neither an algebraist nor a geometer, so a very basic language would be appreciated. Thank you.
Comment: You seem to have an unusual definition of an algebraic group. Usually one also requires the operations to be morphisms of varieties.
Comment: One of the small examples is $H=\Bbb{Z}$ as a subgroup of the additive group $G=\Bbb{C}$. Because $H$ is infinite its Zariski closure is all of $\Bbb{C}$. Here $G/H$ is isomorphic as a Lie group to $\Bbb{C}^*$ via the mapping $\phi:z+H\mapsto e^{2\pi i z}$. But even though $\Bbb{C}^*$ is also an algebraic group, $\phi$ is not a morphism of varieties because $z\mapsto e^{2\pi iz}$ isn't.
Comment: @Bedovlat Being a morphism of varieties is a very strong condition. It's not merely topological, there's algebraic stuff going on.
Comment: Thanks for the comment. The algebraic variety is taken with its Zariski topology, so if the topological group is homeomorphic to it, then its group operations are continuous with respect to the Zariski topology. Isn't that wat is needed? I can't tell what a morphism of varieties is.
Comment: $\mathbb{C}^*$ as an algebraic group has a different topology than $\mathbb{C}^*$ as a Lie group. $\phi$ is a homeomorphism between $G/H$ on one hand, and on the other hand $\mathbb{C}^*$ as a Lie group, and not as an algebraic group. If it were a homeomorphism with an algebraic group taken with the topology of an algebraic group, it would be what you call a morphism of varieties, I guess.
Comment: Oh, I see, my apologies to everyone! I naively thought that algebraicity is about the topology being Zariski. So it's even more subtle.. Thanks to everyone.
Answer: The easiest example I can think of where both fail miserably is $S^1\subseteq\mathbb C-\{0\}$ under multiplication, where we treat $\mathbb C-\{0\}$ as a complex variety. $S^1$ is uncountably infinite, whereas the proper Zariski closed subsets are finite. The quotient is the group of positive reals, which is not algebraic over the complex numbers.
Comment: Hmm, thanks! Things are much more complicated than they seem at first.
Comment: @Bedovlat No problem.


Postman on Linux - Couldn't open sign-in link from app

Question: I have just installed postman on Linux by following the guide here. And I was able to open the postman desktop app. However, when I wanted to sign in by clicking the "Sign in" button on the upper right, the page below showed up and never directed me to any page to sign in (clicking "open it manually" didn't work either). The page just hung there until "Your request timed out" showed up.

I tried to open the app from terminal instead and I saw the following error:

I am not sure what's going on here but any insights would be much appreciated!
Comment: You have a good question, but you have posted to the wrong StackEachange site. I'm voting to close this question because your question is not "Programming" related, it is more appropriate for the StackExchange sites [Super User](http://superuser.com/) or [Unix & Linux](http://unix.stackexchange.com/). That said, I'm glad you were able to suss-out missing xdg-utils was the problem. You may want to consider moving the question and answer to the Unix & Linux site.
Answer: Found the solution myself. It's because xdg-utils was not installed on my linux. yum install xdg-utils fixed the issue.


DependencyProperty and DataBinding - Why property setter isn't called when UserControl loads?

Question: I want to model the behavior of a RangeSlider, using a class RangeSliderModel with properties describing the sizes (widths) for a given set of values.
Then, I created an UserControl where the position and size of some rectangles should represent those properties, and some instances of Thumb from which the DragDelta events are used to resize these rectangles and enable the calculation of a new value for a RangeSliderModel.
At last, this UserControl has a  DependencyProperty of type RangeSliderModel:
    public RangeSliderModel Model
    {
        get
        {
            return (RangeSliderModel)GetValue(RangeSliderModelProperty);
            // or instead calculate a RangeSliderModel from children sizes.
        }
        set
        {
            // this IS NOT called when UserControl loads
            SetValue(RangeSliderModelProperty, value);
            // here I could take the value and calculate new sizes for the children.
        }
    }

    public static readonly DependencyProperty RangeSliderModelProperty =
        DependencyProperty.Register("RangeSliderModel",
                                    typeof(RangeSliderModel),
                                    typeof(MyUserControl),
                                    new PropertyMetadata(ModelPropertyChanged));

    private static void ModelPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        // this IS called when UserControl loads.
        RangeSliderModel model = e.NewValue as RangeSliderModel;
    }

I was expecting to override the SetValue and GetValue properties, but even when I bind this DependencyProperty to a corresponding Source in ViewModel, the setter is never called! And I can't quite understand why PropertyChangedHandler is called instead, and much less what I should do with this information - I was expecting to use just GetValue and SetValue in a way similar to a ValueConverter.
Comment: In your ModelPropertyChanged handler, the code should be myObject.Model = e.NewValue as RangeSliderModel.
Answer: Dependency properties don't work that way when you set them through bindings. DependencyObject.SetCurrentValue is called. The Binding is calling (in essence):
yourObject.SetCurrentValue(YourClassName.RangeSliderModelProperty, someValue);

So, yeah, SetCurrentValue vs SetValue. SetValue will overwrite any binding on the dependency property; SetCurrentValue won't. IIRC this has to do with the way Style Triggers in XAML can't override values set by attributes. It's not directly relevant to what you're doing here, fortunately.
The bottom line is that your ModelPropertyChanged handler is where you put code that needs to get called when the value changes. Dependency properties and regular .NET CLR properties are two independent mechanisms.
I have had dependency properties bind correctly in XAML if I left out the public property entirely; I just tested that again and found it to be the case for my test example. In comments you mention that you did not find this to be the case with your code, so clearly I need to do some more reading.
If you need to have subclasses respond to changes, you can either write a virtual method they can override, and call it in ModelPropertyChanged, or else write a ModelChanged event and raise that in ModelPropertyChanged.
They could add a ValueChanged handler via a DependencyPropertyDescriptor, but it'd be right neighborly of you to spare them the trouble of googling how to that, by writing a virtual method or event.
Comment: The XAML parser calls `SetBinding`, `DependencyObject.SetBinding` is just a shortcut for the former as far as i know. I think the binding itself will call `SetCurrentValue`, which unlike `SetValue` does not remove the existing binding.
Comment: Fine, I started to use SetValue directly instead of the regular setter, and that worked fine. On the other hand, deleting the regular setter/getter did break the XAML binding (I guess it was expecting the given property name), so I let it be. Now things are working as expected, thanks!
Comment: @heltonbiker Hmm! Let me test that and make sure I'm not spouting nonsense. Thanks!
Comment: Actually, it's not calling `SetValue`, it calls `SetBinding`.
Comment: @H.B. Are you saying that you set a binding on a dependency property by calling BindingOperations.SetBinding, or are you saying that you set the value of a dependency property by calling DependencyObject.SetBinding?
Comment: @H.B. Are you thinking SetCurrentValue? OMG I should've kept my mouth shut, this stuff is a nightmare.
Comment: Yes, just looked at docs again right now myself...


Why does XlsxWriter border box merges my string cell to the corner when the actual corner cell contains empty string

Question: let's use an example df as following:
<code>a     b        c   d
"hi"  "Tom,"   ""  ""
"how" "are"    ""  ""
"you" "doing?" ""  ""
</code>
I'm trying to export this to Excel with xlsxwriter and I would like to put a border around the entire dataframe using the following code:
https://gist.github.com/pankaj28843/d8c9c548a5a761be7ae6
When I do this I get the square border exactly as desired but the cell with "Tom" is dragged out over c and d, as if I used merge. This makes it look like this:
<code>"hi"       "Tom,"
"how" "are"    ""  ""
"you" "doing?" ""  ""
</code>
Why does this happen, why can't I just put a border around the corner cell with "".
I checked and if I put a character in the string of columnn d, row 0 all cells stay in place like they should without the merge effect.
Thank you!
Answer: I solved it now by replacing all empty strings "", with a space string " " but would still like to understand what's happening here.
Answer: https://xlsxwriter.readthedocs.io/format.html#set_center_across
In my case, the issue was related to the 'center_across' formatting attribute. This was being set to True, resulting in formats with a 'text_h_align' value of 6. I would iterate through your workbook's formats and verify the final 'text_h_align' in each.
I noticed the undesired merging behavior after porting from xlsxwriter-1.1.5-1 on py2, to xlsxwriter-3.0.2-1 on py3 -- but didn't investigate to find out whether it was broken in previous versions or had purposefully updated. Regardless, I had redundant formatting written using the suggested merge_range method, so once I removed any 'center_across' definitions from my formats I no longer saw undesired merges.


SQL Table Split-Is it necessary

Question: I've a table with around 6-7lacs records and it's going to grow as time passes.It has around 16-20 columns in it. There are no one-many relationship to any of these columns.
User data entries are stored in these table.
So would it be feasible to split my table into multiple small tables or else just split the table into 2 halfs one with all the entries in it and other the recently fresh records which would be present to the data entry operators to feed in their entries.
In short my question is whether the mysql execution time would be faster if I split the tables, or would it be faster if I split them into two half's.
I guess the latter would be more feasible since it would not perform any join queries.
Updated:
<code>CREATE TABLE `images` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `primary_category_id` int(10) unsigned DEFAULT NULL,
  `secondary_category_id` int(10) unsigned DEFAULT NULL,
  `front_url` varchar(255) DEFAULT NULL,
  `back_url` varchar(255) DEFAULT NULL,
  `title` varchar(100) DEFAULT NULL,
  `part` varchar(10) DEFAULT NULL,
  `photo_id` int(10) unsigned DEFAULT NULL,
  `photo_dt_month` varchar(2) DEFAULT NULL,
  `photo_dt_day` varchar(2) DEFAULT NULL,
  `photo_dt_yr` varchar(4) DEFAULT NULL,
  `type` varchar(25) DEFAULT NULL,
  `size_width` int(10) unsigned DEFAULT NULL,
  `size_height` int(10) unsigned DEFAULT NULL,
  `dpi` int(10) unsigned NOT NULL DEFAULT '0',
  `dpix` int(10) unsigned DEFAULT NULL,
  `dpiy` int(10) unsigned DEFAULT NULL,
  `in_stock` varchar(50) DEFAULT NULL,
  `outlet` varchar(50) DEFAULT NULL,
  `source` varchar(50) DEFAULT NULL,
  `keywords` varchar(255) DEFAULT NULL,
  `emotional_keywords` varchar(255) DEFAULT NULL,
  `mechanical_keywords` varchar(255) DEFAULT NULL,
  `description` text,
  `notes` text,
  `comments` text,
  `exported_to_ebay_dt` datetime DEFAULT NULL,
  `exported_to_ebay` set('Y','N') NOT NULL DEFAULT 'N',
  `updated_worker_id` int(10) unsigned DEFAULT NULL,
  `updated_worker_dt` datetime DEFAULT NULL,
  `locked_worker_id` int(10) unsigned DEFAULT NULL,
  `locked_worker_dt` datetime DEFAULT NULL,
  `updated_admin_id` int(10) unsigned DEFAULT NULL,
  `updated_admin_dt` datetime DEFAULT NULL,
  `added_dt` datetime DEFAULT NULL,
  `updated_manager_id` int(10) unsigned DEFAULT NULL,
  `updated_manager_dt` datetime DEFAULT NULL,
  `manager_review` set('Y','N') NOT NULL DEFAULT 'N',
  `paid_status` set('Y','N') NOT NULL DEFAULT 'N',
  `exported_to_web_dt` datetime DEFAULT NULL,
  `exported_to_web` set('Y','N') DEFAULT 'N',
  `prefix` varchar(50) DEFAULT NULL,
  `is_premium` set('Y','N') DEFAULT 'N',
  `template` varchar(50) DEFAULT 'HIPE_default',
  `photographer` varchar(100) DEFAULT NULL,
  `copyright` varchar(100) DEFAULT NULL,
  `priority` int(4) DEFAULT '1',
  `step` set('1','2') DEFAULT '1',
  PRIMARY KEY (`id`),
  UNIQUE KEY `part` (`part`),
  KEY `primary_category_id` (`primary_category_id`),
  KEY `updated_worker_id` (`updated_worker_id`),
  KEY `updated_worker_dt` (`updated_worker_dt`)
) ENGINE=MyISAM AUTO_INCREMENT=1013687 DEFAULT CHARSET=latin1
</code>
The above is my table structure.After there are entries being made say around 1lac I would split it into another table say images_history with same structure.Is this feasible or should I split them into multiple tables to reduce the query execution time
Comment: Can you add some DDL describing roughly what your table looks like and what it would look like if it were split?
Comment: thanks for editing ... didn't know why it wasn't formatting
Comment: For those of you unfamiliar with asian numbers, 1 lakh = 100'000
Answer: Why do you want to split the table? It would lead to a ton of extra code and slow down the execution time by adding extra queries if you still want to access both of the new tables. (If one of the tables are going to store rarely used previous versions of records of the images table - i.e. version control - it may still be a good idea).
Before even thinking about splitting the table, see if you can increase performance by optimizing the existing code by making sure none of the following performance disasters are:

Do all SELECTs filter by PRIMARY KEY?
Is the index cache large enough to hold all indices in the computers RAM?
Are any string matching SELECTs with LIKE using the indices? I.e. only exact matches or wildcards on the right, never on the left (e.g. "searchword%" and never "%searchword"
Are there any slow performing queries that use SELECT * instead of selecting only the columns you need?
Have you avoided using OR in SELECTs?

Performing queries on a table with 700 000 records shouldn't be slow if tabels are properly indexed and queries are actually using those indices.
Comment: Yes by indexing the performance would boost up, but what if I divide the tables which has around 15-20 column in it --- to 3-4 tables each having 5-6 columns and having a good indexing. Does doing this would reduce my sql execution time? that's my real question
Comment: if you have a column that is of a BLOB kind (TEXT, LONGTEXT), a SELECT * or SELECT blobcolumn will force the data to be written to a TMP table on disk instead of RAM. Having a lot of columns will AFAIK not slow down anything if you actually access the columns you actually are going to use by using indexed columns.
Comment: @ Harald: Thanks! I don't have many text columns only 2-3( check my structure above  ).So would the query execution time increase If I ran a query such as Select * and as I have only indexes on few columns only.Is splitting of tables a necessity then?

SQL Table Split-Is it necessary


AKS Isolate Service in namespace

Question: We deploy a service to our existing AKS cluster that needs to be isolated as much as possible so it can't access other services or resources in our cluster.
I created a new kubernetes namespace and deployed the service there.
Next i would like to lock down the network in this namespace so the service can be reached from the outside world via HTTPS but can not access other services running in the same AKS cluster (but in different namespaces).
For that, i deployed a Network Policy, denying all egress:
<code>apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny
  namespace: namespace-where-service-is-deployed
spec:
  podSelector: {}
  policyTypes:
  - Egress
</code>
based on: https://projectcalico.docs.tigera.io/security/kubernetes-network-policy
This works but it totally blocks all egress. I need the service to be able to access it's database (CosmosDB) which is running outside the AKS cluster.
Also i would like log transmission via Application Insights to work.
Is there a way to isolate the service without having to figure out all the IP Adresses of CosmosDB and App Insights and allowing them explicitly?
We are running on Kubernetes Version 1.23.8 and using the Network Plugin "kubenet" with the Network Policy "calico".
Thank you very much!
Answer: I finally was able to achieve the isolation by restricting ingress to the namespace where my other workload was deployed (which should not be accessed from the service to isolate) based on this approach:
how to isolate kubernetes namespaces but allow access from outside
But as "the outside" in my case was the Ingress Controller, i applied the label to the Namespace where the Ingress Controller was deployed instead of kube-system.

AKS Isolate Service in namespace


How do I use it only in the frontend theme?

Question: Using the jQuery Update module, I set version 1.8. This version "broke" the views UI in the Admin theme; it seems that the AJAX calls in the Views UI work only with jquery 1.5.
How can I fix it?
Answer: With jQuery Update 7.x-3.0-alpha2 and later, there is a setting that allows to change the jQuery used for a specific theme; you can select:

The site default version (set with the jQuery Update module)
The version that comes with Drupal
Any version supported by the jQuery Update module
Answer: try this
<code>/**
 * Implements hook_module_implements_alter().
 */
function mymodule_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'library_alter') {
    if(isset($implementations['jquery_update'])) {
      // Move jquery update to the end. This will make sure our hook_library_alter
      // is always called before the jquery_update.
      $jquery_update = $implementations['jquery_update'];
      unset($implementations['jquery_update']);
      $implementations['jquery_update'] = $jquery_update;
    }
  }
}

/**
 * Implements hook_library_alter().
 */
function mymodule_library_alter(&$libraries, $module) {
  // If it is the admin theme all we want to do is change the global $conf
  // variable so when jquery_update runs right after us it will use 1.5.
  // We are not using path_is_admin(current_path()) because some admin path can use
  // the frontend theme like node edit page
  global $theme_key;
  if (variable_get('admin_theme') == $theme_key) {
    // Modifying global $conf variable, can be dangerous. Be carefull.
    global $conf;
    $conf['jquery_update_jquery_version'] = '1.5';
  }
}
</code>
from http://antistatique.net/blog/2013/01/04/drupal-use-a-different-jquerys-version-for-the-frontend-and-backend/
Answer: You can use my patch from this issue. It will add per path settings, like on the following mockup:

Patch code here, and also below:
<code>*** jquery_update.module    Fri Sep 28 01:53:48 2012
--- jquery_update.module    Tue Oct 08 11:12:58 2013
***************
*** 68,77 ****
--- 68,83 ----
    // We are updating just the system module. For all other cases we return.
    if ($module != 'system') {
      return;
    }

+   // We don't want to alter if we are on one of the excluded paths
+   if(drupal_match_path(current_path(), variable_get('jquery_update_exclude_paths', ''))) {
+     return;
+   }
+
+
    $path = drupal_get_path('module', 'jquery_update');

    // Make sure we inject either the minified or uncompressed version as desired.
    $min = variable_get('jquery_update_compression_type', 'min') == 'none' ? '' : '.min';
    $cdn = variable_get('jquery_update_jquery_cdn', 'none');
***************
*** 146,155 ****
--- 152,167 ----
        'microsoft' => t('Microsoft'),
        'jquery' => t('jQuery'),
      ),
      '#default_value' => variable_get('jquery_update_jquery_cdn', 'none'),
      '#description' => t('Use jQuery and jQuery UI from a CDN. If the CDN is not available the local version of jQuery and jQuery UI will be used.'),
+   );
+   $form['jquery_update_exclude_paths'] = array(
+     '#type' => 'textarea',
+     '#title' => t('Disable jQuery update on the following paths'),
+     '#description' => t('You are allowed to use wildcards, for example admin/*'),
+     '#default_value' => variable_get('jquery_update_exclude_paths', ''),
    );

    return system_settings_form($form);
  }
</code>
Answer: Use dev version, that has already commited patch allowing to set different version for administrative pages: https://drupal.org/node/1524944
Comment: Sadly, it still does not allow to use original jQuery version to be selected. This issue is still open.


Tornar as checkbox selecionadas, conforme dados do banco!

Question: Conforme o código abaixo, preciso fazer com que ao carregar a página, uma tabela seja carregada com os checkbox marcados, conforme dados do banco, por exemplo:
                Destino
             _______________________________________
    Origem  |   1   |   2   |   3   |   4   |   5   |
    --------|-------|-------|-------|-------|-------|
       1    |       |   X   |       |       |       |
    --------|-------|-------|-------|-------|-------|
       2    |       |       |   X   |       |       |
    --------|-------|-------|-------|-------|-------|
       3    |       |       |       |   X   |       |
    --------|-------|-------|-------|-------|-------|
       4    |       |       |       |       |   X   |
    --------|-------|-------|-------|-------|-------|
       5    |       |       |       |       |       |

Onde o X seria conforme o banco de dados, formando o seguinte array:

   $transicao => array(
              (int) 0 => array(
                      'origem' => 1,
                      'destino' => 2
              )
              (int) 1 => array(
                      'origem' => 2,
                      'destino' => 3
              )
              (int) 2 => array(
                      'origem' => 3,
                      'destino' => 4
              )
              (int) 3 => array(
                      'origem' => 4,
                      'destino' => 5
              )

Código atual:
Copiando e colando o código neste site, você verá o mesmo em funcionamento
<?php

   $status = array(
              [
                  'origem' => 1,
              ],
              [
                  'origem' => 2,
              ],
              [
                  'origem' => 3,
              ],
              [
                  'origem' => 4,
              ]
   );

//simulando dados do banco de dados
   $transicao = array(
              [
                  'origem' => 1,
                  'destino' => 2
              ],
              [
                  'origem' => 2,
                  'destino' => 3
              ],
              [
                  'origem' => 3,
                  'destino' => 4
              ],
              [
                  'origem' => 4,
                  'destino' => 5
              ]
   );

echo "

         ORIGEM 	";
        foreach ($status as $xkey => $xvalue) :
            echo " " . $xvalue['origem'] . "	";
        endforeach;
        echo "

";
    //      foreach que percorre as colunas
            foreach ($status as $ykey => $yvalue) :
                echo " " . $yvalue['origem'] . "	";
                foreach ($status as $xkey => $xvalue) :
                    $value = $yvalue['origem'] . '|' . $xvalue['origem'];
                    echo "
<input type='checkbox' name='origem" . $value . "destino value='" . $value . "'>
                    	";
                endforeach;
                echo "
";
            endforeach;
echo "
";

Comment: Quando for dar o "echo" no input, faça uma verificação pra ver se aquele deve ser marcado, se for o caso coloque o atributo checked="checked".
Comment: Pois é José, eu fiz isso, porém ainda não encontrei a lógica correta pra marcar somente aqueles que existe no banco de dados, quando faço essa verificação, ele marca alguns e aí fica sobrando outros checkbox caso tenha algum marcado, estou tentando aqui, qualquer coisa eu posto o resultado, se você tiver outra alternativa ficarei grato pela ajuda xD
Answer: Você pode verificar se existe o array do checkbox dentro dos dados que estão vindo do banco com o in_array
$checked = (in_array(['origem'=>$yvalue, 'destino'=>$xvalue], $transicao) ? 'checked="checked"' : '');

echo "";
    echo "<input type='checkbox' name='origem" . $value . "destino value='" . $value . "' ".$checked.">";
echo "	";

Comment: Cara, pra mim não funcionou, devido aos arrays bidimensionais.
o `in_array` não funciona em arrays bidimensionais (se não me engano)
Comment: o `in_array` verifica se um objetivo igual contém dentro do array, somente se o seu array estiver diferente do origem/destino que você citou no exemplo, fiz o teste com o seu código e funcionou certinho.
Comment: Tens razão, eu coloquei o array `X` e `Y` dessa forma para melhor ser entendido o que eu estava falando, porém o `array X` e `Y`, seria um `Array status`, vou editar para melhor ser entendido.
Answer: Solução encontrada:
Criei uma variável $marcado dentro do foreach que percorre o array $x para fazer a inserção dos checkbox, inicializei a variável como false (assim: $marcado = false;) e depois fiz a seguinte verificação:
Se $yvalue (origem) for igual à $transicoes_value['origem'] (origem do array $transicoes) e $xvalue for igual à $transicoes_value['destino'] (destino do array $transicoes), então eu seto a variável $marcado = true.

if ($yvalue == $transicoes_value['origem']
 && $xvalue == $transicoes_value['destino']) {
    $marcado = true;
}

Após eu imprimo o checkbox caso a variável $marcado seja igual a true eu imprimo o checkbox com a propriedade checked="checked" se não, imprimo normal sem a propriedade checked="checked".
Assim:
if ($marcado == false) {
    echo "
        <input type='checkbox'
               name='origem" . $value . "destino value='" . $value . "
               checked='checked'>
    	";
} else {
     echo "
        <input type='checkbox'
               name='origem" . $value . "destino value='" . $value . ">
    	";
}

Código final:
Copiando e colando o código neste site, você verá o mesmo em funcionamento
<?php

   $status = array(
              [
                  'origem' => 1,
              ],
              [
                  'origem' => 2,
              ],
              [
                  'origem' => 3,
              ],
              [
                  'origem' => 4,
              ],
              [
                  'origem' => 5,
              ]
   );

//simulando dados do banco de dados
   $transicao = array(
              [
                  'origem' => 1,
                  'destino' => 2
              ],
              [
                  'origem' => 2,
                  'destino' => 3
              ],
              [
                  'origem' => 3,
                  'destino' => 4
              ],
              [
                  'origem' => 4,
                  'destino' => 5
              ]
   );

echo "

         ORIGEM 	";
        foreach ($status as $xkey => $xvalue) :
            echo " " . $xvalue['origem'] . "	";
        endforeach;
        echo "

";
    //      foreach que percorre as colunas
            foreach ($status as $ykey => $yvalue) :
                echo " " . $yvalue['origem'] . "	";
                foreach ($status as $xkey => $xvalue) :
                    $marcado = false;
                    $value = $yvalue['origem'] . '|' . $xvalue['origem'];
                    foreach($transicao as $transicao_key => $transicao_value) :
                    if ($yvalue['origem'] == $transicao_value['origem']
                     && $xvalue['origem'] == $transicao_value['destino']) {
                        $marcado = true;
                    }
                endforeach;
                if ($marcado == true) {
                    echo "
      <input type='checkbox'
             name='origem" . $value . "destino value='" . $value . "
             checked='checked'>
                    	";
                } else {
                    echo "
      <input type='checkbox'
             name='origem" . $value . "destino value='" . $value . " '>
                    	";
                }
                endforeach;
                echo "
";
            endforeach;
echo "
";


Differentiate $y=x^x$

Question: How do you differentiate $$\large{f(x) = x^x}$$
The working I got was $$\ln f(x) = x \ln  x$$
which I am pretty fine...but I do not know how it advances to
$$\frac{f'(x)}{f(x)} = x\begin{pmatrix} \frac 1 x\end{pmatrix} + \ln x$$
although the final answer can be, by multiplying $f(x)$ on both sides of the equation,
$${f'(x)} = x^x\begin{bmatrix}x\begin{pmatrix} \frac 1 x\end{pmatrix} + \ln x\end{bmatrix}$$

UPDATE : SOLVED
Indeed, $$\ln f(x) = x \ln  x$$
Differentiate both sides of the equation w.r.t $x$
$$\frac{f'(x)}{f(x)} = x\begin{pmatrix} \frac 1 x\end{pmatrix} + \ln x = 1 + \ln x$$
Bring the $f(x)$ over and you'll finally get

$$f'(x) = x^x\begin {pmatrix} 1 + \ln x\end{pmatrix}$$
Comment: If you have any function to a variable exponent in a calculus problem, say $f(x)^{g(x)}$ I find it almost always pays to replace it by $e^{f(x)g(x)}$. Example: ${d\over dx}2^x={d\over dx}e^{x\ln2}=(\ln 2)e^x$  and $\int 2^x dx=\int e^{x\ \ln 2}dx=e^{x \ln 2}+C$ by an elementary substitution which is much better than memorizing where that $\ln 2$ goes and then putting it in the wrong place.
Comment: Yes............but why won't you better write $\,x\frac{1}{x}=1\,$ ...?
Comment: It was directly lifted off from the textbook. I know what you meant, but perhaps some help to get there before I change it back to $1 + \ln x$
Comment: Some help...where? What you did is correct!
Answer: Another way (You already used the chain rule and $[\ln f(x)]'$: $$x^x=e^{x\ln x}$$
Answer: By the chain rule
$$\frac{d}{dx} \ln{f(x)} = \frac{1}{f(x)} f'(x)$$
Answer: The following came from a mathoverflow answer (I cannot recall the question):
A student was asked to differentiate $y=x^x$. Not remembering how to do logarithmic differentiation the student reasoned as follows: "well, I do not know how to differntiate $x^x$, but I do know how $x^r$. This is $rx^{r-1}$. But this is not right since the exponent is $x$. But I also know the derivative of $r^x$. This is $ln(r)r^x$. This is not right either for the same reason. So I'll split the difference and add them together and get $rx^{r-1}+ln(r)r^x$. But that $r$ is actually $x$ so the answer must be $x^x+ln(x)x^x$
The funny thing is that the result is right, but the reasoning is incomplete. What you need is multivariable chain rule for a composite of the form, $$\mathbb{R}\to\mathbb{R}^2\to\mathbb{R}$$, where the first map is the diagonal, and the second will be called $f$.  The answer that you get in the case is $$\frac{df(x,x)}{dx}=\frac{\partial f}{\partial x}+\frac{\partial f}{\partial y}_{x=y}$$
Where $\frac{\partial f}{\partial y}_{x=y}$ is the composite $\frac{\partial f}{\partial y}(\iota)$, where $\iota(y)=x$.
Comment: You would not necessarily see this type of solution in a first calculus course.

Differentiate $y=x^x$


Relative error in Gaussian distribution.

Question: For discrete Gaussian distribution using cumulative distribution table how is the Relative error calculated?
Specifically, In this paper https://eprint.iacr.org/2014/254 on page 7 section 3.4 It says that reversing the table will prevent blowing up of relative errors. I quite did not understand the reason very well.
Comment: So I'm not sure whether this is a one-tailed distribution or not, but I can definitely see the possible problem with a one-tailed distribution. Basically, if you sum a rapidly decreasing sequence of positive numbers in floating point arithmetic, soon enough you're going to start seeing something like $1+\epsilon_{mach}$, which will be just $1$.
Comment: So when you go to subtract the two neighboring terms, you will get just zero rather than a tiny positive number, which is a 100% relative error. Summing from the other way keeps the CDF small when the PMF is small, so that adding something to it makes a significant impact.
Comment: A concrete example albeit not in this context: $(1+2^{-100})-1$ will probably display $0$, whereas $(2^{-90}+2^{-100})-2^{-90}$ will not, even though both in theory should be $2^{-100}$.
Comment: What confuses me is that I usually think of a Gaussian as being two-tailed, and this problem cannot be eliminated in such a simple fashion in a two-tailed problem.
Comment: Since the gaussian is symmetric with 0, cant you just use the one-tailed and then have a 50/50 chance of being positive / negative ?
Comment: @MGirard I suppose that works (with appropriate modification if the mean is nonzero), it just didn't sound like that was what they were doing from what I got from the article. But maybe it was, I didn't read that carefully. It still doesn't work in a more general two-tailed situation with no symmetry.
Answer: So I'm not sure exactly what they're doing in this context, but I think I know essentially what is going on. The problem is essentially this: if you sum a rapidly decreasing sequence of positive numbers in floating point arithmetic, eventually the cumulative sum $S_n$ is way bigger than the next term $x_{n+1}$, which causes that term to be swamped, i.e. most or even all of its significant digits are destroyed. The remaining significant digits are all that you get when you attempt to reconstruct $x_{n+1}$ as $S_{n+1}-S_n$. But if instead you sum a rapidly increasing sequence of positive numbers, then the worst thing that could happen is that the cumulative sum itself gets swamped, which is not really a big deal in terms of computing $x_{n+1}$ as $S_{n+1}-S_n$.
One way to play with this (with less technical issues than in the article that you linked) would be to look at the distribution with $P(X=i)=\frac{2^{-i}}{\sum_{j=1}^{100} 2^{-j}}$ for $i=1,2,\dots,100$ and zero otherwise. Try computing the CDF by summing from left to right and then reconstructing the PMF, and then computing it again by summing from right to left and reconstructing the PMF. What you'll find is, if you're using IEEE double precision, the first method will actually just give $P(X=i)=0$ for $i$ larger than about $55$, while the second method will give reasonable results. This would be even worse if it were not for the fact that these numbers are all exactly floating point representable. You could try replacing $2$ with $3$ to see how much worse it can get.


How to run batch file with credentials using Jenkins

Question: I've mkdir commands in a batch file but only admins have permissions to create directory, so how to pass credentials from Jenkins job to the batch file.
mkdir \\%%S.domain.com\c$\Test

Comment: But that prompts user to enter password, so how to configure it in Jenkins
Comment: Check out [runas](http://technet.microsoft.com/en-us/library/cc771525%28v=ws.10%29.aspx).
Comment: Use one of the alternatives such as [this](http://www.softtreetech.com/24x7/archive/53.htm) that allow you to specify the password on the command line. Use EnvInject / Mask Passwords plugins in Jenkins to store the password in Jenkins and hide it in the console output (alternatively, just `@echo off` in the batch build step).
Answer: Select the "use secret text(s) or file(s) and then add a binding.  See screenshot :
Comment: Just to add to this, use the Bindings as above to store and pass the username and password.

The set the username variable to USERNAME and Password Variable to PASSWORD, then in you batch file use the `net use` command

    net use "\\server\share" %PASSWORD% /user:%USERNAME%
    \* whatever you need to do on that share, e.g. xcopy, mkdir *\
    net use "\\server\share" /delete
Comment: Where do I find these settings?
Answer: Yes Daniel, it might be done using such utility tools but my organization doesn't allow me to use third party tools without approvals. So, we have configured server with WinRM that allows to connect to server remotely using credentials.
Answer: Just to add to @Marc's answer, use the secret text Bindings as suggested to store and pass the username and password as environment variables.
The set the username variable to USERNAME and Password Variable to PASSWORD, then in your batch file use the net use command like so.
net use "\\server\share" %PASSWORD% /user:%USERNAME%
\* whatever you need to do on that share, e.g. xcopy, mkdir *\
net use "\\server\share" /delete