Proof that direct distance from $a$ to $b$ is at most the distance of any other path from $a$ to $b$

Question:
Lemma 1. If the triangle inequality holds in a graph with positive
  weights, then d(a, b) is at most the weight of any path from a to b.
Proof. We prove the lemma by induction. Let the inductive hypothesis P
  (n) be the statement "If n is the length of a path p from a to b, for
  any vertices a and b, then d(a, b) is at most the weight of p."
This
  holds for the base case of n = 1, since the minimum cost of traveling
  from a to b cannot be strictly greater than the weight of the direct
  path from a to b (otherwise, we could simply take the direct path for
  a smaller cost).

In the above proof I know the base case is true because if length of path $p$ is $1$, then $d(a, b)= \text{weight of } p$.
However I can't understand their reasoning which states:
 $\text{minimum cost of travelling from a to b } \le d(a,b)$
EDIT: Graph is complete graph and $d(a,b)$ is known for each pair of vertices, where $d(a,b)$ is the weight of edge $a-b$.
Comment: What is the definition of $d(a,b)$?
Comment: I assume that the "minimum cost of travelling" is simply the minimum of *distance*".
Comment: It is the weight of edge a-b.
Comment: @shiva From your answer, I deduce that there is at most one edge between any two vertices. So for the case $n=1$ there is really nothing to show, because the only path with length $1$ *is* the edge connecting $a$ and $b$. Anyway, either you have misunderstood some definition, or the above proof is really not very sensibly formulated.
Comment: I actually think that $d(a,b)$ should be the infimum of the weights of all the paths leading from $a$ to $b$. Then this definition would make sense even if there is no edge between $a$ and $b$. But then the statement of the lemma would be tautological
Comment: With this modification, the lemma should read "if there is an (always unique) edge $p$ between $a$ and $b$, then $d(a,b) = w(p)$", and the proof of it would be again the one from my answer.
Comment: I have edited the question. Please look.
Comment: This does not change my answer. What they are saying is just that by triangle inequality the direct path is the shortest, which is what I have proved below.
Comment: @57Jimmy However I had trouble understanding their reasoning for the base case.
Comment: I know, but the point is really that their argument does not make sense: they are doing an induction, but the explanation they give for the base case is actually a general explanation (whereas for the base case one does not need any explanation: if everything is as you have defined it, there is *only one* path of length $1$ between $a$ and $b$, and it is the edge connecting them). And the general explanation is: "if you can travel along a path and your cost of travelling (i.e., the sum of the weights / distances) is smaller than $d(a,b)$, then the triangle inequality cannot hold".
Comment: Without any offence, I really think that either you are missing some part of some definition, or the proof (as you stated it) does not make sense.
Comment: None taken. And its highly probable that I might have missed something. Here is the source: https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-042j-mathematics-for-computer-science-fall-2010/recitations/MIT6_042JF10_rec09_sol.pdf. If you get time then you can go through it, won't take much time.
Answer: This follows from repeated application of triangle inequality (without explicitly using induction). Indeed, if you have any path $p$ from $a$ to $b$ consisting of $n$ edges $p_i$ connecting vertices $c_{i-1}$ to $c_i$ (hence $c_0=a, c_n=b$), and if $w$ denotes the weight function, then you have
$$d(a,b) \le \sum_i d(c_{i-1},c_i) = \sum_i w(p_i) = w(p).$$


How to test cat5/cat6 cable runs, using software-only, or simple tools?

Question: Are there any utilities or simple tools or techniques to easily test a CAT5 cable, to see how well was it installed?
Cat5 is often installed by amateurs, but has been installed and "working" for years. Proper cable testers and certifiers like a Fluke or LanTech often cost over USD$1000 and people who have them are few.
Aren't there some sort of special network cards, or USB cat5-testing devices, one can plug into a computer and test the cat5 with software?  Perhaps an Intel utility for their cards?
Comment: What are you looking to test? Are you just looking to see if the cable is OK or are you looking to run a full battery of tests for performance and the like?  If you just want to see if a cable is punched properly they sell pretty cheap devices to do that.
Comment: are you testing patch cables or cabling throughout a building?  If it's the former, throw it away and buy a new one if it's homemade; no test required and much much cheaper.
Comment: Forget it man, virtually all professionals have a problem with amateurs getting to use higher end functionality using cheap network cards instead of expensive equipment. They're going to repeat again and again to "buy a Fluke". I'm an EE, and I know a cable tester can do much better than an NIC in physical terms, but just for doing approximate TDR for locating faults, NICs are definitely enough. Some NICs actually do have them.
Answer: If you are doing Cat5e/6 gigabit and your PC auto negotiates to gigabit then your data pairs are terminated correctly. If it auto negotiates to 10/100 or doesn't work at all your data pairs are out of order or incorrectly terminated.
If a file copy of a large file hits max speed, and wireshark or netstat -s shows lower TCP retransmissions (0.5% or lower is acceptable), then the wire is good. The larger the file you copy the higher the guarantee is that the cable is good.
If you need to test the non data pairs (applies to 10/100 ONLY not gigabit which uses all 4 pairs), then you will need either a tester (which tests continuity), or a certifier (which is expensive). Some certifiers only test continuity on the non data pairs anyway, so if you do the same thing it is NOT the end of the world.
Cable certifiers make finding the issue quick and easy, and make testing much quicker then a PC. They completely eliminate the possibility of PC hardware issues from the equation. The downside is the price, especially for SOHO or hobbyists.
However there are some specialized PC based testers like NetPi turning up, if you are not sure where to start as far as what software to use, and how to use it.
Passing Cat6 can be hard, if there are any kinks, nicks, etc. Also if you punch down to a keystone keep the wire twisted as close to the keystone as possible, if you untwist it too much it won't pass. Cat5e cert is good enough for gigabit, so most people are fine with this in SOHO and Hobby. But if you are charging or going to be charging people for Cat6 certified, then it should certify as Cat6.
Answer: Buy a Fluke cable tester, they're what everyone else uses.
Comment: Want to add to my toolkit something allowing to test and troubleshoot cables in a troublesome LAN.  A Fluke is just much too expensive, simple continuity testers are just too simple. Just found one bad cable now - computer worked OK, but network seems flaky. The cable apparently has bad terminations. Changed it, but just based on appearance.
Answer: If you are going to continually test cables afterwards buy a fluke you won't be disappointed. If this is a one time only call around locally to companies and IT shops see what they would charge you to come out and test your runs. You could also do some searches on Google to rent a fluke cable tester. I found a few companies that do it.
Comment: Yes, cable certifiers are the best way. See some cheaper ones. Fluke, test-um, wavetek, microtest. Intel 82577 gigabit network cards have an "advanced cable diagnostics" with TDR, they do several tests. I ended up using "Totusoft LAN Speed Test" to benchmark the cable. Became visible it would only transfer at 40Mbits. Another cable benchmarked at 95mbits.
Answer: I think the major problem you are facing is that to test the physical properties of cables you need low level hardware access for the software which a standard laptop or PC NIC won't give you.
So you can use something like this hardware (https://pockethernet.com/) and I think you can use your own software if you're not happy with their completely adequate software, or buy one of the well know hardware testers like Fluke and EFXO.
Since you say some cables are installed and working, you can use something like https://github.com/jwbensley/Etherate to make low level Ethernet software tests.
Answer: Totusoft LAN Speed Test, when used with their LAN Test Server product, is a software way of testing throughput of cable runs. Their products are free for basic features, and quite cheap (~$10) for registration to get the advanced features.
(thanks to user135698 for the tip)
Answer: If you don't want to buy specialized hardware, you can use iperf to be sure your cables transmit at maximum rate. If the obtained rate is significantly lower than expected, it can be due to packet retransmissions caused by bad cables.


Add link gone from main menu and getting errors when trying to add new menu item

Question: Running D7
For some reason the add link is gone from the admin menu view...can only edit but can't add any links or menu items, getting errors also:
Warning: Illegal string offset 'hierarchical_select' in
drupal_array_set_nested_value() (line 6776 of
C:\aquiasites\redoII\includes\common.inc).

Fatal error: Cannot create references to/from string offsets nor
overloaded objects in C:\aquiasites\redoII\includes\common.inc on line
6776

I disabled hierarchical_select to no avail...I can't find the view to control those settings, but this is a core view right?
Usually menus say:
    list links    edit menu    add link

But now these options are gone...
It only says:
    MENU LINK   ENABLED TARGET  OPERATIONS

Answer: Ok, found the answer, eventually another error popped up when trying usermenu:
Warning: Illegal string offset '#value' in
content_menu_form_menu_item_delete_form_alter() (line 270 of
C:\aquiasites\redoII\sites\all\modules\content_menu
\content_menu.module)

I disabled all possible menu plugins...the offending module didn't create any errors on main menu and other, ONLY on usermenu...
Disabled this module https://www.drupal.org/project/content_menu
Now works fine


C++-ObjC OpenCV Constrained Delaunay

Question: I succesfully implemented a Delaunay triangulation of a contour in OpenCV 2.3.1.
With cvPointPolygonTest I can get all the triangles in the convex hull, then I tried to perform another cvPointPolygonTest on triangles centroid to know if they are in the main contour or not, so I can have the constrained triangulation of the contour.
But, it doesn't work well, as some triangles are (eg. with a walking man who has his two legs distant) 'over' a hole.
Does anyone know a way to perform a constrained triangulation. I thought about convexityDefects, but can't manage to understand how to begin with this.
Thanks in advance !
Ben

In fact, it is not a Convex Hull defects problem, but a triangulation one. This image will show you the trouble :

Particularly in the bottom of the triangulated hull, you can see that the triangulation is in AND out of the contour, because OpenCV is triangulating the convex hull. I would like to find a way to triangulate the contour itself.
I found some ideas about adding Steiner Points in the contour itself, but can't find where to begin with OpenCV.
My idea was to :

test if the triangle is in AND out of the contour ;
if true : get the intersection point ;
and add it to the cvSubdiv2D.

Am I right with this ?
Thanks for your patience and your answers !
Comment: Do you mean that your contour has some holes inside it and some of the triangles have the centroids in them?
Comment: Thanks for your comment. Yes, I mean exactly that. cvSubdiv2D performs the Delaunay triangulation of the convex hull of the contour, not the contour itself. So (in the case of a man walking) I have one point on an edge of the left leg, and another point of the same triangle on an edge of the right leg.In this case it's ok: the centroid is out of the man contour, but when a triangle is over the contour **and** the hole, it only erase the triangle or take it entirely, depending of the centroid position.
Answer: Finally I implemented the poly2tri library in my program.

Here is the result (OpenCV to get the contours, then poly2tri to perform triangulation) :
// -------------------- poly2tri --------------------

NSMutableArray* temp = [[NSMutableArray alloc] init];

vector<p2t::Triangle*> triangles;
vector< vector<p2t::Point*> > polylines;
vector<p2t::Point*> polyline;

for(int i = 0; i < contour32->total; i++ ) {
    CvPoint2D32f* pt32 = CV_GET_SEQ_ELEM(CvPoint2D32f, contour32, i);
    polyline.push_back(new p2t::Point((double)pt32->x, (double)pt32->y));
}

polylines.push_back(polyline);

p2t::CDT* cdt = new p2t::CDT(polyline);

// TODO -> holes with CV_RETR_TREE

// Triangulation !
cdt->Triangulate();

// On exporte nos triangles
triangles = cdt->GetTriangles();

for (int i = 0; i < triangles.size(); i++) {

    p2t::Triangle& t = *triangles[i];
    p2t::Point& a = *t.GetPoint(0);
    p2t::Point& b = *t.GetPoint(1);
    p2t::Point& c = *t.GetPoint(2);

    double x1 = (width / rWidth * (double)a.x) - (width / 2.f);
    double y1 = (height / rHeight * (double)a.y) - (height / 2.f);
    double x2 = (width / rWidth * (double)b.x) - (width / 2.f);
    double y2 = (height / rHeight * (double)b.y) - (height / 2.f);
    double x3 = (width / rWidth * (double)c.x) - (width / 2.f);
    double y3 = (height / rHeight * (double)c.y) - (height / 2.f);

    [temp addObject:[[NSArray arrayWithObjects:
                      [NSArray arrayWithObjects:
                       [NSNumber numberWithDouble:x1],
                       [NSNumber numberWithDouble:y1],
                       [NSNumber numberWithDouble:0.],
                       nil],
                      [NSArray arrayWithObjects:
                       [NSNumber numberWithDouble:x2],
                       [NSNumber numberWithDouble:y2],
                       [NSNumber numberWithDouble:0.],
                       nil],
                      [NSArray arrayWithObjects:
                       [NSNumber numberWithDouble:x3],
                       [NSNumber numberWithDouble:y3],
                       [NSNumber numberWithDouble:0.],
                       nil],
                      nil] autorelease]];

}

[outDelaunay addObject:temp];

where contour32 is your OpenCV contour found with cvFindContours, then converted to float32.
Comment: This is really interesting! Can you may give me a hint how to implement cvFindContours the right way? I'm trying to work with it on the iPhone …
Comment: You'll have to perform a threshold (and, if you want, a canny edge, but this is really bad for performance) on your gray image, then create a CvSeq for the contour. After that you can perform your cvFindContours and iterate the contours to obtain its coordinates or to directly draw it.
Comment: Thanks a lot! Got it working, but it's a mess because I first need proper background substraction I guess. Do you have any recommendations?
Comment: I don't know on what platform you're working, but background substraction on OpenCV is very heavy for performances. You might want to do a simple BG with a shader, then take your texture and convert it in a IplImage.
Answer: You will have to use:
    CvSeq* cvConvexityDefects(
const CvArr* contour,
const CvArr* convexhull,
CvMemStorage* storage = NULL
);

This will return a sequence(CvSeq) of CvConvexityDefect and not CvPoint or anything else like the CvSeq that you are probably used to.
You can go trough the defects in a loop, like this:
CvSeq* defects =  cvConvexityDefects(.....);
for (i = 0; i < defects->total; i++)
{
CvConvexityDefect* def = (CvConvexityDefect*)cvGetSeqElem(defects, i);
//do something with them
}

A defect has the following structure:
    typedef struct CvConvexityDefect {
// point of the contour where the defect begins
CvPoint* start;
// point of the contour where the defect ends
CvPoint* end;
// point within the defect farthest from the convex hull
CvPoint* depth_point;
// distance between the farthest point and the convex hull
float depth;
} CvConvexityDefect;

So after getting each defect you can build a CvSeq of points from them and use cvPointPolygonTest on the centroids of the triangles to see if they are inside of them.
If they are inside the defects, then it means that they are outside the main contour.
Hope this is what you need and that it helps.
Comment: Hi, Thanks you for your message. Won't your solution return approximately the same thing that is returning the cvPointPolygonTest I'm performing in the **contour itself** ? The problem is that I have sometime triangles which are **inside the convex hull** but **over a hole** so the centroid might be in the contour or in the defect. I try your proposal ! Thanks again !
Comment: I was thinking of adding Steiner Points to perform the constrained triangulation ([Steiner points](http://en.wikipedia.org/wiki/Steiner_points)) , but don't know where to begin... :-/
Comment: Here's an image : [on Google Doc](https://docs.google.com/open?id=0B4I3rXGO003hMGVjOGUzNjQtZmViMS00MmJmLTlmNTAtYjIwNjBlMTY3NmU5)
Comment: What I explained covers this case. The space between the legs will be a defect found by cvConvexityDefects, and if any triangle has the centroid in that defect, than you know you have to delete it because it is not inside the contour.
Comment: Thanks a lot ! I'll try this right now ! But I'm afraid it will erase some particular triangles like the one which is over the deisred contour AND the hole. I'll tell you !
Comment: I'm thinking about refining the contour to take in consideration the inner contour of the hole, by adding points. What do you think ?
Comment: I'm sorry but in fact it doesn't work : I'll have to refine the contours to find this constrained triangulation. There's something to do with convexityDefects, but not with centroids, as my triangulation doesn't take in consideration Delaunay edges crossing contours, but only the convex hull triangulation.

C++-ObjC OpenCV Constrained Delaunay


What is the function that converts uniform to exponential?

Question: What is the function that converts uniform to exponential with the following assumption?
Suppose the random variable $X$ follows the arbitrary cumulative distribution $F_{x}(x)$. If the random variable $U$ is defined by $U = F_x(x)$, $U$ has a uniform distribution between zero and one.
Answer: You need the function $F_x^{-1}(u)=x$. You can see how to generate exponential RV from uniform RV here as follows:
$$F^{-1}(u)=-\frac{\ln(1-u)}{\lambda}$$
where $\lambda$ is the rate parameter of exp. RV.
Comment: sorry can you give the proof
Comment: Sorry, this seems like a homework problem. Apologies if not. That's why I didn't provide the whole solution, but tried to point you in the right direction. Why don't you give it a try, write the CDF of exp RV (which can be obtained from wikipedia) and solve for $F(x)=u$, i.e. obtain $x$?
Comment: yes you were right that was easy but this is not a homework :|
Comment: now I want to code a  function in matlab that does the following
 Inside it by producing Uniform random variables samples (using the rand command) and applying the function g(U) on them to obtain examples of exponential random variables. The output of the function will be a vector N × 1 and Landa is an exponential random variable parameter


Use the following theorem to show that the set of irrational numbers is equinumerous to the set of real numbers

Question: The theorem states. Let A be a set and Let c be a non empty countable set disjoint from A. If A has a denumerable subset then A union C is equinumerous to A and conversely.
I was thinking of letting A be the rational numbers, and letting C be the irrational numbers that way it's disjoint, and then the subset of A would be integers, but then so the union of integers and irrational numbers would be equinumerous to rational numbers, but that doesn't help with the equinumerous of irrational and real numbers. Not sure what to do.
Answer: Let $A$ be the irrational number and $C$ be the rational number, then $A$ and $C$ are disjoint.
Check that $A$ has a denumerable subset and you can conclude that $A \cup C = \mathbb{R}$ is equinumerous to $A$, the set of irrational numbers.
What remains for you to do is to check that $A$ has a denumerable subset, can you complete that?
Comment: Perfect ok so a subset of irrational numbers that is denumerable? hmm could I just say the set of irrational numbers less than sqrt(2)?
Comment: hmmm, the set of irrational numbers less than $\sqrt2$ is not denumerable. Hint: $\{ 1, 2, \ldots, \}$ is denumerable, try to link them with $\sqrt2$ to make it irrational.
Comment: I can't think of a possible subset of irrational numbers? what could it possibly be? could you just say the set of all numbers equal to sqrt(2) that way it's just one value and that is obviously denumarable?
Comment: Just multiply $\mathbb{N}$ with $\sqrt2$ elementwise. you can also do addition, subtraction, division.


How to configure bind9 to be a local DNS only with no internet access?

Question: I want to configure bind9 to be a local DNS only with no internet access at all. So I have 5 PCs in my virtual domain xy.com. Within this domain there is no access to the internet.
The DNS server has entries like:

pc1.xy.com IN A 10.1.1.1
pc2.xy.com IN A 10.1.1.2
.
.
pc5.xy.com IN A 10.1.1.5

Bind is configured correctly but when I do a "dig @localhost pc1" on the DNS server it does not work because he gets stuck contacting the root servers. But I only want him to be local and to answer which IP pc1 has.
How can I achieve this?
Comment: In addition to the answer below, you need you actually lookup a record that's on the server. "pc1" and "pc1.xy.com" are not the same and a DNS server will not make assumptions for you.
Comment: In a zone file, names without a trailing period will be assumed to be relative to the zone itself. So if you have a zone example.com, and records in it `www IN A 188.8.131.52` and `ftp IN A 18.104.22.168` then the FQDN version of those records is `www.example.com` and `ftp.example.com` respectively. You should not configure TLDs or records in that namespace. You should configure your clients with a domain name and search domains (if there are multiple), DHCP option 15 and 119 respectively.
Comment: Ok I guess "pc1 IN CNAME pc1.xy.com." will do the job, right?
Answer: To achieve this you need to create a fake root zone to replace the "root.hints" zone that's normally configured.
In named.conf put this:
zone "." IN {
        type master;
        file "fake.root";
};

and in fake.root put this:
$TTL    300
.               IN      SOA ns. hostmaster.xy.com. (
                        20120101 1800 900 604800 86400
                )
.               IN      NS      ns
ns              IN      A       127.0.0.1

This will prevent all attempts to access the internet to obtain the real root hints.
You can also put your pcN.xy.com entries directly into that root zone, too - there's no need for them to be in their own xy.com zone file, so you can just append the following to fake.root:
$ORIGIN xy.com.
pc1             IN      A       10.1.1.1
pc2             IN      A       10.1.1.2
pc3             IN      A       10.1.1.3
pc4             IN      A       10.1.1.4
pc5             IN      A       10.1.1.5

Apart from any options { } that you may need (ACLs?) that's it - nothing else required.
Comment: @JulianDimitrov turn off DNSSEC validation.  NB: BIND 9.11 is now relatively ancient.   BIND 9.11.36 is the current version of BIND 9.11-ESV but it is about to go EOL.   The new ESV is based on BIND 9.16.
Comment: I don't think this works. At least not nowadays. Bind has root DNS hardcoded. Maybe turning recursion off will help. This will however also disable forwarders.
Comment: Yes, it works.  BIND has a supplied set of root *hints* but they are not used if a "real" root zone is configured.   Note that when a hints file is used, the BIND server will make an initial "priming query" to learn the current set of root servers, to allow for them being different to the compiled-in list.
Comment: Hi, this seems not to work for me with `BIND 9.11.5-P4-5.1+deb10u6-Debian (Extended Support Version)`. In the error log it says `managed-keys-zone: Unable to fetch DNSKEY set '.': failure`. I can create a separate question with full explanation
Answer: You need to disable recursion:
Add to the config:
allow-transfer {"none";};
allow-recursion {"none";};
My config "named.conf" looks like this (on RHEL system):
options {
        allow-query {
        any;
};
allow-recursion {
        none;
};

Comment: Ok in which file do I have to put this? named.conf.options, named.conf.local or db.xy.com or db.10.10.1?
Comment: I added both to named.conf.options but now I don't get an answer on "dig @localhost pc1.xy.com" but the WARNING: recursion requested but not available.
Comment: For me it is `named.conf`, but I know what my distro is, I do not know what yours is..
Comment: It's Debian 6. So you put both into the options section of named.conf?
Comment: It is declared right after "options" section. See the update to my answer.
Comment: Also, I know this isn't the answer, but this stuff is why I personally hate bind. I find "powerdns" to be a awesome alternative, and I can use various different backends, like mysql or ldap for instance.
Comment: this has _nothing_ to do with recursion, or transfers - it's all because BIND tries to download the latest real root hints whenever it starts.
Answer: You did not describe your configuration in enough detail. I think you are missing the authoritative part. You need to have a block like this in your config files:
zone "domain.lan" {
        type master;
        file "master/db.domain.lan";
        allow-update { none; };
};

where master/db.domain.lan should point to the zone file which should contain the records you posted above. Also, the zone file should have SOA (start of authority) record in its header. The zone file should like like:
domain.lan.     86400   IN SOA  dns.domain.lan. root.dns.domain.lan. ( 1 10800 3600 6044800 86400 )
                86400   IN NS   dns.domain.lan.

dns.domain.lan.      86400   IN   A    10.10.10.1
pc.domain.lan.    86400   IN   A    10.10.10.2

You can customize the names/values/IPs according to your needs.
Comment: @khalid I do have a zone just like you posted it, but bind tries to ask the root servers even if I dig for pc1.xy.com and thus times out. that sucks :(


Adding VLAN removes earlier virtual IPs in CentOS 6.X

Question: I added some virtual IPs to my eth0 interface in CentOS 6.5,
ip addr add 192.168.100.2 dev eth0

I then simply added a VLAN on eth0.
vconfig eth0 10

The VLAN was created but it removes any of my added IPs on eth0 (eg. 192.168.100.2).
I didn't face this issue in CentOS 5.X. The eth0 retains IPs.
Comment: I've removed "SOLVED" from the title of this question for two reasons: First, that is not how we indicate a question is resolved here, and second, this question obviously does not have a workable answer yet.
Answer: use ip notation for the vlan too - see the archlinux wiki https://wiki.archlinux.org/index.php/VLAN
ip link add link eth0 name eth0.10 type vlan id 10

Comment: Thanks, with Google search I came across the same link. Tried but it has the same problem. All other IPs (except the physical IP) disappear.
Comment: order is important - first create the link, then add new addr to the new link: ip addr add  192.168.100.2 dev eth0.10
Comment: The problem I'm facing is with IPs on eth0 which I want to retain. IPs for eth0.10 could be added later without a problem. The IPs however are retained on CentOS 5.4.
Comment: can you post content of /etc/udev/rules.d/70-persistent-net.rules
Comment: # This file was automatically generated by the /lib/udev/write_net_rules
# program, run by the persistent-net-generator.rules rules file.
#
# You can modify it, as long as you keep each rule on a single
# line, and change only the value of the NAME= key.

# PCI device 0x8086:0x1026 (e1000)
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="00:0e:0c:aa:9b:aa", ATTR{type}=="1", KERNEL=="eth*", NAME="eth0"

# PCI device 0x8086:0x1026 (e1000)
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="00:0e:0c:aa:c0:a8", ATTR{type}=="1", KERNEL=="eth*", NAME="eth1"
Comment: excuse me for the formatting. I'm not able to allow line breaks.
Comment: It is probably an issue on 6.5, it worked fine on older version 6.4.
Answer: It is probably an issue with CentOS 6.5.
It worked fine when tried on CentOS 6.4. The IPs on the interface are retained.


Views bonus pack CSV export internal server error

Question: I'm using the CSV export feature in the views bonus pack, but when I go to the path I set up for it I get this error message:
"The website encountered an error while retrieving http://something.com/csv. It may be down for maintenance or configured incorrectly."
I'm successfully using this module on a different site, and as far as I can tell they have the same configurations. It used to work on this site and recently broke for no apparent reason. Any ideas on what the potential points of failure might be to cause this error?
Comment: You should post details, like the error message from the logs
Comment: Not sure why I'm getting down votes. There are no errors in the log. Is there some information I'm not thinking of I should include?
Comment: Try going to the url and see what happens
Comment: I navigate to the url and it loads for 5 or so seconds, then gives me a 500 error, but nothing in the log.
Answer: Apparently the problem was Theme Developer being on.
Answer: The error is caused because you're having an internal server error (fatal PHP error) on the URL it's trying to use. The reason is most likely faulty data, you can find the exact cause by looking in the error log of your webserver.


Constructing an $R$-algebra from an $R$-module, and their relation

Question: Let $R$ be a commutative ring, and let $M$ be an $R$-module. Then every $r \in R$ could be seen as a group endomorphism on $M$, i.e. we have a natural map $f : R \to \operatorname{End}(M)$. This map is a ring homomorphism, and so by setting $r\cdot \varphi := f(r)\varphi$ for $\varphi \in \operatorname{End}(M)$ we have an action of $R$ on $\operatorname{End}(M)$, which gives us an $R$-algebra.
Is there anything known about the relation of this $R$-algebra to the module $M$, some theorems relating those two?
Comment: Yes, of course, one is the endomorphism ring of the other. There are tons and tons of results relating endomorphism rings and their moduls, if one has property A then the other has property B, and many of these can be found in most Algebra textbooks. Could you thus maybe clarify what exactly you are looking for?
Comment: @DirkLiebhold Sorry, I do not know of any results. Would you mind citing one? The relation here is between the module and an associated algebra, so not directly the endormorphism ring itself...
Comment: In many cases, $f$ will be injective. In this cases, you don't have to worry about the difference between endomorphism ring and algebra. The cases where $f$ is not injective get a little bit more complicated, yes, but I'm sure there are still nice results for that one (I just don't have an algebra textbook at hand right now to look them up).
Answer:
we have an action of $R$ on $\operatorname{End}(M)$, which gives us an $R$-algebra.

No, not quite. To make $End(M)$ an $R$ algebra, the map $f$ would have to map into the center of $End(M)$.
For example, $\mathbb H$ is a $\mathbb C$ module, and has such a map, but there is no map of $\mathbb C$ into the center of $\mathbb H$. $\mathbb H$ is not a $\mathbb C$ algebra.
The map $f$ you are talking about is a well-known equivalent way of defining what it means to be an $R$ module. You can either specify all the axioms about how the addition and multiplication works, or you can say "a ring homomorphism from $R$ into $End(M_\mathbb Z)$."
As for your last question, let me say this. There is not such a tight connection between $M_R$ and $End(M_\mathbb Z)$, other than the property we mentioned that $End(M_\mathbb Z)$ contains a homomorphic image of $R$.
The really interesting relationship is between $M_R$ and $End(M_R)$. You can say lots of things about that relationship. For example, the direct summands of $M_R$ correspond to idempotent elements of $End(M_R)$.
Every once in a while, some structure in $M_R$ can tell you a lot about the structure of $End(M_R)$. For example, if $M_R$ is simple, $End(M_R)$ is a division ring; if $M_R$ is semisimple, then $End(M_R)$ is von Neumann regular; if the submodules of $M_R$ are linearly ordered, then $End(M_R)$ has either one or two maximal right ideals.
Those are just the ones off the top of my head... to be sure there are more.


In hook_form_alter(), how can I access the entity that is being flagged?

Question: In hook_form_alter(), I want to load the entity being flagged so that I can do some processing based on the field values of that entity.
However, I can't find an entity object using kint($form).  I know it must be there somewhere because the flag is correctly attached to the entity.
function MYMODULE_form_flagging_MYFLAG_add_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  kint($form);
  kint($form_state);
  // Where is the flagged entity object id?
}

On the flagging object, after the flagged has been saved, the entity id can be accessed like this:
    $flagged_entity_id = $flagging->get('entity_id')->value;

However, in hook_form_alter(), when the flag has not yet been saved for the first time, I can't find the entity_id in $form.
I thought it might be in $form_state, but I got a NULL result for $form_state->get('entity_id').
Comment: Don't you have the flag in `$form_state->getFormObject()->getEntity()` and from there can get the flagged entity? Idea taken from https://drupal.stackexchange.com/a/297990/15055
Comment: Also taken from his other question [here](https://drupal.stackexchange.com/a/297681/27710) @leymannx
Answer: Ok, thanks to leymannx and No Sssweat, I think I finally understand how to get the entity from a form.
To get the entity being flagged inside a flag, this is what I had to do:
function MYMODULE_form_flagging_MYFLAG_add_form_alter(&$form, FormStateInterface $form_state, $form_id) {
      $flagging_entity = $form_state->getFormObject()->getEntity();
      $flagged_entity_id = $flagging_entity->get('entity_id')->value;
}


map is not a function returning div inside ternary operator

Question: I'm trying to do a little react app pulling some uniswap crypto data for my own UI just for fun, I've grabbed some data with a graphql query and I'm trying to render it out on the condition that its loaded which I get from a ternary operator in my functional component.
when I try this in multiple combinations, I just get the error that allTokenData.map is not a function
I have included my component below and I have notated where my mapping function is trying to pull data from the array I get back from graphql, since I'm getting data I'm sure I'm just mixing something up with the mapping syntax :/
here is a snippet of the data I'm grabbing for reference logged in the console, any help is appreciated

function CoinData(props) {

  //fetch whichever coin we want to add
  const NEWCOIN_QUERY = gql`
  query tokens($tokenAddress: Bytes!) {
    tokens(where: { id: $tokenAddress }) {
      derivedETH
      totalLiquidity
    }
  }
`;

  const { loading: ethLoading, data: ethPriceData } = useQuery(ETH_PRICE_QUERY);
  const { loading: allLoading, data: allTokenData } = useQuery(QUERY_ALL_TOKENS);
  const { loading: coinLoading, data: coindata } = useQuery(NEWCOIN_QUERY, {
    variables: {
      tokenAddress: props.parentState.newcoins!== '' ? props.parentState.newcoins.toString() : '0x6b175474e89094c44da98b954eedeac495271d0f',
    },
  });

  const coinPriceInEth = coindata && coindata.tokens[0].derivedETH;
  const coinTotalLiquidity = coindata && coindata.tokens[0].totalLiquidity;
  const ethPriceInUSD = ethPriceData && ethPriceData.bundles[0].ethPrice;
  console.log(props.parentState.newcoins)

  return (

        coin price:{" "}
        {ethLoading || coinLoading
          ? "Loading token data..."
          : "$" +
            // parse responses as floats and fix to 2 decimals
            (parseFloat(coinPriceInEth) * parseFloat(ethPriceInUSD)).toFixed(2)}

        Coin total liquidity:{" "}
        {coinLoading ? "Loading token data...": parseFloat(coinTotalLiquidity).toFixed(0)}

//////////////////////////////////////////----map function////////////////////////////
            {allLoading ? "Loading token data...":

                        {allTokenData.map((token, index) => (

 {token.id} SYN: {token.symbol}

                        ))}

            }
//////////////////////////////////////////----map function////////////////////////////

  );
}

Comment: I think the function `useQuery` is async. Therefore, `allTokenData` can be `undefined` or `null` (depends on the implementation)
Comment: I suspect that `allTokenData` is not an array. Test this with a `React.useEffect(() => console.log(allTokenData), [allTokenData]);`.
Comment: useQuery(QUERY_ALL_TOKENS); where is that query that you pass to useQuery?
Answer: maybe allTokenData.tokens.map.
Comment: this actually was the correct format to use in my case thanks a bunch!
Answer: It is because allTokenData is an object.
const {tokens} = allTokenData
{tokens.map((token, index) => (

 {token.id} SYN: {token.symbol}

                        ))}


Tag Audio não funciona no Phonegap

Question: Tag audio não funciona no Phonegap utilizando o formato AACP, em MP3 funcional normalmente.
<audio src="http://22.214.171.124:9984/;stream.nsv" controls autoplay></audio>

Alguém sabe o porque disso?
Answer: Porque a tag audio, por enquanto, suporta somente três formatos de arquivos: .mp3, .wav e .ogg. Há suporte pra reprodução de .aac também, mas somente em um container MP4.
Nessa página você pode ver alguns testes realizados com esses formatos.
E a especificação.

Tag Audio não funciona no Phonegap


Scala iterate over a set of objects

Question: I have a sealed trait which is implemented by 3 objects
sealed trait MyTrait {
...
}
object A extends MyTrait { ... }
object B extends MyTrait { ... }
object C extends MyTrait { ... }

I'm using Scalaz's validation mechanism wherein the apply methods of the objects A, B and C return a validated type. the Objects A, B and C does contain some logic and I want to apply this logic sequentially, i.e., I want to first apply A and check what the result of A is and based on it, decide if I want to call B or just return the validated result. I want to repeat this until I hit C after which I just return whatever I get as a result of calling C.
Currently I have a static approach where I first call A, pass the result of A to a utility method and check for the result and then call B.
  def apply(request: Request): Validated[Result] = {
    val vResultA = run(request, A)
    val vResultB = if (isResultOk(vResultA)) run(request, B) else vResultA
    if (isResultOk(vResultB)) run(request, C) else vResultB
  }

Is there a better way to do this? Any suggestions or any patterns that I can apply?
Answer: We will define succeeded results = results that are OK, and failed results = results that are not OK.
First, A, B, and C are all objects extending MyTrait. Therefore, they can be grouped into an Array or a List of MyTrait.
val objects = Array(A, B, C) /* You can use List instead if you want. */

Then the type of objects is Array[MyTrait].
Next, we have to iterate on this Array.
However, just calling map on this Array continues mapping even if the previous isResultOk() is false.
Therefore, we will use Stream instead of Array.
Let's see how using Stream can stop calling map if some condition is satisfied.
Array(1, 2, 3, 4, 5).map(i => {
    println(i)
    i + 100
  }).takeWhile(_ <= 103).foreach(println(_))

The output of the above code will be:
1
2
3
4
5
101
102
103

So, map() ends, and then takeWhile() ends -- takeWhile() does not affect calling map().
However, if we do the same operations on the Stream,
Array(1, 2, 3, 4, 5).toStream.map(i => {
    println(i)
    i + 100
  }).takeWhile(_ <= 103).foreach(println(_))

The output will be:
1
101
2
102
3
103
4

So the calling will be map() -> takeWhile() -> foreach() -> map() -> takeWhile() -> ...
At the end, 4 is printed, and 4 + 100 = 104 > 103 will be cut in takeWhile().
The following elements will be not accessed further.
So, do we have to use takeWhile?
objects.toStream.map(run(request, _)).takeWhile(isResultOk(_))

This will get rid of failed results, even though we need the first failed result if failure occured.
(i.e. This will make a problem if there is any result that is not OK.)
How about the opposite function dropWhile()?
objects.toStream.map(run(request, _)).dropWhile(isResultOk(_))

This will get rid of all succeeded results, even though all results are succeeded.
(i.e. This will make a problem if all results are OK.)
So, we will use span().
c.span(p) = (c.takeWhile(p), c.dropWhile(p))
We will test if there are results that are not OK.
If there is a result that is not OK, then we will return the first such result.
Otherwise, we will return the last result that is OK.
val (succ, fail) = objects.toStream.map(run(request, _)).span(isResultOk(_))
fail.headOption.getOrElse(succ.last)

fail.headOption will return Some(fail's first element) if fail is not empty, otherwise None.
In summary,
val objects = Array(A, B, C)

def apply(request: Request): Validated[Result] = {
  val (succ, fail) = objects.toStream.map(run(request, _)).span(isResultOk(_))
  fail.headOption.getOrElse(succ.last)
}

Comment: What is the advantage here of using Streams? How different are they from the Collection API?
Comment: Looks like the call happens only once with the Object A. Rather I want it to work in such a way that if Result of object A is false or failure, try the request with Object B and so on.

Scala iterate over a set of objects


Faster phpunit-bootstraping for single Unit-Tests

Question: My team and I started on Drupal some months ago. As we began creating our own modules, I also wanted to test them, but was very annoyed by the Performance of the tests - or better: of the Performance of core/tests/bootstrap.php:

It takes about 35 seconds after entering the phpunit-command until the tests have passed.
The Unit-Tests themselves in my modules take 1-2 Seconds to pass.
All the other time is spent in building up phpunit, especially in core/tests/bootstrap.php#drupal_phpunit_populate_class_loader()

The reason: Although I only want to test my module, bootstrap.php scans every path in all the modules, profiles and themes in core and contrib for populating $GLOBALS['namespaces']. IMHO, 30seconds of bootstraping for any tests prohibits fast and often testing and therefor makes test-driven development impossible.
I found that I can significantly improve the performance by calling phpunit with the UnitTest-Folder as argument (phpunit modules/custom/modulename/tests/src/Unit) and  changing $paths in drupal_phpunit_contrib_extension_directory_roots():
  $paths = [
//    $root . '/core/modules',
//    $root . '/core/profiles',
//    $root . '/core/themes',
//    $root . '/modules',
//    $root . '/profiles',
//    $root . '/themes',
      $root . '/modules/custom',
      $root . '/themes/custom'

With this change, bootstraping the tests takes about 1-2 seconds, which would be accetable for me.  But it works only for UnitTest, Kernel- and Browser-Tests run no more.
So my questions:

Is bootstraping of around 30sec for running of phpunit under drupal considered as 'normal' or is this a sign of something broken in my installation?
Is there any proposed way to reduce bootstraping time when doing only UnitTests?
I suppose I could create a second phpunit.xml, referring to an alternative core/tests/bootstrap.php with a $paths, which is reduced to our custom modules. And then, I would call phpunit with -c-option for the alternate phpunit.xml and the Unittest-Folder as argument. Is this a good idea or a sure way to shoot myself in the foot?

======
Update: Thanks to the Feedback from Kevin, I once more investigated why core/tests/bootstrap.php took so long to populate the classloader: The culprit is not bootstrap.php/drupal, but vagrant/virtualbox:
If I run the unit-tests from outside vagrant, they run in 1-2 seconds, as it seems normal to me (and is along what Kevin said)
If I run them inside the vagrant, the they take >30seconds.
The difference is in bootstrap.php, when drupal_phpunit_find_extension_directories() iterates over all Module-, Profile- and Theme-Directories in core, contrib and sites. Those directories are mounted via the Sync Folder-Feature by Vagrant, where there is a known performance-issue with Virtualbox.
Therefore, I renounce from hacking core :)
Comment: This sounds wrong. Unit tests execute very quickly as its only running raw code, there is no full Drupal bootstrap like Kernel or Functional tests. I can run 100 unit tests on my projects in a few seconds or less. phpunit can take arguments of which types of tests to run. Make sure your  directive in phpunit.xml is set only to the path(s) of your custom module folder.
Answer: Kernel and Functional tests are expected to take longer because of a full Drupal bootstrap and site scaffolding per run to test in a clean environment. Unit tests are running raw code and should execute very quickly. I can run a few hundred of them in a matter of seconds.
Ensure your phpunit.xml file is set up correctly. For example, scanning for tests only in the custom module directory:
<testsuites>
    <testsuite name="unit">
      <directory>web/modules/custom/*/tests/src/Unit</directory>
    </testsuite>
    <testsuite name="kernel">
      <directory>web/modules/custom/*/tests/src/Kernel</directory>
    </testsuite>
    <testsuite name="functional">
      <directory>web/modules/custom/*/tests/src/Functional</directory>
    </testsuite>
  </testsuites>

Or running a specific kind of test:
phpunit --testsuite unit

Other than that something is wrong with your setup. It should never take 30 seconds to kickstart a unit test. Make sure you are not running with xdebug enabled and listening, etc.
(also, dont hack core!)
Comment: Thank you for your feedback. phpunit.xml was ok, as was my usage of the phpunit-command. The problem really could be isolated to core/tests/bootstrap.php, when it populates the classloader. But thanks to your feedback, I investigated this step again and found that the problem lies within vagrant and virtualbox, and not within bootstrap.php itself.
Comment: Just as an aside, altough now only theoretical: If I use my own phpunit.xml (copied from core to drupal-root and then altered), and refer to another bootstrap.php (copied from core/tests, and then altered), would this still be considered hacking core? The original files would be left unchanged.
Comment: I don't know what the use case is for that.


Using password recommendations code

Question: I've got a Drupal 9 site where I'm adding a form that will add a user  to the Drupal site and also to an external database. I'd like to be able to use the same mechanism that you see in the Add user form which shows recommendations for the password, and removes individual recommendation items as the entered password passes them.
Is there an API for using Drupal Core's code for this in my own forms?
Comment: This is the form element: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21PasswordConfirm.php/class/PasswordConfirm/10. I don't know whether the JavaScript tests automatically activate if you use it.
Comment: This is a broad recommendation question, probably off-topic and will be closed because of it. First step you need to take yourself is to find that piece of code in core that does it and then try to copy this to your custom implementation. If this doesn't work, find out why and show some code so we can help you move forward from there.
Answer:
Is there an API for using Drupal Core's code for this in my own forms?

Using the password_confirm form element, you automatically get the JavaScript code that does what you described. The function that adds the necessary JavaScript code is user_form_process_password_confirm(), but you do not need to call it, as that is a process hook that is automatically invoked for that form element.
function user_form_process_password_confirm($element) {
  $password_settings = [
    'confirmTitle' => t('Passwords match:'),
    'confirmSuccess' => t('yes'),
    'confirmFailure' => t('no'),
    'showStrengthIndicator' => FALSE,
  ];

  if (\Drupal::config('user.settings')->get('password_strength')) {
    $password_settings['showStrengthIndicator'] = TRUE;
    $password_settings += [
      'strengthTitle' => t('Password strength:'),
      'hasWeaknesses' => t('Recommendations to make your password stronger:'),
      'tooShort' => t('Make it at least 12 characters'),
      'addLowerCase' => t('Add lowercase letters'),
      'addUpperCase' => t('Add uppercase letters'),
      'addNumbers' => t('Add numbers'),
      'addPunctuation' => t('Add punctuation'),
      'sameAsUsername' => t('Make it different from your username'),
      'weak' => t('Weak'),
      'fair' => t('Fair'),
      'good' => t('Good'),
      'strong' => t('Strong'),
      'username' => \Drupal::currentUser()->getAccountName(),
    ];
  }

  $element['#attached']['library'][] = 'user/drupal.user';
  $element['#attached']['drupalSettings']['password'] = $password_settings;

  return $element;
}

There is no need to add any specific CSS class to the form element, as that is already done from PasswordConfirm::processPasswordConfirm().
  $element['pass1'] = [
    '#type' => 'password',
    '#title' => t('Password'),
    '#value' => empty($element['#value']) ? NULL : $element['#value']['pass1'],
    '#required' => $element['#required'],
    '#attributes' => [
      'class' => [
        'password-field',
        'js-password-field',
      ],
      'autocomplete' => [
        'new-password',
      ],
    ],
    '#error_no_message' => TRUE,
  ];
  $element['pass2'] = [
    '#type' => 'password',
    '#title' => t('Confirm password'),
    '#value' => empty($element['#value']) ? NULL : $element['#value']['pass2'],
    '#required' => $element['#required'],
    '#attributes' => [
      'class' => [
        'password-confirm',
        'js-password-confirm',
      ],
      'autocomplete' => [
        'new-password',
      ],
    ],
    '#error_no_message' => TRUE,
  ];

To use a password_confirm form element, you just need to define the form element using code similar to the following one. (It is the code used by the User module for the account password.)
$form['account']['pass'] = [
  '#type' => 'password_confirm',
  '#size' => 25,
  '#description' => $this->t('To change the current user password, enter the new password in both fields.'),
];

As side note, the password_confirm form element must not be confused with the password form element, which shows a single text field to enter a password, without the second text field to confirm it. It does not show the strength indicator either.

Using password recommendations code


Proof of $A\left [ \left [ x \right ] \right ]$ PID implies $A$ is a field

Question: It is a well known result that $A$ (commutative ring with 1) is a field if and only if $A\left [ x \right ]$ is PID. Now, while reading about the formal power series ring $A\left [ \left [ x \right ] \right ]$, I found this result: Let $A$ be a commutative ring with 1. if $A$ is a field, then $A\left [ \left [ x \right ] \right ]$ is a PID and a local ring. Now, $A\left [ x \right ]$ PID implies that A is a field, which made me wonder if the same is true for $A\left [ \left [ x \right ] \right ]$. In other words:

If $A\left [ \left [ x \right ] \right ]$ is a PID and a local ring, then $A$ is a field. proof:
Let $m$ be the maximal ideal of $A\left [ \left [ x \right ] \right ]$. Then, it is true that $m=A\left [ \left [ x \right ] \right ]-units\left ( A\left [ \left [ x \right ] \right ] \right )$. Now, an element $\sum_{0}^{\infty }a_nx^n $ in $A\left [ \left [ x \right ] \right ]$ is a unit if and only if $a_0$ is a unit in $A$. Then, in order to check that $A$ is a field, i would need to check that $m=\left ( x \right )$. Now, because $A\left [ \left [ x \right ] \right ]$ is local, i should only check that $\left ( x \right )$ is maximal. Now, because we are in a PID, this ideal is maximal if and only if $x$ is irreducible in $A\left [ \left [ x \right ] \right ]$. But i think i could show that, because: if it were $x=f.g$, with $f =\sum_{0}^{\infty }a_nx^n $, $g = \sum_{0}^{\infty }b_m x^m $, then $a_0=b_0=0$ is impossible, because then it would be $f.g=x^2.h$, with h in $A\left [ \left [ x \right ] \right ]$. It is also impossible that $a_0 \neq 0 \neq b_0$, because then the independent term of $f.g$ would be $a_0.b_0 \neq 0$ (because $A\left [ \left [ x \right ] \right ]$ is a PID, so it is an integral domain). Then, only one of the two elements $f,g$ can have a non zero independent term. WLOG, let it be $a_0$. then, the first term of $f.g$ should be $a_0.b_1x$, that should be equal to $x$. then, $a_0.b_1 = 1$, and $a_0$ is a unit, so $f$ is a unit, and $x$ is irreducible in $A\left [ \left [ x \right ] \right ]$.
Then, the non units of $A\left [ \left [ x \right ] \right ]$ would be the ones that have $a_0 = 0$ (independent term equal to zero), so every $a\in A$ not equal to zero should be a unit, so A would be a field.

So then:

Is my reasoning ok?
Is it redundant to ask $A\left [ \left [ x \right ] \right ]$ to be local? Does being $A\left [ \left [ x \right ] \right ]$ a PID imply that $A\left [ \left [ x \right ] \right ]$ is local? (This question arises mainly because i initially found that $A$ is a field $\rightarrow$ $A\left [ \left [ x \right ] \right ]$ is a PID)

(Note: I also tried a proof without asking that the power series ring is local, by adapting the reasoning made for the polynomial ring A[x]. However, in certain part the author uses the fact that $f.g = a$ implies that the degree of $f$ is zero. However, i think this is false for the power series ring, because $\left ( 1-x \right ).\left ( 1+x+x^2 +... \right ) = 1$.)
Comment: Your reasoning seems good to me. If $A$ is not a field I believe it should be possible to have multiple maximal ideals in $A[[X]]$ of the form $(a_0)$, where $a_0\in A\setminus A^\times$. So I think you have to assume locality.
Answer: You are overcomplicating things.
If $A[[X]]$ is a PID, then it is a domain, and thus so is $A$ (as a subring of a domain).
In this case $(X)$ is a non zero prime ideal: indeed,  taking constant terms induces a ring isomorphism $A[[X]]/(X)\simeq A,$ which is a domain.
But in a PID, nonzero prime ideals are maximal. Hence $(X)$ is maximal and the corresponding quotient, namely $A$,  is a field. Note that this proof works if we replace $A[[X]]$ by $A[X]$.
Now it is known that $K[[X]]$ is local with unique maximal ideal $(X)$ for any field $K$ (it follows directly from the fact that any power series with nonzero constant term is invertible in this case)


How can I get other content type data in current content type?

Question: I want to put one condition in my template file of contenttype1. The condition is if contentype2 contains a field value X then I want to print one block in contentype1. So how can I get contenttype2 field values in contenttype1 template file.  To get more clarity, with the contentype2 fields I am creating a views block. I want to display that block in contentytype1 template file. So I want to check a field condition of contentype2. If that field has any value then only I want to display that views block in contenttype1 otherwise it should not display. Thanks in advance for any suggestions.
Comment: `contenttype2` could contain 100 nodes. So which one of the 100 needs to have field value x? There needs to be some sort of specific relationship, how are you liking `/node/1` of `contenttype1` with `/node/15` of `contenttype2`?
Comment: with the contentype2 I am creating a views block. I want to display that block in contentytype1 template file. So I want to check one field condition of contentype2. if that field has any value then only i want to display that block in contenttype1 otherwise it should not display..
Comment: What is the contenttype1 ? Is it also views? Can you please elaborate your question with what data is what. Because, your question do not talk abt anything about views, and that is the significant point. So, answerer can get better idea how data is designed so he/she can give better answer.
Comment: @Suraj How are you **linking** these 2 nodes? Are you using entity reference? Taxonomy term reference?
Comment: @No Sssweat I am not linking these two contenttypes. but I am using the views block in contentype1.
Comment: let me ask you this `contenttype1` has `node/1`, `node/2`, `node/3` and `contenttype2` has `node/4`, `node/5`, and `node/6`. So when you visit `node/1` which `contentype2` node should we check for field value x? check all of them `node/4`, `node/5`, and `node/6`? or is there specific relationship, `node/5`only?
Comment: @No Sssweat Thank you for your support. I want to check condition for all the nodes.
Answer: What you need to do is make X a taxonomy term.
1) Go to taxonomy and create a vocabulary (ex: Colors)
2) Inside Colors vocabulary, add terms. (ex: Red, Blue, Green, Yellow etc..)
3) Go to contentype1 manage fields and add a new field of type: Taxonomy Term Reference. Then select the vocabulary (colors).
4) Now edit your contentype1 nodes and give them a taxonomy term. Ex: Node 1 blue, Node 2 red, Node 3 blue, ...etc
5) Repeat steps 3) and 4) but with contentype2 this time.
6) Create a block view of contenttype2 (You will see it lists all the contentype2 nodes)
7) Under Advanced, add Relationship of Terms of the node, checkmark Colors and checkmark require relationship.
8) Add a contextual filter of Taxonomy Term and for when filter is not available, set it up like this (using screenshot from another answer):

Once you add the contextual filter, your view preview will go blank, which is normal. Go to a contentype1 node, where you placed the view block, and you should see contenttype2 nodes that have the same taxonomy term as the current contentype1 node that you're viewing.


Fixing bad dates in multi record table

Question: I have a dataframe where it has records of participation data with start and end dates. Sometimes there are bad dates such as below:
<code>+--------+------------+-----------+
|   ID   | Start_Date | End_Date  |
+--------+------------+-----------+
| ABC123 | 1/2/2018   | 6/1/2020  |
| ABC123 | 5/1/2027   | 12/2/2017 |
| ABC123 | 1/1/2015   | 4/5/2017  |
+--------+------------+-----------+
</code>
Is there a script that would replace the bad start date with the end date of previous record to make it look like the table below
<code>+--------+------------+-----------+
|   ID   | Start_Date | End_Date  |
+--------+------------+-----------+
| ABC123 | 1/2/2018   | 6/1/2020  |
| ABC123 | 4/5/2017   | 12/2/2017 |
| ABC123 | 1/1/2015   | 4/5/2017  |
+--------+------------+-----------+
</code>
Answer: Arc89, I think it will be easier to write your own function. Take a look at this:
<code>def get_correct_dates(row):
    """ this function checks if start date is past the end date, if yes it takes the previous date"""
    if pd.isna(row["prev_End_Date"]):
        return row["Start_Date"]

    if row["Start_Date"] > row["End_Date"]:
        return row["prev_End_Date"]
    else:
        return row["End_Date"]

df["prev_End_Date"] = df.groupby("ID")["End_Date"].shift(-1)
df["Start_Date"] = df.apply(lambda row: get_correct_dates(row), axis=1)
df.drop("prev_End_Date", axis=1, inplace=True)
</code>

Fixing bad dates in multi record table


Restrict translation and editing of node to one language

Question: Edit
I found this in Workbench Access issue queue:
https://www.drupal.org/project/workbench_access/issues/2982941#comment-12670744
It seems as if I need to deactivate the translate *bundle* *node* permissions, because if those are set, the permission will be short circuited and no other access restrictions may apply, and create a hole bunch of new *translate *bundle* *node* *language* permissions on my own. In my case we have 15 node types and 6 languages. That would result in 90 new permissions. That is overwhelming.
Original Question
I'm trying to restrict the access to creating and editing of nodes in the Drupal admin section to only one language for a user. I didn't find a module which provides for this feature. Is there any module that does this?
I then tried to create my own module. I came up with this solution
File: custom_i18n_access.module
<?php

use Drupal\node\NodeInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResult;

/**
 * Implements hook_node_access().
 *
 * Prevent editor role to edit and/or delete fr/en nodes. Quick and dirty.
 */
function custom_i18n_access_node_access(NodeInterface $node, $op, AccountInterface $account)
{

    $roles = $account->getRoles();

    if (in_array('administrator', $roles)) {
        return AccessResult::neutral();
    }

    if ($op !== 'update' && $op !== 'delete') {
        return AccessResult::neutral();
    }

    // Access should be restricted only if this permission is set
    if (!$account->hasPermission('custom_i18n_access_restrict')) {
        return AccessResult::neutral();
    }

    $current_language = \Drupal::languageManager()->getCurrentLanguage();
    $lang             = $current_language->getId();

    if ($account->hasPermission("custom_i18n_access_{$lang}_allow")) {
        return AccessResult::neutral();
    }
    return AccessResult::forbidden();
}

File: custom_i18n_access.permissions.yml
permission_callbacks:
  - Drupal\custom_i18n_access\Permissions::permissions

File: src/Permissions.php
<?php

namespace Drupal\custom_i18n_access;

class Permissions {
    public function permissions() {
        $languages = \Drupal::languageManager()->getLanguages();

        $permissions["custom_i18n_access_restrict"] = [
            'title' => t("Restrict language access"),
            'description' => 'Restrict the edit access of nodes',
        ];

        foreach($languages as $lang) {
            $permissions["custom_i18n_access_{$lang->getId()}_allow"] = [
                'title' => t("Allow to edit @lang content", ['@lang' => $lang->getName()]),
            ];
        }

        return $permissions;
    }
}

This custom module successfully restricts the editing and deleting of existing content to only the language I specified in the permissions. But it does not prevent new translations of the content into  other languages.
As I see it, the HOOK_node_access hook is not called for every language when on the translations subtask page. How can I achieve this? Is there a different hook for that? I didn't find any help online.
Comment: Not sure if feasible, but you can restrict language for users https://www.drupal.org/project/language_access
Comment: @ales I think this is for view. I need edit.
Answer: I would suggest here checking NodeTranslationHandler class, in entityFormAlter you could find a way how to restrict a user from creating a new translation.
Comment: Thanks for your answer. I'll take a look into it.
Comment: Basically, each entity type is using their own translation handler ContentTranslationHandler, you could try to even override this handler using hook_entity_type_alter() f.e.                                                                                `/**
 * Implements hook_entity_type_alter().
 */
function MY_MODULE_entity_type_alter(array &$entity_types) {
  $entity_types['node']->setHandlerClass('translation', CustomTranslationHandler::class);
}`


GTK+: GtkTreeView: passing extra data when a cell gets clicked

Question: I am quite new with GtkTreeView. I am creating one single column with multiple rows, and I am detecting when the user is clicking on each row (or cell in this case).
I am able to retrieve the label from the cell but it is not merely enough for what I need to do. I have a struct that contains a few extra parameters that I would like to pass along. I am currently using a callback on the whole tree, as follows:
GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(list));
g_signal_connect(selection, "changed", G_CALLBACK(on_changed), selection);

I append rows in my TreeView. Would it be possible to create a unique signal per row where I could pass my struct as the parameter please? Otherwise, is there another way to pass data for the function? The problem is that each row has a unique struct that contains different information.
Thank you very much.
EDIT:
I had not understood all the power of the TreeView. I've put everything in my model now and it works just fine. Sorry guys, I now understand the model a lot better.
Comment: I fixed my problem: I had not understood all the power of the TreeView. I've put everything in my model now and it works just fine. Sorry guys, I now understand the model a lot better.
Answer: Although you have found your answer just adding a couple of points which you might find useful:
1. When you are connecting a callback for a signal to a widget it is redundant to pass the widget to which you are connecting the callback as data. In g_signal_connect(selection, "changed", G_CALLBACK(on_changed), selection); passing selection as data is redundant as the callback function for "changed" signature has the first parameter as GtkTreeSelection * through which you will get pointer to selection. AFAIK this is true for all the signal callbacks; you will find that there is GtkWidget  * (or pointer to the object for which signal callback was connected) parameter in the callback function through which will get the object for which the signal was received.
2. If you already didn't know, what you found out on your own is Model-View-Controller or MVC implementation in GtkTreeView. In this pattern, the data logic, UI & input-interaction logic are separated. GtkListStore & GtkTreeStore represent the model which hold your data. Thus to add any kind of data you make use of these. The view or the UI in this case consists of GtkTreeView, GtkCellRenderer etc. And of course, you control the interactions through handling user inputs with the aid of signals & callbacks.
Hope this helps!
Comment: Thanks a lot. I did not know about 1) and I fixed it. That's what I discovered for 2), I hadn't completely understood the separation. Thanks a lot for your help!


How to add a referenced taxonomy term name to the node title in page-title.html.twig

Question: Using a term reference field, I am adding the manufacturer's name to the front of our node titles in views for styling and line breaks between the manufacturer field and the title which is really nice. For the node display titles, I am currently using a block view for the manufacturer's name, and placing it above the page title block in the block layout. This stacks the Manufacturers name above the Node title which i don't really prefer:
Manufacturer
Some Node Title
I would like to add the field_manufacturer field to the node display title as a prefix so that it is inline and not stacked like my example above, and I need to add a class to it so that I can target and style it. I am not sure which twig file is responsible for rendering the title, so I would really appreciate help marking this up properly.
Thanks!
Comment: Do you want to add field_manufacturer` to the title in all views (teaser, full page, etc), or just certain views? I'm not 100% sure but... To change the title on the node's full page view, you can implement `template_preprocess_page_title(&$variables)` and change `$variables['title']`. The template file for theming the page title is `page-title.html.twig`. To change the title field in a view like the `teaser`, I think you would implement `template_preprocess_node(&$variables)`, and change `$variables['label']`. In this case, the template file would be `node.html.twig`.
Comment: I am looking to change the node title on the default node display. Could you explain "To change the title on the node's full page view, you can implement template_preprocess_page_title(&$variables) and change $variables['title']. " in more detail?
Answer: Posting this answer to help those trying to accomplish the same thing. I was told the code above had security vulnerabilities (which has since been removed see comments below).  On the Drupal Slack channel, someone pointed out the following concern with runwithscissors' answer:

"This code is potentially dangerous:$variables['title'] = \Drupal\Core\Render\Markup::create($new_title); A user could set  as the Node or Term title and potentially execute code on the site. Typically you don't want to ever create Markup objects manually. For what you're doing, I'd suggest setting $term_name to a new key in $variables, then forming your combined title in the Twig template like {{ term_name}} {{ title }}"

So what i ended up doing was adding this template_preprocess_page_title to my MY_SITE.theme file.
(Note: field_manufacturer is the specific field for my use case, so you would need to change all instances of that to your taxonomy reference field name.)
/* Add field_manufacturer to all node titles with field_manufacturer and not empty */
function template_preprocess_page_title(&$variables) {
   $node = \Drupal::request()->attributes->get('node');
   if ($node && $node->hasField('field_manufacturer') && !$node->field_manufacturer->isEmpty()) {
     $term = \Drupal\taxonomy\Entity\Term::load($node->get('field_manufacturer')->target_id);
     $term_name = $term->getName();
     $variables['term_name'] = $term->getName();
   }
 }

This applies to all nodes with the field_manufacturer, but also checks that the term field is NOT empty with && !$node->field_manufacturer->isEmpty()). This was critical as the reference field was not required, so nodes that had the field but didn't have a value crashed the site with Error: Call to a member function getName() on null in template_preprocess_page_title()
Then I copied and overwrote the page-title.html.twig file from my bootstrap base theme which originally renders the title like this:
{% if title %}

{{ title }}

{% endif %}

And changed the H1 title line to this:
{% if title %}

    {% if term_name %}
      {{ term_name }}
    {% endif %}
  {{ title }}

{% endif %}

This adds a MY-DESIRED-CLASS-NAME span class to the term_name. Also by putting it within {% if term_name %}/{% endif %} statement, it prevents that class from being rendered in the html where there is no term_name present.
Hope this helps someone!
Comment: Thanks for the thought, but don't worry about removing your up-vote from my answer. I set the title of a node to `` and confirmed that using `Markup::create()` will cause the script to execute. I also now realize that the `span` elements should be added in the template and not the theme. When I searched for how to do the same thing you wanted, I came across many blog posts
 and up-voted answers using the `Markup::create()` method. It's clear that no one should do it that way. I deleted my post so no one else makes the same mistake I did, and up-voted your answer.
Comment: Cool. Thanks! Answer edited for clarity.
Answer: Would you want to use Automatic Entity Label to actually change the title?
Comment: No, I keep the manufacturer separate for line breaks and styling in views displays.


what is $L_{\omega_1} (x)$?

Question:
The class of all hereditarily countable sets can be proven to be a set from the axioms of Zermelo–Fraenkel set theory (ZF) without any form of the axiom of choice, and this set is designated . The hereditarily countable sets form a model of Kripke–Platek set theory with the axiom of infinity (KPI), if the axiom of countable choice is assumed in the metatheory. If $x \in H_{\aleph_1}$, then $L_{\omega_1}(x) \subset H_{\aleph_1}$.

What is $L_{\omega_1}(x)$? I heard of constructible universe, but that did not contain a thing like $(x)$....
Answer: When you see $L(x)$ or $L_\alpha(x)$, you're dealing with relative constructibility. Instead of starting from the empty set ($L_0=\varnothing$), you start from $TC(x)$, the transitive closure of $x$ ($L_0(x)=TC(x)$). Then you proceed just as in the construction of the constructible hierarchy: $L_{\alpha+1}(x)$ is the set of first-order definable subsets of $L_\alpha(x)$, and $L_\alpha(x)=\bigcup_{\xi<\alpha}L_\xi(x)$ for limit $\alpha$. The last statement that you quote says that if $x$ is hereditarily countable, every set constructible from $x$ in at most countably many steps is still hereditarily countable.
Comment: The last sentence should probably say "constructible from $x$..."
Comment: @Trevor: I was using *definable* informally, but you're right, I probably oughtn't.

what is $L_{\omega_1} (x)$?


DataBinding: 'System.Data.Objects.ELinq.InitializerMetadata'

Question: In controller;
var getSubjectClassList = (SMSEntitiesNew.Subjects).GroupBy(p => p.SubjectName).ToList();
SelectList listA = new SelectList(getSubjectClassList, "SubjectName", "SubjectName");
ViewBag.getSubjectClassList111111 = listA;

In Index.cshtml;
@Html.DropDownList("getSubjectClassList", ViewBag.getSubjectClassList111111 as SelectList, "Please select Subject", new { @class = "form-control" })

When running Application, I am getting the following error :-

DataBinding:
  'System.Data.Objects.ELinq.InitializerMetadata+Grouping`2[[System.String,
  mscorlib, Version=18.104.22.168, Culture=neutral,
Answer: I think you're getting error on these lines:
var getSubjectClassList = (SMSEntitiesNew.Subjects).GroupBy(p => p.SubjectName).ToList();
SelectList listA = new SelectList(getSubjectClassList, "SubjectName", "SubjectName");

The Enumerable.GroupBy method actually returns IEnumerable<IGrouping<TKey, TElement>> with Key property that provides key values(s) for grouped members and host IEnumerable interface which lets you iterate through all members inside the group. It doesn't give you IEnumerable<Subject> which you want to convert as SelectList instance.
If you want to insert unique SubjectName list into ViewBag that later converts to SelectList, you can perform Select query with Distinct and OrderBy like this:
var getSubjectClassList = (SMSEntitiesNew.Subjects).Select(p => new { p.SubjectName })
                                                   .Distinct()
                                                   .OrderBy(p => p.SubjectName).ToList();

Similar issue:
Entity Framework ORDER BY issue
Comment: If you're satisfied to someone's answer, you can click accept mark to mark your question solved. There's no obligation for doing this (https://stackoverflow.com/help/someone-answers).
Comment: Please mail me the steps.  The link  (stackoverflow.com/help/someone-answers), I am not getting the slution for marking accept. My mailid- firstname.lastname@example.com


Newsletter php (email com campos vazios)

Question: Alguém pode me ajudar por favor?
Eu vi isto na net e tentei aproveitar, no entanto no meu email recebo os campos "Nome:" e "Email:" mas estão completamente vazios, mas ao enviar eu envio com os campos preenchidos!
index.html
<form method="POST" action="newsletter.php">

                            <input type="text" class="text" value="Nome">

                            <input type="text" class="text" value="Email">

                            <input type="submit" value="submit">
                    </form>

newsletter.php
# RESULT PAGE
$location = "";

## FORM VALUES ##

# SENDER - WE ALSO USE THE RECIPIENT AS SENDER
# DON'T INCLUDE UNFILTERED USER INPUT IN THE MAIL HEADER!
# SEE ALSO: How to protect a php Email Form using php mail or mb_send_mail against Mail Header Injection
$sender = $recipient;

# MAIL BODY
$body = "Name: ".$_REQUEST['Nome']." \n";
$body = "Email: ".$_REQUEST['Email']." \n";
# add more fields here if required

## SEND MESSGAE ##

mail($subject, $body, "From: $sender" ) or die ("O email não pode ser enviado.");

## SHOW RESULT PAGE ##

header( "Location: $location" );
?>

Obrigado
Comment: Já alterei, o javascript fazia parte de uma outra abordagem, nada a haver :)
Comment: Se o método for sempre POST acho melhor trocar o $_REQUEST por $_POST.
Answer: Falta o atributo name nos seus inputs.
<input type="text" class="text" value="Nome" name="Nome">
<input type="text" class="text" value="Email" name="Email">

Sem falar no php que você substitui o conteúdo de $body na segunda vez que você atribui valor a ele. O certo seria algo assim:
$body = "Name: ".$_REQUEST['Nome']." \n";
$body .= "Email: ".$_REQUEST['Email']." \n";

Comment: Resolveu! Obrigado!
Comment: De nada, sempre que posso ajudo^^


Get the title attribute into a lightbox frame

Question: I've been exploring and getting somewhat close to what I want (getting the value of the title attribute into my lightbox frame) by reading documentation
and this topic here at Drupal Answers.
I'm working with a custom tpl.php file with the following code (copied from elsewhere):
   if($id == 'field_afbeelding') {
            $samples = explode(';', $fields['field_werken_afbeelding_sampl']->content);
            $originals = explode(';', $field->content);
            for($i = 0; $i < count($samples); $i++) {
                print l($samples[$i], $originals[$i], array('html' => TRUE, 'attributes' => array('rel' => 'lightbox')));
            }
        }

From what I gathered in the documentation, it appears that I need to insert the lightmodal[][] array-thing into my code right at the end, where it says array('rel' => 'lightbox').
In the Drupal Answers topic, the question starts off about how to insert a CCK field (or a caption or whatever) into a lightbox, but ends about how to get the title attribute.
The very last comment says - I quote : 'Type
<?php print_r($node); ?>
 in node.tpl.php to see what's available in the node object (what fields, how formatted, etc.) and then take what you want and output it to the lightbox. I hope that's what you need..'
In my case, it's a view, so I went with devel module, going <?php global $field; dpm($fields);?>
Now as for 'take what you want and output it to the lightbox', the problem is I don't recognize out of these clickable Krumo blocks what I need. I do get these Krumo blocks that the devel module shows where you can click in the them and explore those elements/objects/whatever you want to call them.
I've been expanding all of the arrays and been seing 'title' in nested arrays. I guess the question boils down to what exactly must I put in this lightmodal[][] array if I'm right about the lightmodal thing?
And, before you ask, I made sure than in CCK, when editing the image field, I have alt and title attribute checkboxes checked and also given values to the images at hand.
Comment: what format are you using for your view - content or fields? it sounds like you are using a node template and then displaying the results in your view as nodes so the relevant values would be in the $node object and not views / fields specific.
Comment: I'm using the fields format in my view. Is it normal that `` doesn't return anything? I get no errors either, just a blank green devel box.
The name of my template file is `views-view-fields--grafiek--page.tpl.php`
Answer: There are multiple issues for Lightbox about your problem. Atm your best chance is indeed to override the relevant tpl.php file. This would be in the form of views-view-field--viewid--fieldname.tpl.php. The variables exposed in there that are of interest are the following:

$output: The processed output that will normally be used.
$row: The raw SQL result that can be used.

The first one indeed contains a string in the form of:

The above should become something like this:

in order to have a caption in your lightbox.
You could of course use a replace function in order to achieve this, such as your attempted solution.
What I recommend is to use the $row variable to obtain the data itself and construct the output however you wish, for instance to add a title in  as well and why not solve the empty alt attribute value issue as well for the sake of SEO:
<?php
  //print $output;
  //dpm($output);
  //dpm($row);
  $caption = $row->taxonomy_term_data_name, // HERE use your field of choice
  print l(
    theme_image_style(array(
      'style_name' => 'thumbnail',
      'path' => $row->field_field_image[0]['raw']['uri'],
      'alt' => $caption,
      'attributes' => array('typeof' => 'foaf:Image'),
      'width' => NULL,
      'height' => NULL,
    )),
    image_style_url('large', $row->field_field_image[0]['raw']['uri']),
    array(
      'attributes' => array(
        'title' => $caption,
        'rel' =>
          'lightbox[field_image][
' . $caption . '
]',
      ),
      'html' => TRUE,
    )
  );
?>

Answer: You're using Views 3, Drupal 7 and creating a view with a fields format so you want to be using the views-view-fields--VIEWNAME template for row style output (all of which looks good so far). The change is that because you're using fields and not node, you won't have access to your $node variables within the views template and you want to use the $fields array.
Assuming that the title you want to add to the lightbox attribute is the same as the title of your node (and assuming you probably want the plain text version) you could access it as:
print $fields["title"]->raw;

If that's not the field you want, you can scan the fields array using devel with this:
dsm($fields);

Comment: Hi, if you check my (I admit a little long and clunky) question, you can see  I already did a `dpm($fields);`. In the output of that `dpm($fields);`,the title attribute of the image is inside of a string that is the entire html of the image and not a `key => value` structure that could be used.


Convert a yyyy-mm-dd to other date format in Javascript

Question: I am trying to convert "1983-24-12" to December 24, 1983 using Javascript.
Do we have any ready made function in Javascript which makes this conversion same as simpledateformat in Java?
I am trying to avoid taking months in Arrays and then do the manipulation.
My Code is as below.
//For Date Format
    months = ["", "January", "February", "March", "April", "May", "June",           "July", "August", "September", "October", "November", "December"];
    dob = responseObj.data.personDetail.birthDate.split('-');
    month = months[dob[1]];
    responseObj.data.personDetail.birthDate = month +" "+dob[2] +","+dob[0];

Kindly help.
Comment: There is a *Date.prototype.toLocaleString* method, but then you'd first have to convert the string to a date (not hard, but needs 2 or 3 lines of code) and then a call to *toLocaleString*. And then the method is implementation dependent so you get whatever the browser returns, which is different in just about every browser. Many also ignore local settings so return the US-centric month, day, year even if the system settings are for day, moth, year. So the method you are using is already probably as good as it gets.
Answer: If you don't want to use a library why not just split the date string and concoct your own date?
var str_date = "1983-24-12",
    arr_date = str_date.split('-'),
    months   = ['', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

alert(months[arr_date[2]] + ' ' + arr_date[1] + ', ' + arr_date[0]);

Demo: http://jsfiddle.net/9xeBZ/
JavaScript has the Date() object: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
The problem is that the JavaScript Date() object will not return a string representation of a month. So at some point you will have to create that logic yourself. Also the format you posted ("1983-24-12") is an invalid format for parsing with the Date() object.
Comment: BTW, *Date.prototype.toLocaleString* is implementation dependent, some browsers do return the full month name (e.g. Safari) and some don't.
Comment: Hi Jasper, I tried the same but trying to avoid taking the help from array. DO we have any simpledateformat kind of formatter function which helps us in this case? I am making a mobile website with Sencha framework
Comment: @HPK I updated my answer with the paragraph at the end. Also here is a link to a SO answer that shows how to add this functionality to your site via `Date.prototype`: http://stackoverflow.com/a/1643506/752738
Answer: This might help: Date Format Conversion
Comment: I am avoiding to try to put any library in my code which will unnecessary increase the size of my mobile website. I am trying if sencha provides any help..
Comment: Then could you show some of your codes... what have you tried..?
Comment: @HPK–if you are concerned about the size of your code, why on earth are you using bloatware like Sencha?
Answer: If I understand you right, you are trying to reformat your date for which a quick google search brought up this http://blog.stevenlevithan.com/archives/date-time-format which looks like what you want.
Answer: EDIT: Since you mentioned that you're using Sencha, you can use Ext.Date to add advanced date formatting and parsing:

A set of useful static methods to deal with date Note that if Ext.Date is required and loaded, it will copy all methods / properties to this object for convenience.

You can find more information here: http://docs.sencha.com/ext-js/4-0/#!/api/Ext.Date
The two methods you might find useful are parse and format

Alternatively, JQuery UI's DatePicker widget implements a very robust date parser and formatter, which can be used in your own code like this:
var parsedDate = $.DatePicker.parseDate("yy-m-d", "1983-24-12");
var outputString = $.DatePicker.formatDate("MM d, yy", parsedDate);
// outputString = "December 24, 1983"

The relevant functions here are parseDate and formatDate.
There is one problem though, to use this you'll have to include both JQuery and JQuery UI as scripts in your code, which is probably a little excessive for what you need, and the other answers may perhaps suit your needs better.
Comment: @HPK - I've edited my answer, I've added a bit about using Sencha Ext JS that might work for you :-)
Comment: I have used birthDate = date.dateFormat( "F d, Y" ); // Sencha DateObject. Thanks.


How do I use a preprocess function to add custom classes to a view fields?

Question: I have a View that outputs several fields per row. I'd like to use a preprocess function to add a class to one of the fields, depending on the value of another field. How do I do that in Drupal 8?
Note, I do not want to add a class to the entire row -- just a specific field in that row. The output would be something like:

 ...

 ...

Comment: Did you consider rewriting the output of your field value or using an additional "Global: Text" field where you can use the values of all other fields added before that field with Twig (and even Twig control structures as if...then...else)? - I'm on mobile right now, therefore the brevity. Both suggestions don't require for any preprocess functions. They can be applied within the configuration of your View.
Comment: Related: https://drupal.stackexchange.com/questions/225328/how-to-preprocess-view-field
Answer: As mentioned in the comment you can add classes to fields through the interface, and you can use field tokens as CSS classes.
Add field-value-based CSS class to a field

Position the field with the value you want to use as the CSS class (the value-class field) above the field where you want the class to appear (the styled field).
Set the value-class field to Exclude from display if you don't want it to appear there.
If you need it visible in some other place then add that same field again where you need it, while keeping the first one for the token (because you can only use tokens of fields preceding in the Fields list).
Edit the field where you want to apply the CSS class (the styled field) >

Uncollapse Style settings >
Customize field and label wrapper HTML (or Customize field HTML if you don't need the wrapper) >
Create a CSS class and
enter the first part of your class (myclass)
(class names can't start with numbers and some special characters so it's good to control at least the first character to make it independent of the other field's value to prevent trouble down the line).

Uncollapse Rewrite results (don't enable it, you just need to temporarily reveal and uncollapse to copy the token),

uncollapse Replacement patterns,
copy the value-class field token and
paste it in the above CSS class field
(you end up with something like myclass-[field_name_a]).

Save the View and check your HTML output (in any theme), you will see a class based on your value-class field on the field where you added the class, something like class="views-field views-field-name-b myclass-namebvalue".
Comment: You don't really need me for this. Your answer is pretty good already. Just add the "Global: Custom text" variant. It can use the very same Replacement patterns and allows for text like that: `{{ field_my_other_field }} {{ field_image }}` to print the previously hidden fields `field_my_other_field` and `field_image`.
Comment: Thanks. This assumes that the value of field_name_a is what I want to use as a class name, and is sanitized. The reason I was hoping to be able to do this in a preprocess function is to be able to check the value of field_name_a and then apply some other class name. For example, if the value of field_name_a is "Overview Page A" or "Overview Page B", then the class to apply is "type-overview". Is it possible to do this in Drupal 8 somehow? In D7, you could use template_preprocess_views_view_field().
Comment: Yes, you can still do that in D8, check out `views-view-fields.html.twig` or `views-view-field.html.twig`, or use twig logic in Global: Text field as suggested in the comment. Lets hope Mario Steinitz adds his answer ;) [Twig best practices - preprocess functions and templates](https://www.drupal.org/docs/8/theming/twig/twig-best-practices-preprocess-functions-and-templates)


Cannot access properties of Sheet object in Powershell OpenXML

Question: I have this powershell script which write the type of the last worksheet from an xlsm document :
Add-Type -Path "C:\Program Files (x86)\Open XML SDK\V2.5\lib\DocumentFormat.OpenXml.dll"
$Document = $null
$Document = [DocumentFormat.OpenXml.Packaging.SpreadsheetDocument]::Open("C:\Users\200207121\Documents\Sandbox\FastPrep_S7_Modified_AVELIA_LZB.xlsm", $false)
$Sheets = $Document.WorkbookPart.Workbook.Sheets
$LastSheet = $Sheets.LastChild
Write-Host $LastSheet.GetType()
$Document.Close()

This outputs
DocumentFormat.OpenXml.Spreadsheet.Sheet

I need to know for sure that $LastSheet is an object of type Sheet, which must have all the properties listed in the documentation.
However, I can't access most of the properties specified in the official documentation
Write-Host "Type is $($LastSheet.GetType())"
Write-Host "State is $($LastSheet.State)"
Write-Host "state is $($LastSheet.state)"

This outputs
Type is DocumentFormat.OpenXml.Spreadsheet.Sheet
State is
state is

Why am I unable to access those properties ? Am I using the wrong library ? Is the doc outdated ? Is my syntax wrong ?
Edit : I have tried downloading the latest version of the package, and import it instead. This produces the exact same behaviour
Answer: Two things:

It does seem you have an instance, and you could explore the properties, methods, and events of that instance using Get-Member:

Try:
$lastSheet | Get-Member # to see what the object can do

You might be able to sidestep this entirely by using the excellent module ImportExcel
Comment: I already thought of that, but for some reason, `$LastSheet | Get-Member` throws _Get-Member : You must specify an object for the Get-Member cmdlet._. I had to use `-InputObject` instead of piping. This led me to an understanding of the SDK which I posted as an answer below.
Answer: That is because State is null when the sheet is visible (default).
This makes sense when looking at the underlying tag <x:sheets> :
<x:sheet name="Sheet 1" sheetId="155" r:id="rId3"/>
<x:sheet name="Sheet 2" sheetId="140" state="veryHidden" r:id="rId4"/>
<x:sheet name="Sheet 3" sheetId="130" state="veryHidden" r:id="rId5"/>

The stateattribute is only specified for hidden/veryHidden sheets. If I update my powershell code to lookup a sheet that is actually hidden, I get the appropriate behaviour.
In my opinion, the doc is totally misleading regarding this property :

state (Visible State) Specifies the visible state of this sheet.
The default value for this attribute is "visible."
The possible values for this attribute are defined by the
ST_SheetState simple type (§18.18.68).

The default value is NOT 'visible'. It is null.


Can we predict if two line segments on the plane will intersect each other?

Question: Let $X$ be a non-empty set of 4 points in the plane, and  $(X,\mathrm{d})$ the euclidean metric on $X$. Let $(x_0,y_0)\in X^2$ be any pair of points in $X$ and $\overline{x_0y_0}$ a straight line joining them. Can we tell if the line $\overline{x_1y_1}$ between the remaining points will intersect $\overline{x_0y_0}$ using only points in $X$ and distances in the metric space? (Angles too, but no line extending is allowed).
I've been doing a lot of thinking, but the only logical conclussion i came up with is that this is impossible: to know if two line segments do not intersect each other i would need to prove they are either parallel or the intersection point lies outside the convex hull of $X$, but these are all properties of lines in the plane, not points in $X$.
Comment: If computing triple orientations (signed areas, determinants of 3 points) is fair game, then yes.
Comment: I am not sure what "can we tell" means mathematically: I can imagine, you asking for an algorithm or if the 6 distances uniquely determine the intersection properties...
Comment: Yes! If we can determine the intersection using the available distances, the question will be answered.
Comment: "Yes" to what? To an algorithm? Or to what is essentially MW's answer?
Comment: Yes, we can determine if x0y0 intersects x1y1.
Answer: You can indeed determine this just from the distances.
To see this, note that after applying an isometry of the plane, we can assume with no loss of generality that $x_0=(0,0)$, $y_0=(0,d)$ for some $d>0$, and $x_1$ lies in the (closed) upper half plane.  Then $x_1$ is uniquely determined by its distance to $x_0$ and $y_0$, and similarly $y_1$ is uniquely determined by its distance to $x_0$ and $y_0$, up to a reflection across the horizontal axis.
But then from the two possible choices, $y_1$ is uniquely determined by its distance from $x_1$, except in the special case that both possible locations are equidistant from $x_1$, in which case $x_1$ must lie on the horizontal axis.  In this latter case, reflection across the horizontal axis gives an isometry preserving $x_0$, $y_0$, and $x_1$, so we may assume that $y_1$ is in the upper half plane as well, and is still uniquely determined.
Since all four points have uniquely determined locations in the plane up to a planar isometry, one can determine the intersection (or lack thereof) using planar geometry.
Remark
The number $4$ isn't really important in this problem.  That is, if we have any subset $X\subseteq \mathbb R^2$, then either:

All triples of points in $X$ satisfy $d(x,y)+d(y,z)=d(x,z)$ (for some permutation of the points).  In this case all of the points are colinear, and we may map some $x$ to $0$, some $y$ to $d(x,y)$, and the distances to $x$ and $y$ uniquely determine a location on the real line (or the horizontal axis) for every other point in $X$.

or

There are three points with $d(x,y)+d(y,z)>d(x,z)$ for all permutations, in which case after a planar isometry we may assume $x=(0,0)$, $y=(0,d)$, $z$ is in the open upper half plane (uniquely determined by its distance from $x$ and $y$), and every other point in $X$ is uniquely determined by its distances to $x$, $y$, and $z$.

The upshot is that any isometry between two planar subsets $X_1$ and $X_2$ extends to a linear isometry of the plane itself.  As a corollary, any property of a planar subset $X$ that is invariant under planar isometries will be determined solely by the inherited metric on $X$. (A similar statement is also true in higher dimensions as well.)
Comment: @SimónFlavioIbañez Unfortunately, you may have trouble using this result outside of Euclidean spaces.  For example, the result is false in the plane with the $\ell_1$ (or "taxicab") metric.  A counterexample is that $X_1=\{(0,0), (0,1), (0,2), (0,3)\}$ and $X_2=\{(0,0),(0,1),(1,1),(1,2)\}$ are isometric in that metric, yet the segment from $(0,0)$ to $(0,2)$ intersects the one from $(0,1)$ to $(0,3)$, whereas the corresponding segments in $X_2$ from $(0,0)$ to $(1,1)$ and from $(0,1)$ to $(1,2)$ do not intersect.
Comment: Thanks! This will be very useful on non-euclidean metric spaces as well!
Comment: indeed, it was a hasty conclussion, but there might be special cases.