Types of synths used in modern guitar-based music

Question: I have a solo project where I write rock/metal, and I am interested in adding synths to my music in order to expand the sonic possibilities, add more interesting textures, make the tracks sound bigger and so on.
I used to play keyboards some 20 years ago, and back then I simply used the sounds available in the one unit I owned. But when looking at videos by modern producers, I mostly see FM synthesis and DAW plug-ins. However, these seem to be making mostly electronic music.
When a guitarist is working on their tone, they invest in technique, stompboxes, amps and so on. What does the modern metal producer do? Learn how to use additive synthesis to create the sound they want from the ground up? Buy lots of physical keyboards with good sounds? Plugins? Orchestral sample packs, or some other kind? Some combination of the above?
I'd like to learn a bit about pros and cons and common practices before investing loads of money and time in learning new things and buying gear. I'm not asking what specific products to buy, but what techniques are generally used.
Thanks!
Comment: You might check out the band Metric, which blends synths and guitar really well. They started with just a physical analog subtractive mono synth (a vintage Sequential Pro One).
Answer: Back in the days of yore, you'd hear about a new synth because you read the music mags, or you heard an artist who explained in some NME article what gear they had.
Armed with this limited information, you'd drag yourself to the biggest music shop you could get to & see what they had to play with in the store. You'd twiddle some dials & try to get an impression of just what it was that had impressed that artist/music mag. There were no presets to even try out.
Armed with that paucity of information, you'd either get out your wallet, or go away & think again.
As years went by, your 'store demo' improved because there were now presets. I bought my first ever preset-capable synth in 1980 - a Rhodes Chroma - after trying it in several different places over about a month.
OK, so a Chroma was three grand plus at the time, so you had to feel you were sure what you were getting. We had friends who over the years owned Prophets, PPGs, Jupiter 8s, Emulators, Linn Drums, etc etc etc & we would each borrow everybody else's gear if we were heading to the studio. Very few people could afford them all, even hit recording stars of the time*. When the DX7 later came out at a mere grand, everybody bought their own - they'd finally reached 'affordable'.
Basically, the voicing method went from 'twiddle the knobs until you find something you like' to 'find a preset you like a bit & twiddle until you either like it a lot, or move on to something else'. It was all just 'suck it & see'. Sometimes you were actually doing this under pressure, whilst racking up studio time, because you'd just borrowed it from someone only yesterday & the first time you ever saw it in action was when the studio clock was ticking. Nothing had much of a manual in those days either, maybe just a diagram of what the buttons did.
Scroll on 35 years or so…
There are now so many VST plugins for synthesis that you have almost no hope of ever learning them all, finding which are the best other than via peer or online magazine reviews.
However… these days there are a lot of freeware or very cheap VSTs you can start on, to see if you like the approach. Pick your method, additive, subtractive, wavetable, sample - you name it, somebody's done it.
Sit down with them one at a time & fiddle with some knobs & sliders to see what they do.
90% of this effort will produce no useable result, but the overall experimentation will teach you - eventually - what you are looking for. That's the point at which you start looking at demos of the 'good stuff' (read: expensive).
Several weeks/months later, you'll be ready to buy.
I would heartily recommend not getting one of every single plugin you can find & giving them each half an hour before moving on because you're bored. That won't teach anything at all, except that 'instant gratification' is for kids with a new Playstation.
I would also recommend not going the hardware route unless you plan to take your rig on the road. You simply don't need a whole double A-frame full of physical keyboards all Midi'd together & plumbed into a 32-channel desk these days. Spend your money on one good hardware keyboard/controller instead.
*Bear in mind, the total cost of the synths we were using in the studio at that time would be maybe 20 - 30 grand. That would buy you quite a decent house.
Comment: I like this answer in general and I disagree with the suggest not to consider hardware. For me hardware is fundamentally different (and imho better) that plugins for two reasons 1) it just sounds a lot better. 2) you can easily and quickly reach out and touch all the settings. Even with a great USB controller, software synths just aren't as real-time tweakable. And even in a composing at home setting, for me the magic and the music happen when I'm hands on an instrument and really playing it. I'd suggest instead of avoiding hardware synths to instead find **one** physical analog synth.
Comment: Personally (& I really can offer any advice on this based on my own personal experience) as one-time owner of racks of the things, back in the day, I'd take one good controller - which can then be used as control surface for both the DAW itself & also a lot of the VSTs too (idk other DAWs as well, but Cubase is good at this; I've even used iDevices & OSC control surfaces in addition for a great 'driving' experience of VSTs) A 'regular' hardware synth will control itself just fine, but not the rest of the DAW, & will have to have its own 'one at a time' routing to your recorder.
Comment: tbh, any answer of mine of this type of subject is always going to be quite anecdotal & personalised from experience. Think of it like the crusty old bloke in the corner of the pub, pipe in one hand, half a mild in the other, regaling the youngsters with tales of his youthful exploits. It's only years after he's gone you find he was the guy who invented cats-eyes, may have been a millionaire & most of what he claimed was actually true (almost true story).
Answer: Background: I'm a guitarist of 27 years who had piano lessons as a kid and got addicted to synthesizers about ten years ago. Now I have a whole suite of virtual synth plugins as well as a huge rack of physical synthesizers.

When a guitarist is working on their tone, they invest in technique, stompboxes, amps and so on. What does the modern metal producer do? Learn how to use additive synthesis to create the sound they want from the ground up? Buy lots of physical keyboards with good sounds? Plugins? Orchestral sample packs, or some other kind? Some combination of the above?

Kind of like guitarists, everyone has their own approach to synthesis, producing, and music in general. I do want to say that subtractive synthesis is much more famous and more popular than additive synthesis. Most synths you're hearing across all genres are subtractive.

I'd like to learn a bit about pros and cons and common practices before investing loads of money and time in learning new things and buying gear. I'm not asking what specific products to buy, but what techniques are generally used.

Jumping off of this paragraph and Tetsujin's excellent answer, I have a suggestion for what you might think about in terms of getting into synthesis: Think about how you approach guitar and use that as a basis for exploring synths.
A synth is just another instrument. Everyone has their favorite kind of guitar, pickups, effects, analog versus digital opinion, amps, cables, strings, etc. etc. Synths have a lot of analogous choices that come down to taste and opinion for the musicians. You can see that Tetsujin and I have different tastes when it comes to hardware versus virtual synths, and that's just the tip of the iceberg. In both the hardware and virtual synth worlds, there are a huge number of choices you can make and preferences you can have.
So I suggest approaching it similar to guitar. Maybe when you bought your first guitar, you either heard a sound and wanted to get that gear, or you just bought the one you could afford, or you bought the one that looked coolest to you, etc. Either way you probably had a limited budget and likely didn't get a '59 Les Paul as your first axe. But the first one you bought was something you could learn on and get the hang of it and develop your ear so you could start learning what you look for in a guitar. And likewise with amps and effects, etc.
So, do the same with synths! Either look for something affordable, pick a band/artist/producer to emulate and see what they use, play around with a bunch in your price range in a store or demoing software or watch YouTube videos and start with something that grabs you by the ear.
One way you can get a head start is to make the analog/digital/hardware/virtual decision based on how you are with guitars. If you've got a Line 6 Helix and the Helix plugin on your computer and you love those and really appreciate being able to take your laptop and an interface anywhere and get your guitar sound, then you'll probably prefer the power, flexibility, and portability of virtual synth plugins and a decent controller. On the other end of the spectrum, if you can't stand to play through anything other than your vintage Fender Deluxe Reverb with NOS tubes and Variac to imitate old-school wall power, then you'll probably be happier in the end with a 100% analog hardware synth (and there are some awesome affordable choices in that space these days).
I think a big part of your question might be how people chase the sounds they want on synths. With a synth, tone generation is a bit more flexible than on guitar. Whichever way you go on the virtual/hardware front, I strongly suggest looking to get a real or virtual subtractive analog synth. Such a synth or plugin would be based around 2 or 3 oscillators, a low pass filter, two envelope generators, and a voltage controlled amplifier (VCA). A low frequency oscillator (LFO) and some other things are often included, depending on the synth/plugin.
It's a bit of a journey, but with just those components (real or virtual), you can make all kinds of sounds from mellow to metal, and everything in between. Just like with guitar, synths are often used with effects, and many hardware and virtual synths include effects built-in. You can always tack on extra effects either when performing/recording or later on during mixing/producing. You can plug hardware synths right into your guitar rig and play through your pedalboard and amp! A lot of synths have been used that way over the years - the theremin solo in "Whole Lotta Love" is a classic example. So if you want your synth to sound more metal, add distortion! Or run it through a Dual Rectifier (real, modeled, or profiled). More ethereal - add compression and/or chorus and/or reverb. Your knowledge of guitar effects transfers almost 100% intact.
Obviously I could go on way too long. I'm going to cut myself off and include some places I suggest you look next to get into synths. Warning: this could end up consuming a lot of time and money!

Automatic Gainsay is a YouTube channel by Marc Doty (who knows tons about synths) where he posts these excessively long, overly in-depth reviews and analyses of hardware synths. You can learn a lot from him. One video you might watch to understand the archetypal synthesizer (the Strat of synths, one might say) is his overview of the Moog Minimoog Model D
Arturia is probably the closest thing the synth world has to a company like Line 6, but with a twist. Arturia got famous by making some great virtual synth plugins, and they are still one of the top names. They have a (fairly) affordable suite of plugins that includes pretty solid reproductions of (I have to go count) over 25 classic keyboard instruments, most of them synthesizers. But, Arturia also makes some amazing analog hardware synthesizers. And they make great controllers and some other awesome tools besides. No matter how you begin your synth journey, I highly recommend you look through the different options that Arturia offers.
Native Instruments is probably king of the hardware/software integration world for virtual instruments and samples right now. If you really want tight integration between a USB controller keyboard and virtual instruments, my understanding is no one does it better (I've never used anything NI ever, so I can't say myself). You've definitely heard NI's flagship virtual synth, called Massive, on many recordings - soundtracks in particular.
Moog Music in my opinion is very much like a synth version of Gibson USA. They are venerated as having made the first really portable powerful analog synth. Their products generally have excellent sound quality. Many consider their stuff to be overpriced. And they are not so wise when it comes to the business side of things (I tried to link to their home page but I think it's down or having issues?). If you're certain you want a hardware analog synth, you gotta check out Moog. I would look at their affordable options (the most affordable of which sadly require an external keyboard to play them), possibly consider the Grandmother if you want to jump into the deeper end (it's USD 999 but you'll never outgrow it as long as you keep using synths), and definitely check out the used market for the Moog Little Phatty (discontinued but generally affordable and awesome) and other options.
Korg has of course been a huge name in digital synthesizers and keyboards since the 1980s, and they are still one of the top brands in that space. But they have put out some very nice and affordable analog synthesizers in recent years (check out the Monologue, the Minilogue, and the ARP Odyssey). They also have analog modeling synths, which are kind of like virtual instruments in a box with a keyboard - generally similar sound to analog at a lower price with more powerful features.
Sequential Circuits AKA Dave Smith Instruments has nothing affordable and nothing for a beginner in their product lines, but I'm including them for completeness. They might be more like the Fender of the synth world compared to Moog. They made the first viable, portable polysynth back in the 1970s and like the Minimoog, you've heard the Prophet 5 and its descendants thousands of times over the decades since.
If you want to go insane right out of the gate, Eurorack is not a company but a (loose) standard form factor and power supply system for combining individual synth modules into larger systems. Eurorack is more popular with the EDM, sequencing, and producing crowds because adding a keyboard and real-time performance control to Eurorack rigs can be a bit of a pain. If you're the kind of guitarist who likes to build an axe from scratch using Warmoth or Allparts or something like that, you might enjoy putting together Eurorack modules. The cost of entry seems modest, but it really isn't. Better to drop the money on a Moog Grandmother and get an all in one ready-to-go unit that sounds great than start down the Eurorack rabbit hole, in my personal opinion.


Request method 'POST' not supported Spring Boot

Question: Basically, I have a HTML search form which allows me to search within the database. A JavaScript function is called when the form is submitted but I'm not redirected to the required page.
"Request method 'POST' not supported" is the error message received.
My code:
<form th:object="${devices}" method="POST" onsubmit="return fireAction()">
    <input type="text" id="search" name="search" />
    <input type="submit" value="Search"/>
</form>

function fireAction() {
    var searchInput = document.getElementById('search').value;
    var searchFilter = document.getElementById('deviceAttributes').value;
    var checkbox = document.getElementById('lastEntry').checked;

    alert(searchInput + " " + searchFilter + " " + checkbox);
    if (searchInput == "" || searchInput == null) {
        alert("Search field cannot be null.");
        return false;

    } else if (checkbox) {
        window.location.href = '/current/' + searchInput
                + '/filter/' + searchFilter;

    } else {
        window.location.href = '/showForm/' + searchInput
                + '/filter/' + searchFilter;
    }
}

@RequestMapping(value = "/showForm/{keyword}/filter/{searchFilter}", method = RequestMethod.POST)
public String showForm(@PathVariable("keyword") String keyword,
@PathVariable("searchFilter") String searchFilter, Model model) {
    Devices devices = new Devices();
    devices.setSearch(keyword);
    devices.setSearchFilter(searchFilter);
    model.addAttribute(
    "addDevices",
    device.findByDevicesName(devices.getSearch(),
            devices.getSearchFilter()));
    return "showForm";
}

@RequestMapping(value = "/current/{keyword}/filter/{searchFilter}", method = RequestMethod.POST)
public String currentDevices(@PathVariable("keyword") String keyword,
@PathVariable("searchFilter") String searchFilter, ModelMap model) {
    model.addAttribute("devices", new Devices());
    Devices devices = new Devices();
    devices.setSearch(keyword);
    devices.setSearchFilter(searchFilter);
    List<Devices> newList = device.allDevices();
    ListIterator<Devices> iterator = newList.listIterator();
    List<Devices> resultList = new ArrayList<Devices>();
    while (iterator.hasNext()) {
        Devices device = iterator.next();
        if (searchLastEntry(device, keyword, searchFilter)) {
         resultList.add(device);
        }
    }
    model.addAttribute("iterator2", resultList);
    return "current";
}

Comment: What's the URL you see in your browser's network traffic tab?
Comment: @kryger
GET http://localhost:8080/showForm/ss/filter/deviceName
POST http://localhost:8080/
Comment: `window.location.href` issues a GET so it's not clear why you expected this to be a POST. That's a fairly contrived and non-orthodox way to submit a form, either way.
Comment: If you want to change navigation to a new page use a link instead of submitting a form; change controllers' `@RequestMethod` from POST to GET.
Comment: I have tried that but still not working. I'm redirected to an URL
http://localhost:8080/?search=ACCELERA&_uidNumber=on&_uidNumber=on&_uidNumber
Answer: You don't have a return false in your javascript after executing the window.location.href - So i suspect that after the javascript executes the asynchronous GET request to window.location.href, then the function ends and control is passed back to the form, which just does the normal POST action, but you haven't defined an action URL (which explains the GET then POST requests you say you have seen in the network tab).
Aside, as mentioned in the comments, you probably shouldn't be using POST for a search form - Have a look at http://www.w3schools.com/tags/ref_httpmethods.asp


To show that $\lim\limits_{z \to 0} {(\frac{z} {\bar{z}})^2}$ does not exist using ${\epsilon- \delta}$ definition.

Question: To show that $\lim\limits_{z \to 0} {(\frac{z} {\bar{z}})^2}$ does not exist using ${\epsilon- \delta}$ definition.
Let  $\lim\limits_{z \to 0} {(\frac{z} {\bar{z}})^2}=l$
Set ${{\epsilon}\gt{|1-l|}}$
Consider $| {(\frac{z} {\bar{z}})^2}-l|=|\frac{|z|^2(1-l)}{|\bar{z}|^2}|<|1-l| \gt \epsilon $ for every ${\delta}$ such that $0\lt|z|<\delta$
Therefore the given limit does not exist.
please correct my explanation if I have made any mistake.
Comment: How do you obtain $|z|^2$ and $|\bar z|^2$?
Comment: Can you give me example of z for which $|z|^2$ and ${|\bar{z}|^2}$ are not equal.
Comment: I meant I lacked  a fuller justification.
Answer: What you wrote doesn't work since $$\left | {\left(\frac{z} {\bar{z}}\right)^2}-l\right |\neq\left |\frac{|z|^2(1-l)}{|\bar{z}|^2}\right |.$$ Paul Frost already wrote why. You might have mistakenly used $|z|^2 = z^2$, which is true for real numbers, but not for all complex numbers. Remember that $|z|^2 = z\overline z$ holds for all complex numbers instead.
So, how would one approach the problem, using $\varepsilon$-$\delta$ definition? First let us see what the function $z\mapsto (z/\overline z)^2$ does. If we write $z = re^{it}$ (or $z = r(\cos t + i\sin t)$ if you prefer it that way), we can easily see that $$\left(\frac z{\overline z}\right)^2 = \left(\frac {re^{it}}{re^{-it}}\right)^2 = (e^{2it})^2 = e^{4it} = \cos(4t) + i\sin(4t). \tag{1}$$
Thus, our function normalizes our $z$ and quadruples its argument.
Now, assume that the limit $L$ exists. Let us write $L = re^{it}$. Considering what our function does, we want to choose $z$ such that $(z/\overline z)^2$ is as far away as possible from $L$. Since $(z/\overline z)^2$ always ends up on the unit circle and the complex number furthest apart from $L$ on the unit circle is $-L/|L| = -e^{it}$ (if $L\neq 0$, otherwise all the numbers on the unit circle are equally far away), we want $(z/\overline z)^2 = -e^{it}.$ Using $(1)$ we can quickly see that $z = \frac{\delta}{2}e^{\frac 14 i(t+\pi)}$ works for any $\delta > 0$. This scaling factor also makes sure that $|z| = \frac \delta 2$.
Finally, we are ready to prove that the limit $L = re^{it}$, in fact, cannot exist. Take $\varepsilon = 1$ and any $\delta > 0$. Now choose $z = \frac{\delta}{2}e^{\frac 14 i(t+\pi)}$ as above. Then we have $0<|z|<\delta$, but
$$|(z/\overline z)^2 - L| = |-e^{it}-re^{it}| = |e^{it}||1+r| = 1+r\geq \varepsilon,$$
which is contradiction with the assumption that $L$ is the limit.
Answer: There are two problems with your proof.

Equation
$$| {(\frac{z} {\bar{z}})^2}-l|=|\frac{|z|^2(1-l)}{|\bar{z}|^2}| \tag{1}$$
is not plausible (and in fact, it is not true, see below). You have
$$ | {(\frac{z} {\bar{z}})^2}-l|=\frac{|z^2-l\bar{z}^2|}{|\bar{z}|^2} .$$

If $(1)$ were true, then you would get $| {(\frac{z} {\bar{z}})^2}-l|= |1-l|$ (and not $<$). Under your assumption ${{\epsilon}\gt{|1-l|}}$ you get $| {(\frac{z} {\bar{z}})^2}-l| < \epsilon$. You could try to assume ${{\epsilon} <{|1-l|}}$ instead, but this does not work. In fact, if $l$ exists, then necessarily $l = 1$ (take $z_n = 1/n$). This would imply $| {(\frac{z} {\bar{z}})^2}-1|= 0$ for all $z$ which is not true.

I think it is much easier to consider the two sequences $z_n = 1/n$ and $z'_n = \lambda/n$, where $\lambda^2 = i$.


Run-time check Failure #2 , while using API for saving image frame

Question: MSVS 2010 , Windows 7
I am using an API to access camera features.
The following function displays a frame and saves it.
void DisplayThread::OnBufferDisplay( PvBuffer *aBuffer )
{

       mDisplayWnd->Display( *aBuffer ); //displaying frame

//Now let us try to save the frame with name of the form %Y%m%d%H%M%S.bmp

    system("mkdir D:\\ABCD" );
            struct tm *tm;
            int count;
        time_t t;
        char str_time[20];
        t = time(NULL);
        tm = localtime(&t);
        strftime(str_time, sizeof(str_time), "%Y%m%d%H%M%S.bmp", tm); //name of the frame
            char name[1000]; //sufficient space
         sprintf(name,"%s",str_time);
            char   path[]="D:\\ABCD";
            strcat(path,name); //path =path+"\\"+name;
        //  char* str=(char*)(void*)Marshal::StringToHGlobalAnsi(path);
    PvString lFilename( path );
                        PvString lCompleteFileName( lFilename );

 PvBufferWriter lBufferWriter; //The following function saves image
 PvResult lResult = lBufferWriter.Store( aBuffer, lCompleteFileName, PvBufferFormatBMP );

}

The name of the bmp file that is saved is of the form %Y%m%d%H%M%S.bmp
The program builds perfectly fine , even display is coming correctly,
but the following error message pops up:

It looks like something is wrong with the memory allocation with the variable 'name'.
But I have allocated sufficient space, even then I am getting this error.
Why it is happening ?
Kindly let me know if more info is required to debug this.
Note: The value returned by lBufferWriter.Store() is 'OK' (indicating that buffer/frame writing was successful), but no file is getting saved. I guess this is because of the run-time check failure I am getting.
Please help.
Comment: `path` is too small, it can only hold 7 chars (+ zero terminator)
Comment: @Mat Can you please suggest then , what is the best practice ? shall I allocate an array char path[1000]  something like this?
Comment: Your buffer needs to be large enough to hold the data you're trying to put into it.  If you're on Windows, MAX_PATH is generally large enough for a filename.
Comment: @RetiredNinja Thanks for your comment. Could you please give a small code snippet or modify my code to explain this , as an answer?   I will accept it as answer after verifying it.
Answer: Your path[] array size is 8 and it is too small to hold the string after concatenation.
As this path variable is on the stack, it is corrupting your stack.
So, your buffer should be large enough to hold the data that you want to put into it.
In your case Just change the line to:
char path[1024]="D:\\ABCD";


Multiple DHCP Servers maintain multiple LOGICAL subnets

Question: I have one physical LAN, but I have several distinct groups and each should have their own subnet. What this means is each server should be able to recognize its own clients and ignore the rest. Obviously this could be done with MAC addresses, but that sort of defeats the purpose. I remember something about Vendor Arguments/Parameters/Variables/Classes and think this the way to do it, but I can't find any advice. I think the discipline is to identify each client as a member of, say "Class 1", or "Lab", or "Sales", and these classes identify the scope that the DHCP server configures for that client.
Any advice?
Thanks for the help,
Chris.
Comment: Is each group on their own VLAN?
Comment: If by "VLAN" you mean some appliance segregated subset of the LAN, then no. Everybody is on the same set of wires. The intent is that there are different groups and they should each have a parochial view of the world, meaning seeing only the peers and resources pertinent to their mission. Shared resources will be implemented by multi-homed servers that can span subnets.
Comment: As Jim G has said below, you should really setup VLANs for each group. It's really the only way to do what you want with the DHCP services.
Answer: VLANs would be the proper way to do this.  It sounds like you have all of the DHCP servers and clients in one broadcast domain - no bueno.
Could you explain what you're trying to accomplish by doing this?  That might help determine the best solution.


Como por link em table?

Question: Eu tenho um Table em PHP e em cada tr preciso de um link
<?php
$con = mysqli_connect("localhost","root","", "saber");
mysqli_set_charset($con,"utf8");
$result = mysqli_query($con,"select id,nome,vista from mensagens");

while($row = mysqli_fetch_array($result)){
    echo "
";
    echo "" . $row['id'] . "	";
    echo "" . $row['nome'] . "	";
    if($row['vista'] == 1)
        echo "Sim	";
    else
        echo "Não	";
    echo "
";
}
?>

Alguém sabe como faço?
Answer: Você pode inserir o link dentro da
while($row = mysqli_fetch_array($result)){
echo "
<a href=".$row['link'];
echo "" . $row['id'] . "	";
echo "" . $row['nome'] . "	";
if($row['vista'] == 1)
    echo "Sim	";
else
    echo "Não	";
echo "
";
}

EDIT:
Para fazer com que em cada tr tenha um link você poderá utilizar javascript:
while($row = mysqli_fetch_array($result)){
echo "<tr onclick='location.href=.$row['link']."\'";
echo "" . $row['id'] . "	";
echo "" . $row['nome'] . "	";
if($row['vista'] == 1)
    echo "Sim	";
else
    echo "Não	";
echo "
";
}

Comment: Olá Ricardo eu enganei  quando disse que era todos os td, era todos os tr, ou seja quando se clica numa row vai para outro link
Comment: @BrunoGibellino Editei, teste ai.
Comment: Não funcionou no tr porém funcionou num td que eu testei.Mas não consigo fazer com que o link funcione no tr
Comment: de me mais informações será colocado somente um link ou sera colocado um link em cada row (tr)?
Comment: em cada tr vai ter um link
Comment: @BrunoGibellino Editei.
Answer: O link não pode ficar por fora da Td. tem que ficar dentro da td. Envolvendo somente o texto.
echo "" . $row['id'] . "	";

Comment: Boas Lucas eu enganei-me ao elaborar a pergunta eu quis dizer em todos os tr's
Answer: Acredito que isso resolve no caso de trs:

echo '
';

Answer: Terás de colocar um href a rodear a
echo "" . $row['id'] . "	";

Comment: O a href precisa estar dentro da td, não fora, ou seu HTML ficará inválido
Comment: nuussssaa.......

Como por link em table?


iPad iOS7 - UIImagePickerController in UIPopoverController has wrong preview image

Question: I am using an UIImagePickerController within an UIPopoverController which is working perfectly with iOS6. With iOS 7 the "preview" image which is shown to capture the image is rotated, but if I take a picture it is saved correctly.
This is how I get my picker:
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePicker.mediaTypes = [NSArray arrayWithObjects:
                              (NSString *) kUTTypeImage,
                              nil];
imagePicker.allowsEditing = NO;

And add it to a popover controller:
self.imagePickerPopOver = [[UIPopoverController alloc] initWithContentViewController:imagePicker];
    [self.imagePickerPopOver presentPopoverFromRect:CGRectMake(aPosViewA.x, cameraButton_y, 100.0, 30.0) inView:self.detailViewController.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];

Those are calculations for the button position at a UIScrollView to show the popover at the correct position:
presentPopoverFromRect:CGRectMake(aPosViewA.x, cameraButton_y, 100.0, 30.0)

I don't think that the problem lies there as I have tried out several combinations.
I have also tried to capture the image in fullscreen-mode, but the app is only allowed to use landscape mode. If the image is taken in portrait-mode and the modal view is dismissed, the app stays in portrait mode as well. I couldn't find a way to prevent the UIImagePickerController to switch to portrait mode or to force the app back to landscape mode if the modal view was dismissed.
UPDATE
I have taken the answer from here and came a step further.
I transform the view after creating the picker and before showing the popover :
switch ([UIApplication sharedApplication].statusBarOrientation) {
        case UIInterfaceOrientationLandscapeLeft:
            self.imagePicker.view.transform = CGAffineTransformMakeRotation(M_PI/2);
            break;
        case UIInterfaceOrientationLandscapeRight:
            self.imagePicker.view.transform = CGAffineTransformMakeRotation(-M_PI/2);
            break;
        default:
            break;
    }

which works as long as i don't turn around the iPad. For that I am registering for the orientation changed event:
[[NSNotificationCenter defaultCenter] addObserver:self  selector:@selector(orientationChanged:)  name:UIDeviceOrientationDidChangeNotification  object:nil];

and change the picker view:
- (void)orientationChanged:(NSNotification *)notification{

    if (self.imagePicker) {
        switch ([UIApplication sharedApplication].statusBarOrientation) {
            case UIInterfaceOrientationLandscapeLeft:
                self.imagePicker.view.transform = CGAffineTransformMakeRotation(M_PI/2);
                break;
            case UIInterfaceOrientationLandscapeRight:
                self.imagePicker.view.transform = CGAffineTransformMakeRotation(-M_PI/2);
                break;
            default:
                break;
        }
    }
}

REMAINING PROBLEM:
As I wrote in the beginning, when the picture was taken, it was shown correctly to accept or dismiss it. This is now transformed as well. Somehow I need to know when the image is taken and transform it back.
AND, this is really a nasty hack and probably won't work with the next iOS Update. Has anybody an idea how to implement that in a cleaner way?
UPDATE 2
This was too nasty, I have found a cleaner solution which solves my problem but is not the answer to the initial question regarding an imagepicker in a popover controller, which is not recommended by Apple, but allowed.
I have subclassed now the UIImagePickerController like this:
@implementation QPImagePickerController

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    return UIInterfaceOrientationIsLandscape(toInterfaceOrientation);
}

- (BOOL)shouldAutorotate {
    return YES;
}

- (NSUInteger)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskLandscape;
}

@end

and I am using the imagepicker in fullscreen instead in a popover. Tested so far in iOS7.
Comment: I am facing the exact same problem. I can't believe this isn't a more relevant issue—how is it not breaking more apps?
Comment: Exact same problem, won't this be fixed in the next update?
Comment: It looks to me the same issue is affecting the ios7 facebook app which uses a pop-up camera.
Comment: in iOS7 iPad landscape only app iam getting 'UIApplicationInvalidInterfaceOrientation', reason: 'Supported orientations has no common orientation with the application, and shouldAutorotate is returning YES'
Answer: The UIImagePickerController has a property called cameraViewTransform.  Applying a CGAffineTransform to this will transform the preview image but will not transform the captured image which will therefore be correctly captured.  I have the same problem that you describe and I solved it (for iOS7) by creating my camera controller and placing it in a popover as follows:
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];

[imagePickerController setDelegate:self];

imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;

CGFloat scaleFactor=1.3f;

switch ([UIApplication sharedApplication].statusBarOrientation) {

        case UIInterfaceOrientationLandscapeLeft:

            imagePickerController.cameraViewTransform = CGAffineTransformScale(CGAffineTransformMakeRotation(M_PI * 90 / 180.0), scaleFactor, scaleFactor);

            break;

        case UIInterfaceOrientationLandscapeRight:

            imagePickerController.cameraViewTransform = CGAffineTransformScale(CGAffineTransformMakeRotation(M_PI * -90 / 180.0), scaleFactor, scaleFactor);

            break;

        case UIInterfaceOrientationPortraitUpsideDown:

            imagePickerController.cameraViewTransform = CGAffineTransformMakeRotation(M_PI * 180 / 180.0);

            break;

            default:
                break;
        }

 __popoverController = [[UIPopoverController alloc] initWithContentViewController:imagePickerController];

[__popoverController presentPopoverFromRect:presentationRect inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];

I also scale the image when in Landscape so that it fills the viewfinder more than it otherwise would.  To my mind this is all rather nasty, but I will hopefully be able to remove it once iOS7.1 arrives.
Answer: I've found another solution which handles the case where a device is rotated while the UIIMagePickerView is presenting based on the answer Journeyman provided. It also handles the case where the view is rotated from UIOrientationLandscapeRight/UIOrientationLandscapeLeft back to UIOrientationPortrait.
I created a subclass of UIImagePickerController:
#import <UIKit/UIKit.h>

@interface PMImagePickerController : UIImagePickerController

@end

Then registered it to receive notifications if the device orientation changes:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(fixCameraOrientation:) name:UIDeviceOrientationDidChangeNotification object:nil];

The selector fixCameraOrientation contains Journeyman's code with one extra case, wrapped in a check to make sure the sourceType is the camera:
- (void)fixCameraOrientation:(NSNotification*)notification
{
    if (self.sourceType == UIImagePickerControllerSourceTypeCamera) {
        CGFloat scaleFactor=1.3f;

        switch ([UIApplication sharedApplication].statusBarOrientation) {
            case UIInterfaceOrientationLandscapeLeft:
                self.cameraViewTransform = CGAffineTransformScale(CGAffineTransformMakeRotation(M_PI * 90 / 180.0), scaleFactor, scaleFactor);
                break;

            case UIInterfaceOrientationLandscapeRight:
                self.cameraViewTransform = CGAffineTransformScale(CGAffineTransformMakeRotation(M_PI * -90 / 180.0), scaleFactor, scaleFactor);
                break;

            case UIInterfaceOrientationPortraitUpsideDown:
                self.cameraViewTransform = CGAffineTransformMakeRotation(M_PI * 180 / 180.0);
                break;

            case UIInterfaceOrientationPortrait:
                self.cameraViewTransform = CGAffineTransformIdentity;
                break;

            default:
                break;
        }
    }

}

The important case here is the case where the device orientation goes to portrait. The overlay's view needs to be reset in this case. It's also important for the fixCameraOrientation selector to be called after the image picker view loads, in case the device is rotated:
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self fixCameraOrientation:nil];
}

Answer: I had a similar situation in my app. However the preview was rotating correctly in iOS7 and not in iOS8. This code assumes you have more than one orientation.
The first thing is to subclass UIImagePickerController.
Starting from the top, add #import <AVFoundation/AVFoundation.h> to your .m file.
Also add a property to save the initial orientation @property (nonatomic) UIInterfaceOrientation startingOrientation; and another for a condition to remove clipping @property (nonatomic) BOOL didAttemptToRemoveCropping;.
Were going to listen to a couple of notifications.
UIApplicationDidChangeStatusBarOrientationNotification is obviously to listen for the device rotation. AVCaptureSessionDidStartRunningNotification is called right when the camera starts capturing.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarOrientationDidChange:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(captureSessionDidStart:) name:AVCaptureSessionDidStartRunningNotification object:nil];

In the -captureSessionDidStart: add a condition to verify the view is actually on screen and to make sure the camera is supposed to be displayed if (self.view.window && self.sourceType == UIImagePickerControllerSourceTypeCamera). If so, set the starting orientation self.startingOrientation = [UIApplication sharedApplication].statusBarOrientation;.
In the -statusBarOrientationDidChange: add the same condition as above, but this time if true, we'll update the camera transform. First we get the offset rotation based on the initial rotation. This is needed when you enter the UIImagePickerController in orientations other then portrait.
CGFloat startingRotation = ({
    CGFloat rotation;

    switch (self.startingOrientation) {
        case UIInterfaceOrientationPortraitUpsideDown:
            rotation = M_PI;
            break;
        case UIInterfaceOrientationLandscapeLeft:
            rotation = -M_PI_2;
            break;
        case UIInterfaceOrientationLandscapeRight:
            rotation = M_PI_2;
            break;
        default:
            rotation = 0.0f;
            break;
    }

    rotation;
});

Next we'll update the camera transform with the current rotation.
self.cameraViewTransform = CGAffineTransformMakeRotation(({
    CGFloat angle;

    switch ([UIApplication sharedApplication].statusBarOrientation) {
        case UIInterfaceOrientationPortraitUpsideDown:
            angle = startingRotation + M_PI;
            break;
        case UIInterfaceOrientationLandscapeLeft:
            angle = startingRotation + M_PI_2;
            break;
        case UIInterfaceOrientationLandscapeRight:
            angle = startingRotation + -M_PI_2;
            break;
        default:
            angle = startingRotation;
            break;
    }

    angle;
}));

And finally we'll attempt to remove the black bars presented in either 90 degree orientation from the starting orientation. (This might only be an iOS8 issue.) In slightly more detail, if I enter the UIImagePickerController in portrait mode and then rotate to landscape, there will be black bars on the top and bottom of the preview. The solution for this is not to scale but rather to remove the clipping of a superview. We only need to make this attempt once, so first check if we have called this code. Also make sure that we only call this code if we have rotated. If its called in the initial orientation it wont work right away.
if (!self.didAttemptToRemoveCropping && self.startingOrientation != [UIApplication sharedApplication].statusBarOrientation) {
    self.didAttemptToRemoveCropping = YES;

    [self findClippedSubviewInView:self.view];
}

Finally in the code for -findClippedSubviewInView: we loop through all the subviews to search for a view with .clipsToBounds = YES. If thats true we make one more condition to verify one of its ancestral superviews is correct.
for (UIView* subview in view.subviews) {
    if (subview.clipsToBounds) {
        if ([self hasAncestorCameraView:subview]) {
            subview.clipsToBounds = NO;
            break;
        }
    }

    [self findClippedSubviewInView:subview];
}

In the -hasAncestorCameraView: we simply loop up the superview chain and return true if one of the classes has CameraView in the name.
if (view == self.view) {
    return NO;
}

NSString* className = NSStringFromClass([view class]);

if ([className rangeOfString:@"CameraView"].location != NSNotFound) {
    return YES;

} else {
    return [self hasAncestorCameraView:view.superview];
}

Thats the breakdown of code, here's it all together.
#import <AVFoundation/AVFoundation.h>
#import "GImagePickerController.h"

@interface GImagePickerController ()
@property (nonatomic) UIInterfaceOrientation startingOrientation;
@property (nonatomic) BOOL didAttemptToRemoveCropping;
@end

@implementation GImagePickerController

- (instancetype)init {
    self = [super init];
    if (self) {

        if ([[[UIDevice currentDevice] systemVersion] intValue] >= 8) {
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarOrientationDidChange:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(captureSessionDidStart:) name:AVCaptureSessionDidStartRunningNotification object:nil];
        }

    }
    return self;
}

- (void)dealloc {
    if ([[[UIDevice currentDevice] systemVersion] intValue] >= 8) {
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
}

#pragma mark - Capture Session

- (void)captureSessionDidStart:(NSNotification *)notification {
    if (self.view.window && self.sourceType == UIImagePickerControllerSourceTypeCamera) {
        [self updateStartingOrientation];
    }
}

#pragma mark - Orientation

- (void)updateStartingOrientation {
    self.startingOrientation = [UIApplication sharedApplication].statusBarOrientation;
    [self updateCameraTransform];
}

- (void)updateCameraTransform {
    CGFloat startingRotation = ({
        CGFloat rotation;

        switch (self.startingOrientation) {
            case UIInterfaceOrientationPortraitUpsideDown:
                rotation = M_PI;
                break;
            case UIInterfaceOrientationLandscapeLeft:
                rotation = -M_PI_2;
                break;
            case UIInterfaceOrientationLandscapeRight:
                rotation = M_PI_2;
                break;
            default:
                rotation = 0.0f;
                break;
        }

        rotation;
    });

    self.cameraViewTransform = CGAffineTransformMakeRotation(({
        CGFloat angle;

        switch ([UIApplication sharedApplication].statusBarOrientation) {
            case UIInterfaceOrientationPortraitUpsideDown:
                angle = startingRotation + M_PI;
                break;
            case UIInterfaceOrientationLandscapeLeft:
                angle = startingRotation + M_PI_2;
                break;
            case UIInterfaceOrientationLandscapeRight:
                angle = startingRotation + -M_PI_2;
                break;
            default:
                angle = startingRotation;
                break;
        }

        angle;
    }));

    if (!self.didAttemptToRemoveCropping && self.startingOrientation != [UIApplication sharedApplication].statusBarOrientation) {
        self.didAttemptToRemoveCropping = YES;

        [self findClippedSubviewInView:self.view];
    }
}

- (void)statusBarOrientationDidChange:(NSNotification *)notification {
    if (self.view.window && self.sourceType == UIImagePickerControllerSourceTypeCamera) {
        [self updateCameraTransform];
    }
}

#pragma mark - Remove Clip To Bounds

- (BOOL)hasAncestorCameraView:(UIView *)view {
    if (view == self.view) {
        return NO;
    }

    NSString* className = NSStringFromClass([view class]);

    if ([className rangeOfString:@"CameraView"].location != NSNotFound) {
        return YES;

    } else {
        return [self hasAncestorCameraView:view.superview];
    }
}

- (void)findClippedSubviewInView:(UIView *)view {
    for (UIView* subview in view.subviews) {
        if (subview.clipsToBounds) {
            if ([self hasAncestorCameraView:subview]) {
                subview.clipsToBounds = NO;
                break;
            }
        }

        [self findClippedSubviewInView:subview];
    }
}

@end

Comment: works nearly perfectly, it looks a bit strange, as it seems like its doing more rotations than necessary
Answer: iPad with Camera - don't display in a popover.  Instead, present in a modal view controller, like you would on the iPhone.  (at least starting with iOS 7)
Comment: exactly what i needed.  Seems in iOS 8 iPad landscape that popover is best for library but modal view presentation is better for camera.


Can't route to CakePHP Controllers with Apache

Question: I have my own digitalocean droplet setup and followed this tutorial to a T to get Cakephp working
Setup CakePHP with  LAMP Stack
Everything works exactly as written in that tutorial besides for 'Step 6' - Creating the Article user interface. (Books in my case)
After using the bake all command and navigating to `/books' I get a 404 not found

As you can see CakePHP is setup and working at the top level URL, however when trying to move past that to a Controller that definitely exists it can't find it.
Comment: Did you add htaccess file?
Comment: @Parth Patel Yes Parth, all 3 .htaccess files are in place and look correctly configured
Answer: After some more digging, I found the issue.  Apparently mod_rewrite is turned off by default on Ubuntu
`sudo a2enmod rewrite
 systemctl reload apache`

is the solution here
Answer: Make sure your rewrite mod is On
If you are using Linux goto /etc/apache2/sites-enabled -> open 000-default.conf file
<VirtualHost *:80>
....

// add these lines
<Directory /var/www/html>
#Options FollowSymLinks
   Options Indexes FollowSymLinks Includes ExecCGI
   AllowOverride All
   Order deny,allow
   Allow from all
</Directory>

....
<</VirtualHost>

Save it.
restart your server:  sudo service apache2 restart
give your project permissions by giving this command:
sudo chown -R user_name:www-data project_name/
sudo chmod -R 755 project_name/

cd project_name

chown -R www-data tmp
chown -R www-data logs

chmod -R 777 tmp
chmod -R 777 logs


Interpretation of Fixed Effects from Mixed Effect Logistic Regression

Question: I am confused by statements at a UCLA webpage about mixed effects logistic regression. They show a table of fixed effects coefficients from fitting such a model and the first paragraph belows seems to interpret the coefficients exactly like a normal logistic regression. But then when they talk about odds ratios, they say you have to interpret them conditional on the random effects. What would make the interpretation of the log-odds different than their exponentiated values?

Wouldn't either require "holding everything else constant"?
What is the proper way to interpret fixed effect coefficients from this model? I was always under the impression nothing changed from the "normal" logistic regression because the random effects have expectation zero. So you interpreted log-odds and odds ratios exactly the same with or without random effects - only the SE changed.

The estimates can be interpreted essentially as always. For example,
  for IL6, a one unit increase in IL6 is associated with a .053 unit
  decrease in the expected log odds of remission. Similarly, people who
  are married or living as married are expected to have .26 higher log
  odds of being in remission than people who are single.
Many people prefer to interpret odds ratios. However, these take on a
  more nuanced meaning when there are mixed effects. In regular logistic
  regression, the odds ratios the expected odds ratio holding all the
  other predictors fixed. This makes sense as we are often interested in
  statistically adjusting for other effects, such as age, to get the
  "pure" effect of being married or whatever the primary predictor of
  interest is. The same is true with mixed effects logistic models, with
  the addition that holding everything else fixed includes holding the
  random effect fixed. that is, the odds ratio here is the conditional
  odds ratio for someone holding age and IL6 constant as well as for
  someone with either the same doctor, or doctors with identical random
  effects
Comment: I may be wrong but doubt it. There is no special consideration for odds ratios over differences in log odds. Holding everything else constant means conditional on both remaining fixed and random effects. "people who are married or living as married are expected to have .26 higher log odds of being in remission than people who are single" should have "if they have same age, ILS and random intercept value" added to it. It's a plain old equation.
Answer: Indeed, in a mixed effects logistic regression and because of the nonlinear link function that is used to connect the mean of the outcome with the linear predictor, the fixed effects coefficients have an interpretation conditional on the random effects.
An easy example to think of is the following: Say that you have a multi-center clinical trial in which patients in each hospital are randomized to two treatments, A or B. Say also that the outcome of interest is binary (e.g., did the patient require an operation, yes or no). To account for the multi-center nature of the trial we fit a mixed effects logistic regression with a random effect per hospital (i.e., a random intercepts model). From this model we get the regression coefficient for the treatment variable, say $\beta$. This $\beta$ is the logs odds ratio between the two treatments for patients coming from the same hospital. Now, if you had analyzed the same data with a generalized estimating equations (GEE) approach, then you would get coefficients with a marginal interpretation. Continuing in the example above, the estimated coefficient $\beta$ from a GEE would be the log odds ratio between the two treatments for patients across hospitals - in other words the log odds ratio averaged over the hospitals.
There are ways to obtain coefficients with a marginal interpretation from a mixed effects logistic regression. For more details on this, you can have a look in Section 5.2 of my course notes. For an implementation in R of this approach to obtain coefficients with a marginal interpretation from a GLMM, check function marginal_coefs() in the GLMMadaptive package; more info is also available here.
Comment: No, even if you do not exponentiate, the log odds will still have a subject-specific interpretation. I.e., in a mixed effects logistic regression you model $\log \frac{\mbox{Pr}(Y = 1 | b)}{1 - \mbox{Pr}(Y = 1 | b)}$. If you take the expectation w.r.t. the distribution of the random effects you get $X\beta$, the fixed-effects part. But $E_b\{\log \frac{\mbox{Pr}(Y = 1 | b)}{1 - \mbox{Pr}(Y = 1 | b)}\} = X\beta \neq \log \frac{E_b\{\mbox{Pr}(Y = 1 | b)\}}{1 - E_b\{\mbox{Pr}(Y = 1 | b)\}}$, which are the marginal log odds.
Comment: In linear mixed models the coefficients have at the same time both a marginal and subject-specific interpretation.
Comment: If there is one summary \beta from the random effects model, it must be averaged over hospitals at some point. At what level does that averaging occur?
Comment: Thank you for a clear response! Your notes look amazing, I wish the lectures were online!
Comment: Can you confirm, if these interpretations hold for linear mixed models as well ( not just glmms)
Comment: Thank you. Does that mean that with a glmm as long as the coefficients are not transformed ( e.g. exponentiated) the interpretation is both marginal and subject specific? So for a logistic mixed model, as long as the interpretation of the coefificients is in log-odds we can interpret them both ways simultaneously?


Problem with calculating Asymptotic Standard Error for Somer's D

Question: I'm trying to calculate Asymptotic Standard Error (ASE) for Somer's D measure of association for some population data.
The formula for variation (sd^2) I've found (in the article specified below) is:

(this is identical with equations presented in "Analysis of Ordinal Categorical Data" by Alan Agresti)
I've tried to implement it in R:
<code>pairsC <- function(x,prob=FALSE) {

  l <- nrow(x) # rows
  k <- ncol(x) # columns

  pc <- 0

  for (i in 1:l)
    for (j in 1:k) {

      row.idx <- (1:l)[which((1:l)>i)]
      col.idx <- (1:k)[which((1:k)>j)]

      if (length(row.idx)>0 && length(col.idx)>0)

        pc <- pc+x[i,j]*sum(x[row.idx,col.idx])

    }

  ifelse(prob,2*pc,pc)

}

pairsD <- function(x,prob=FALSE) {

  l <- nrow(x) # rows
  k <- ncol(x) # columns

  pd <- 0

  for (i in 1:l)
    for (j in 1:k) {

      row.idx <- (1:l)[which((1:l)>i)]
      col.idx <- (1:k)[which((1:k)<j)]

      if (length(row.idx)>0 && length(col.idx)>0)

        pd <- pd+x[i,j]*sum(x[row.idx,col.idx])

    }

  ifelse(prob,2*pd,pd)

}

prob <- TRUE

pc <- function(x,i,j) {

  pcx <- 0

  l <- nrow(x) # rows
  k <- ncol(x) # columns

  for a in 1:l
    for b in 1:k

      if (a<i and b<j) pcx <- pcx+x[a,b]

  for a in 1:l
    for b in 1:k

      if (a>i and b>j) pcx <- pcx+x[a,b]

  pcx

}

pd <- function(x,i,j) {

  pdx <- 0

  l <- nrow(x) # rows
  k <- ncol(x) # columns

  for a in 1:l
    for b in 1:k

      if (a<i and b>j) pdx <- pdx+x[a,b]

  for a in 1:l
  for b in 1:k

  if (a>i and b<j) pdx <- pdx+x[a,b]

  pdx

}

fi <- function(x,i,j) {

  l <- nrow(x) # rows
  k <- ncol(x) # columns

  tmp <-

    -2 * sum(x[i,]) * (pairsC(x,prob)-pairsD(x,prob)) +

    -2 * (1-sum(x[setdiff(1:l,i),])^2) * (pc(x,i,j)-pd(x,i,j))

  ifelse(length(tmp>0),tmp,0)

}

# nom1 & nom2 - nominators

l <- nrow(x) # rows
k <- ncol(x) # columns

nom1 <- 0
nom2 <- 0

for (i in 1:l)
  for (j in 1:k) {

    nom1 <- nom1 + x[i,j]*fi(x,i,j)^2

    nom2 <- nom2 + x[i,j]*fi(x,i,j)

  }

nom2 <- nom2^2

# den - denominator

den <- (1-sum(rowSums(x)^2))^2

# ASE

sqrt(nom1-nom2)/den
</code>
The table I'm trying to calculate ASE for is:
<code>> portfolio
                 [,1]   [,2]  [,3]   [,4]  [,5]   [,6]   [,7]
defaulted    0.000025 0.0001 0.001 0.0025 0.004 0.0075 0.0125
nondefaulted 0.049975 0.0999 0.199 0.2475 0.196 0.1425 0.0375
</code>
According to an article I've taken the table from (Oliver Blumke "A proposal for a validation methodology for the discriminatory power of a rating system over time", The Journal of Risk Model Validation, Vol. 5/Num. 1, Spring 2011), the Somer's D should be 0.684 and ASE 2.378.
While Somer's D I've calculated is identical to the one in the article, less the sign, i.e. -0.684 instead of +0.684, "my" ASE is 7.5468.
Can anyone help me with deriving the correct ASE value?
Thanks in advance.
Comment: The difference in sign may just be an interchange of x and y; I don't think that in any way explains the difference in ASE though. ... why would you use ASE for a sample size of 7 though?
Comment: Using ASE for this data is not my idea :)

I am using the data presented in the article mentioned in my question.
Comment: @Glen_b You are welcome :) BTW: you are right about the sign of the measure and interchange of some data. When I use -pairsC(x,prob)+pairsD(x,prob) instead of pairsC(x,prob)-pairsD(x,prob), I get +0.684.
Comment: I've checked your data in SPSS. (Since you didn't indicate the sample size N, I took N=1, i.e. your proportion values are taken as frequences.) Somer's D (columns dependent) = -.684; ASE (not assuming H0) = 2.378.
Comment: The R `Hmisc` package's `rcorr.cens` function uses the standard $U$-statistic standard error estimator for $D_{xy}$, calculated efficiently using Fortran.  You might take a look.
Comment: @ttnphns - So it seems that the results for Somer's D and ASE presented in the article are in agreement with what SPSS calculates. It also confirms that while my Somer's D measure code is correct, there is something wrong with the ASE code. Still I do not know WHAT is wrong.
Answer: After some additional research, I was able to implement Somers' D ASE in R and, additionally, in F#.
Both codes are not the most clean, but they seem to work fine:
http://www.reakkt.com/2013/12/sommersd-two-dirty-implementations-r-vs.html
I would like to thank all who assisted me in my search for the solution :)


Preload com Cookie ou Session

Question: Olá pessoal tudo bem? estou utilizando um código preload esta funcionando muito bem, porem o problema é que toda vez que acessa o site carrega o preload isso incomoda muito.. gostaria que carregasse somente 1 vez por acesso, exemplo se continuar navegando não mais irá carregar, porem se voltar a acessar irá mostrar o preload novamente.
Answer: Você pode setar uma variável no $_SESSION e checar se ela foi setada na hora de mostrar o preload, no caso do PHP seria algo assim:
<?php
session_start();

if (empty($_SESSION['preload'])) {
   $_SESSION['preload'] = true;
  //código para mostrar o preload
}
?>

Com JS você pode fazer usando cookie por exemplo:
function setCookie(cname, cvalue, days) {
    var d = new Date();
    var expires;
    if (days) {
        d.setTime(d.getTime() + (days*24*60*60*1000));
        expires = "expires="+ d.toUTCString();
    }else {
        expires = "";
    }
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length,c.length);
        }
    }
    return "";
}

function checkPreload() {
    var preload = getCookie("preload");
    if (preload == "") {
        console.log("mostrar preload");
        setCookie("preload", 1, 1);
    } else {
        console.log("já mostrou o preload");
    }
}

checkPreload();

Comment: Fernando sem querer abusar vc pode me passar um contato para que eu possa resolver esta questão?
Comment: Eu não entendo muito de PHP, como eu montaria o código PHP no meu html, uma vez que utilizo uma div, outra coisa com cookie o mais ideal seria salvar o cookie até a permanência do browser.
Comment: Certo, você poderia estão no evento `onunload` apagar o cookie
Comment: eu não consegui mesmo montar, você poderia me dar um exemplo de como seria o código?
Comment: Você pode setar o cookie sem a data de expiração, nesse caso ele será removido ao final da sessão do browser, quando for fechado. Alterei a função para permitir fazer isso, aí você usa `setCookie('preload', 1)`
Comment: @Renato qual o seu e-mail?
Comment: firstname.lastname@example.com @fernandoandrade

Preload com Cookie ou Session


Javascript getElementById does not work on chrome but works on Firefox

Question: Good Morning,
I have this code
document.getElementById("button").onclick = function () {
    document.getElementById("confirm").innerHTML = "Order Placed Cheack your email!";
    document.getElementById("button").style.display = "none";
}

The above code when executed works on Firefox but when I run it on Chrome Version 81.0.4044.138 (Official Build) (64-bit) or Edge or IE browser it does not gives any response
<!DOCTYPE html>

            <meta charset="UTF-8">
            <title>Form</title>

Confirm order?

            <button id="button">Submit</button>

Comment: Just tested using Chrome and it seems to be working fine. Are you missing some code? Here's a fiddle: https://jsfiddle.net/kdty9c3e/
Comment: The same code on jsfiddle.net/kdty9c3e does not works on Chrome Version 81.0.4044.138 (Official Build) (64-bit) @AndroidNoobie
Comment: Wrap the JS in a `window.addEventListener("DOMContentLoaded", () => {/* add listeners here */})` callback. [Docs](https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event)
Comment: The fiddle works fine for me in that version of Chrome.
Comment: When it doesn't work, are there any errors in the JavaScript console?
Comment: @1252748 The `defer` attribute is supposed to solve that problem.
Answer: You are including your JavaScript before the DOM is ready so the click event is not getting attached properly due to fast loading of the JS file in Chrome V8 engine.
Always remember to put your script tag just before the close of html tag. Also, you are missing type="text/javascript".
<!DOCTYPE html>

            <meta charset="UTF-8">
            <title>Form</title>

Confirm order?

            <button id="button">Submit</button>

Comment: `type="text/javascript"` isn't required now-a-days.
Answer: Two things, please put the  just before the body and also, remove the defer attribute and / after form.js:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Form</title>

Confirm order?

        <button id="button">Submit</button>

The above should work.


Does $\left\lVert a-b \right\rVert_\infty < \epsilon \implies (\int a-b)< \int \epsilon$?

Question: $a,b$ are continuous functions.
I think this is true as constants are continuous functions but I'm not sure if it holds for all cases.
Edit: Integrated over two real numbers
Comment: Even a Clever one cannot give an answer to this question.
Comment: is the set over which you are integrating of finite measure? zero measure?
Answer: Only if the measure space is finite, otherwise you'll have only $\int (a-b) \le \int \varepsilon$ because both sides may be infinite.$\,$
Comment: That's not really correct. You need to have $\mu(X) \le 1.$
Comment: Why would you need $\mu(X) \le 1$?  We're integrating $\varepsilon$ over the same space, so as long as the measure is finite we'll be okay.
Comment: Suppose the measure space is $[0,3]$ with Lebesgue measure. Define $a\equiv 2, b\equiv 1, \epsilon =3/2.$ Then we have $\|a-b\|_\infty = 1< 3/2.$ Is it true that $\int_0^3 (a-b)\, dx < 3/2?$
Comment: No, but it is true that $\int_0^3 (a-b)dx < \int_0^3 \varepsilon dx$, which is what we wanted to show.
Comment: OK, my mistake.  Bad mistake. Stupid. Let me see if I can fix this with the voting. Yes, I turned -1 into +1.


Android: Add a custom button to SearchView Widget in Actionbar

Question: I would like to add a custom button to SearchView widget.
Going through source code of search_view layout file I found out that it has a LinearLayout (submit_area) that contains submit button and voice button.
So I added a dynamic button to submit_area. But it doesn't show my dynamically added button because if either submit button or voice button is not enabled then submit_area is invisible. So it doesn't matter if I add anything dynamically.
SearchView searchView = (SearchView) menuItem.getActionView();

int
submit_areaId = searchView.getContext().getResources()
    .getIdentifier("android:id/submit_area", null, null);

Button btnScan = new Button(getActivity());
btnScan.setText(getString(R.string.scan)); submitArea.addView(btnScan);

However if I just set submit button enabled then it shows submit button as well as my dynamic button, like in the attached photo.
I just want to show my dynamic button only. Any clue how to achieve that?
Comment: What is "submitArea" here in your code ,    submitArea.addView(btnScan);
Answer: searchView.setSubmitButtonEnabled(false);
LinearLayout linearLayoutOfSearchView = (LinearLayout) searchView.getChildAt(0);
Button yourButton = new Button(mContext); // and do whatever to your button
linearLayoutOfSearchView.addView(yourButton);

Comment: Please add some decription to your answer to help the OP understand the solution
Comment: You missed the point in the question. Button is already added to the view. If you disable Submit/Voice buttons then View will not show at all. In my answer below is shows how to show custom button without disabling default button.
Answer: Since a private SearchView class method is setting submit_area Visibility.Gone so we can't do much about it.
A quick dirty trick is to set of the default buttons enabled and then set its width and height to 0. Setting Visibility didn't work so have to set height/width.
I enabled search button and then set its height/width to zero.
int submit_areaId = searchView.getContext().getResources().getIdentifier("android:id/submit_area", null, null);

ImageView submitImage = (ImageView) searchView.findViewById(search_go_btnId);

searchView.setSubmitButtonEnabled(true);

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(0, 0);

submitImage.setLayoutParams(layoutParams);

Now SearchView will show anything that you add in submit_area.


The mean cross sectional area of a volume of revolution

Question: For example: The curve $$y= 0.001sec(x)     $$ is rotated 2π rad about the x axis to form a soild.
Calculate the mean cross sectional area of this solid in the range $[0,\pi/4]$
I am having great trouble in figuring out a method to solve this questions. Any help will be great.
(Also I have though about using the mean value of $sec(x)$ with in the range but most likely that will not work as the cross sectional area will be $sec^2(x)dx$
Comment: $\sec^2$ has an elementary antiderivative, so what's the issue?
Answer: A method:
The volume is given by $$\int_0^{π/4}{πy^2\mathrm d x},$$ so that the mean area $A_m$ satisfies the equation $$A_m\int_0^{π/4}{\mathrm d x}=\int_0^{π/4}{πy^2\mathrm d x}.$$
You should be able to do something now.


Evaluating $\lim_{n\to\infty}\frac{1}{n+1}(\omega+\nu)^{(n+1)}z^\nu{_2F_1}(1,\omega+\nu+1;n+2;1-z)$

Question: I recently found a proof for the following sum
\begin{align*}
S_n & =\sum_{k=0}^n\mathcal S_n^{(k)}(\Phi(z,-k,\omega)-z^\nu\Phi(z,-k,\omega+\nu))\\ & =\frac{1}{n+1}(\omega+\nu)^{(n+1)}z^\nu{_2F_1}(1,\omega+\nu+1;n+2;1-z),
\end{align*}
where $\mathcal S_n^{(k)}$ are Stirling numbers of the 1st-kind, $\Phi(\cdot)$ is the Lerch transcendent, $(s)^{(n)}=\Gamma(s+1)/\Gamma(s-n+1)$ is the falling factorial, and ${_2F_1}(\cdot)$ is the hypergeometric function.
My question is about finding an expression for $S=\lim_{n\to\infty} S_n$.  If we restrict $z\in(0,1)$ each of the special functions listed may be represented as a convergent power series which may aid in this calculation. The r.h.s. then becomes
$$
S=z^\nu\Gamma(\omega+\nu+1)\lim_{n\to\infty}\frac{1}{n+1}\frac{1}{\Gamma(\omega+\nu-n)}\sum_{k=0}^\infty\frac{(\omega+\nu+1)_k}{(n+2)_k}(1-z)^k.
$$
Its not immediately obvious to me what happens with the $\Gamma(\omega+\nu-n)$ term as $n$ becomes large and this is where I got stuck.  How to proceed?
Comment: You have some problems in your last expression for $S$. The subscript in the sum for $(\omega +\nu+1)$ should be $k$. Also where did $(\omega+\nu)^{n+1}$ go?
Comment: @Gary Thank you. I fixed the subscript. The $(\omega+\nu)^{(n+1)}$ was rewritten as a ratio of Gamma functions per the definition.
Comment: Ah, I see, it is not a power.
Answer: By (15.12.3) and (5.11.13), we have
\begin{align*}
S_n & = \frac{1}{{n + 1}}(\omega  + \nu )^{(n + 1)} z^\nu  \frac{{\Gamma (n + 2)}}{{\Gamma (n - \omega  - \nu  + 1)}}\frac{1}{{n^{\omega  + \nu  + 1} }}\left( {1 + \mathcal{O} \! \left( {\frac{1}{n}} \right)} \right)
\\ & = (\omega  + \nu )^{(n + 1)} z^\nu  \frac{{\Gamma (n + 2)}}{{\Gamma (n - \omega  - \nu  + 1)}}\frac{1}{{n^{\omega  + \nu  + 2} }}\left( {1 + \mathcal{O} \! \left( {\frac{1}{n}} \right)} \right)
\\ & = z^\nu  (\omega  + \nu )^{(n + 1)} \frac{1}{n}\left( {1 +\mathcal{O} \! \left( {\frac{1}{n}} \right)} \right)
\\ & = ( - 1)^{n+1} \frac{{z^\nu  }}{{\Gamma ( - \omega  - \nu )}}\frac{{\Gamma (n - \omega  - \nu )}}{n}\left( {1 + \mathcal{O} \! \left( {\frac{1}{n}} \right)} \right).
\end{align*}
If $\omega+\nu$ is not a non-negative integer, $S_n$ will tend to infinity in absolute value and will oscillate in sign.


Como mostar as alterações feitas em uma revisão do SVN?

Question: Eu tenho o número de uma revisão no svn. Como eu faço (em linha de comando) para mostrar as alterações que foram feitas no nessa revisão?
Até onde consegui:

svn log -r XXXXXX

Mas dessa forma ele só mostra o texto do Commit.
Answer: Tente usar --verbose junto do comando que você usou:
svn log --verbose -r XXXX

Referência:
simple command to show changes made in a revision
Answer: svn log --verbose -r <numeroDaRevisao>

Lista com os caminhos de diretório completos:
svn diff --summarize -r<revisaoFinal>:<revisaoInicial>


iSCSI switch replacement (2 VMware hosts)

Question: Good morning everyone,
I recently bought two unmanaged NetGear 1gb switches to replace our older unmanaged Cisco 1gb iSCSI switches.  Right now, the only devices currently connected to this network are 2 VMware 5.5 hosts and a Dell 3220i SAN.
Last week I attempted to cut over by moving just a single connection at a time.  Essentially, I moved one SAN iSCSI connection over to one of the new switches, then one from each of the hosts and then rescanned the bus, hoping that it would find the new route on its own, which is turn would allow for no down time at all.  Well, this didn't happen.  Bassically when I moved them over and rescanned the bus, the old routes just disappeared and I was left with the remaining routes on the old switches, but when I gave up, plugged them back into the old switches and rescanned the bus, they re-appeared.
Can anyone tell me why the hosts failed to pick up the new physical connections through the new switches?  Do I need to just shut everything off and swap them over?
FYI, the network subnetting did not change.
Let me know if you need more information.
Comment: Boy, I really want to say that this has something to do with the MAC address table on the new switch but I'm hesitant about that being the cause of the problem. I'd suggest firing up Wireshark or the like on one of the hosts and running a capture when trying this again.
Comment: Did you replicate the same VLAN structures on the new switches as they were on the older ones?
Comment: Yes, nothing changed on the NIC settings/VSwitches and since the physical switches are unmanaged, nothing to change on them either.
Comment: I mean on the switches, are there VLAN defined?
Comment: No, there is not.
Comment: The storage and the hosts connect directly to these switches? There aren't any intermediate switches or routers?
Comment: Correct, they connect directly to these switches.
Comment: I take everyone's silence that it SHOULD work this way?
Answer: Just so everyone knows, the answer to my problem was the subnetting.  It appears that when doing this type of cut over, you can not use the same subnetting as the old network.  I completely changed the subnetting from 10.11.12.0 to 192.168.1.0 and they showed up without issue.
Comment: So basic IP skills then...
Comment: No, when have you ever needed to configure a different subnet for each additional unmanaged switch?  That would be a nightmare on your normal network.  not to mention the amount of router configuration to get the subnets to talk to one another.  @Chopper3


JQuery UI Sortable Only Allows Drag to Top When Gripped from the Bottom

Question: I am using JQuery UI and Sortable in order to drag portlets and reorder between a few different connected ".column" DIVs.
The problem is that in order to drag a portlet to the very top position of any of the columns, you have to grip/click towards the bottom of a portlet.  If you click/drag from the top of a portlet, you won't be able to place the portlet at the very top of a column...at least not without considerable effort moving the portlet around.
I have tried using the "cursorAt" attribute to force the cursor to the bottom, where dragging usually works, but it doesn't have the desired effect. Example: cursorAt: {left:  205, bottom: 5}
Here is a jsfiddle of the issue:
http://jsfiddle.net/KxP72/
Otherwise, here is the code, starting with the JavaScript:
$(function() {
$(".column").sortable({
    connectWith: ".column"
});
$(".column").disableSelection();
});

And here is the CSS
.ui-sortable-placeholder {border: 1px dashed #7E7F81; visibility: visible !important;            height: 200px !important;}
.ui-sortable-placeholder * {visibility: hidden;}
 #container {width: 100%; display: inline-block; border-top: 1px solid #3B3D41; border-       bottom: 1px solid #000; text-align: center;}
 #object_body {display: inline-block; margin: 0px auto 0px auto; padding: 200px 30px 200px 0px; position: relative; text-align: left;}
 div.column {float: left; display: inline-block; width: 437px;}
 div.portlet {display: inline-block; padding: 5px; width: 400px; min-height: 225px; background: #141517; border: 1px solid #111; margin: 25px 0px 0px 25px; color: #FFF; float: left; position: relative; cursor: move; box-shadow: 1px 1px 0px #3D3F42; -moz-border-     radius: 5px; border-radius: 5px;}
div.portlet img {width: 400px; margin-left: 0px;}

And here is the HTML:

Answer: You can remove float:left for .column and .portlet, and make them both display:block instead of inline-block. To make them also aligned left you can change #object_body to display:block as well.
div.column {display: block;float: none;}
div.portlet {display: block;float: none;}

here I updated jsfiddle http://jsfiddle.net/paulitto/KxP72/2/
With sortable container having float:left and/or display:inline makes it located at the very top, and images sorting becomes problematic within that bounds (as they are out of it). You may e.g add border to .column and see what it looks like.
Comment: Brilliant, it works. To think it was just a matter of a display block and the removal of a needless float. Thanks!


Is there a test to check if a second derivative is always negative for a given interval?

Question: Is there a test to check if a second derivative is always negative for a given interval?
I am currently evaluating the second derivative many times with incrementing intervals and checking if negative or positive.
However, this is computationally expensive for the given precision I need.
I am aware of methods to find the local minimum and maximum of functions, but is there a clean solution for my problem?
The function in question is a 5th degree polynomial.
Comment: would you like to share your function?
Comment: **draw a variation array**, starting with the sign of third derivative (it is quadratic so you can study it directly). Then the second derivative is $\searrow$ or $\nearrow$ on some intervals, find the minimum, maximum and determine if it annulates on the given interval.
Comment: @SiongThyeGoh It is a 5th degree polynomial.
Comment: Couldn't you just numerically find the zeros of the second derivative (using something like Newton's method for example). Once you know the zeros, you simply have to make sure your interval doesn't contain a zero and that the second derivative is negative at any point inside your interval.
Answer: You can check if the second derivative of your 5th degree polynomial (a 3rd degree polynomial itself) has any root in the given interval. There are a few methods for it: Newton, secant, etc. If it doesn't, and such 3rd degree polynomial has a negative value evaluated at any arbitrary point of the interval, you will know that it is negative on the whole interval (otherwise it would be contradicting Bolzano's theorem).


Create URL and redirect?

Question: function news_article_node_submit($node, $form, &$form_state)
{
// Make a URI link from title of pdf being uploaded
if (isset($form_state['values']['field_upload_import_pdf'])) {
    $file = file_load($node->field_upload_import_pdf['und'][0]['fid']);
    $filePath = file_create_url($file->uri);

    // Redirect to pdf
    isset($_GET['destination']);
    unset($_GET['destination']);
    if (isset($filePath)) {
        drupal_goto($filePath);

        // Return all field behaviors to redirect to default
    } else {
        $form_state['redirect'] = 'to page preview';
        drupal_redirect_form($form_state);
        }
    }
}

I was experimenting with drupal_goto() and $form_state['redirect'], but neither of them seems to work. Using drupal_goto() hijacks the whole module and the $form_state['redirect'] doesn't do anything. Also I am getting PHP errors when else function encounters the first two lines of code above:

Notice: Undefined offset: 0 in news_article_node_submit()

Notice: Trying to get property of non-object in news_article_node_submit()

Is there a way to create a URI from the filename, and redirect users to domainname://NAME_OF_FILE.pdf when choosing a conditional field while, at the same time, when users use any other conditional field, the behavior is the default Drupal one?
Comment: I know! Is there another way to approach this?
Answer: You can use the trick from the module File Force Download. You can check it in the their code repository https://cgit.drupalcode.org/file_force/tree/file_force.module?h=7.x-1.x

Create URL and redirect?


Proving a topological space is/is not Hausdorff?

Question: I know this is a basic question, but I am having trouble proving that particular topological spaces are/are not Hausdorff and was wondering if I could get some guidance. For example, I have to decide whether or not the half-open topology is Hausdorff and then prove my decision. I think that it is, and my proof is as follows:
Let $U, V \subset H'$ such that $x \in U$ and $y \in U$ with $x \not= y$. THen for $a,b,c \in \mathbb{R}$, we can construct $U = [a,b)$ and $V=[b,c)$, which are disjoint sets. Thus for any $x,y \in \mathbb{R}$, there exist two open sets $U$ and $V$ that contain $x$ and $y$ such that $U \cap V = \emptyset$. It follows that $H'$ is Hausdorff.
Basically, I feel like this proof is wrong or incomplete or something. Could anyone give me any pointers about this proof and how to go about proofs like this in general? Thanks.
Comment: It's hard to tell what you're doing. Instead, find $U$ and $V$ explicitly. For example, if $x<y$ are given, you can set $U=[x,y)$ and $V=[y,y+1)$.
Comment: Perhaps you want a<x<b<y<c?
Comment: So let's take $x=3$ and $y=4$.  How does it help me to know that I can construct the sets $[10,11)$ and $[11,12)$ ?
Answer: It's hard to tell what you are doing. You have to find explicit open sets $U$ and $V$ depending on $x$ and $y$ which are disjoint and contain $x$, $y$, respectively. You can assume that $x<y$, then one of the sets could be $[y,\infty)$ or $[y,y+1)$, the other set could be $[x,y)$. Note also that the complement of a basic open set $[a,b)$ is again open as it's the union of the open basic open sets
$$\bigcup_{c<a} [c,a)\cup\bigcup_{b<d} [b,d)$$
Since for any two points $x<y$, the basic set $[x,y)$ contains $x$ but not $y$, there is always a separation of the space between $x$ and $y$. A space with this property (which is stronger than the Hausdorff property) is called totally separated.
If you want to practice some problem solving like this, I suggest that you try and show that $X$ is also normal, i.e. for disjoint closed sets $A$ and $B$ there are disjoint open neighbourhoods. The proof is not very difficult.


Use js library in flutter web

Question: I need widget with bpmn.js view: https://github.com/bpmn-io/bpmn-js
Used HtmlElementView:
    // ignore: undefined_prefixed_name
    ui.platformViewRegistry
        .registerViewFactory('bpmn_view', (int viewId) => element);

    return Column(
      children: <Widget>[
        Expanded(
            child: HtmlElementView(key: UniqueKey(), viewType: "bpmn_view")),
      ],
    );

With js:
    const html = '''

canvas

    ''';

    element.setInnerHtml(html,
        validator: NodeValidatorBuilder.common()..allowElement('script'));

But I get error when it execute:
VM4761 bpmn-viewer.development.js:18864 Uncaught TypeError: Cannot read property 'appendChild' of null
    at Viewer.BaseViewer.attachTo (VM4761 bpmn-viewer.development.js:18864)
    at Viewer.BaseViewer._init (VM4761 bpmn-viewer.development.js:18911)
    at Viewer.BaseViewer (VM4761 bpmn-viewer.development.js:18454)
    at new Viewer (VM4761 bpmn-viewer.development.js:19082)
    at <anonymous>:3:25
    at main.dart:185
    at future.dart:316
    at internalCallback (isolate_helper.dart:50)

And I can't set selector for BpmnJS like:
 var bpmnJS = new BpmnJS({
               container: "document.querySelector('flt-platform-view').shadowRoot.querySelector('#canvas')";
           });

How can I make it work?
Comment: Iframe is not a good solution in my humble opinion. Especially when flutter rebuilds the `HTMLElementView` widget it might even re-render the iframe altogether For e.g when a resize is happening. Also communication between the main app and Iframe could be another paint point. I will try this issue later today.
Comment: Why are you trying to access with the `viewType` . Since inside your shadow dom the canvas id is `canvas` use something like this.`document.querySelector('flt-platform-view').shadowRoot.querySelector('#canvas');`
Comment: Ah, ok. Thx. I change and edit this.
Comment: I think I just use iframe element but I want know how to do it properly in flutter web.
Answer: Since BpmnJS container parameter accepts DOMElement type value, we can pass querySelector's result directly:
    _element = html.DivElement()
      ..id = 'canvas'
      ..append(html.ScriptElement()
        ..text = """
        const canvas = document.querySelector("flt-platform-view").shadowRoot.querySelector("#canvas");
        const viewer = new BpmnJS({ container: canvas });
        """);

    // ignore: undefined_prefixed_name
    ui.platformViewRegistry
        .registerViewFactory('bpmn-view', (int viewId) => _element);

BpmnJS module should be attached to index.html file (in your project's top-level web folder):
<!DOCTYPE html>

  <title>BpmnJS Demo</title>

...

Here is full code:
import 'dart:ui' as ui;
import 'package:universal_html/html.dart' as html;
import 'package:flutter/material.dart';

class BpmnDemo extends StatefulWidget {
  @override
  _BpmnDemoState createState() => _BpmnDemoState();
}

class _BpmnDemoState extends State<BpmnDemo> {
  html.DivElement _element;

  @override
  void initState() {
    super.initState();

    _element = html.DivElement()
      ..id = 'canvas'
      ..append(html.ScriptElement()
        ..text = """
        const canvas = document.querySelector("flt-platform-view").shadowRoot.querySelector("#canvas");
        const viewer = new BpmnJS({ container: canvas });
        const uri = "https://cdn.staticaly.com/gh/bpmn-io/bpmn-js-examples/dfceecba/url-viewer/resources/pizza-collaboration.bpmn";
        fetch(uri).then(res => res.text().then(xml => viewer.importXML(xml)));
        """);

    // ignore: undefined_prefixed_name
    ui.platformViewRegistry
        .registerViewFactory('bpmn-view', (int viewId) => _element);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Center(
          child: HtmlElementView(key: UniqueKey(), viewType: "bpmn-view")),
    );
  }
}

UPDATE:
This example shows how to load a diagram from dart code and uses dart:js library:
import 'dart:ui' as ui;
import 'dart:js' as js;
import 'package:universal_html/html.dart' as html;
import 'package:flutter/material.dart';

class BpmnDemo extends StatefulWidget {
  @override
  _BpmnDemoState createState() => _BpmnDemoState();
}

class _BpmnDemoState extends State<BpmnDemo> {
  html.DivElement _element;
  js.JsObject _viewer;

  @override
  void initState() {
    super.initState();
    _element = html.DivElement();
    _viewer = js.JsObject(
      js.context['BpmnJS'],
      [
        js.JsObject.jsify({'container': _element})
      ],
    );
    // ignore: undefined_prefixed_name
    ui.platformViewRegistry.registerViewFactory('bpmn-view', (int viewId) => _element);
    loadDiagram('assets/pizza-collaboration.bpmn');
  }

  loadDiagram(String src) async {
    final bundle = DefaultAssetBundle.of(context);
    final xml = await bundle.loadString(src);
    _viewer.callMethod('importXML', [xml]);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Center(child: HtmlElementView(key: UniqueKey(), viewType: "bpmn-view")),
    );
  }
}

UPDATE 2:
Certain complications with calling methods from js library can arise when HtmlElementView uses IFrame element. In this case we can try two options:

Store IFrame context on dart side and then use callMethod with saved context.
Use postMessage method to communicate with IFrame

import 'dart:ui' as ui;
import 'dart:js' as js;
import 'dart:html' as html;
import 'package:flutter/material.dart';

class IFrameDemoPage extends StatefulWidget {
  @override
  _IFrameDemoPageState createState() => _IFrameDemoPageState();
}

class _IFrameDemoPageState extends State<IFrameDemoPage> {
  html.IFrameElement _element;
  js.JsObject _connector;

  @override
  void initState() {
    super.initState();

    js.context["connect_content_to_flutter"] = (content) {
      _connector = content;
    };

    _element = html.IFrameElement()
      ..style.border = 'none'
      ..srcdoc = """
        <!DOCTYPE html>

I'm IFrame

        """;

    // ignore:undefined_prefixed_name
    ui.platformViewRegistry.registerViewFactory(
      'example',
      (int viewId) => _element,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: [
          IconButton(
            icon: Icon(Icons.filter_1),
            tooltip: 'Test with connector',
            onPressed: () {
              _connector.callMethod('hello', ['Hello from first variant']);
            },
          ),
          IconButton(
            icon: Icon(Icons.filter_2),
            tooltip: 'Test with postMessage',
            onPressed: () {
              _element.contentWindow.postMessage({
                'id': 'test',
                'msg': 'Hello from second variant',
              }, "*");
            },
          )
        ],
      ),
      body: Container(
        child: HtmlElementView(viewType: 'example'),
      ),
    );
  }
}

Comment: I added an example.
Comment: @nbloqs [here](https://stackoverflow.com/a/61306049/1891712) is example with PayPal feedback to flutter, but to work with a large number of methods you have to create wrapper with a [package:js](https://pub.dev/packages/js) (not a dart:js library).
Comment: @nbloqs I added some suggestions to my answer.
Comment: Thx! Can I pass xml to viewer without `fetch` operation?
Comment: Excellent answer! Is there a way of sending back a message from JS to the Dart side?
Comment: CustomEvent event maybe: https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent
Comment: Thanks! I will try and if I can't figure it out, I will post a question.
Comment: Thanks again. By looking into the PayPal example I can send and receive data, but calling methods, although I can do it with functions defined in the Flutter for web's index.html, I am not able to call methods inside the IFrame's srcdoc. Is there a way to do that?
Comment: @Spatz Thanks a lot!
Comment: The name 'platformViewRegistry' is being referenced through the prefix 'ui', but it isn't defined in any of the libraries imported using that prefix.
Try correcting the prefix or importing the library that defines 'platformViewRegistry'.
Comment: @gowthaman C did you miss this line ``// ignore:undefined_prefixed_name``?

Use js library in flutter web


How to sort view by content type, using literal ordering, as second order-by clause

Question: In a view, I want to sort content by:

Collection (a taxonomy term)
Content type
Something else
Something else ...

I have this configured in the View UI and I want to leave most of it as it  is but for the content type ordering, I want to make this literal - I want to state the order exactly ("article", "page", "thingy", "other one").
For this in MySQL you would use FIELD()
I have tried using hook_views_query_alter and setting $query->orderby[1][field] to FIELD(node_field_data_type, "article", "page", "thingy", "other one") but I am running into exactly this problem: https://www.drupal.org/node/1382016#comment-12058755 In other words, the brackets and quotes are being removed so that it thinks it's one long field name (which of course does not exist) rather than treating it as a function call. It seems this did not happen in Drupal 7.
Is there a known way to get around this in Drupal 8?
Answer: Although there may be a method to do this via a query alter I was unable to find the correct solution. I was however able to find a solution.
Although we utilise search API heavily and we can use the content type relevance weighting we had a requirement to sort by a custom content type order and then by date, in addition some content types needed the same weight.
Our solution: Add a search weighting field to the required content types (e.g. integer 1-5) and include it in the index.  In the view add a sort filter for your search filter field.
You'll need to batch process or use views bulk operations to fill in existing node data and hide the field from content add / edit screens if required.
One added benefit of this method is, if the client wants to have a piece of content show at the top when it's in the result set they can manually amend the new field for it.


finite axiomatizability of first order theories?

Question: If we consider a single schema as a single axiom, so ZFC for example would be finitely axiomatizable after this kind of counting axioms.
By schema its meant a syntactical expression (string of symbols) that contains among its symbols free meta-theoretic variable symbols that range over a decidable set of formulas of the language of the theory in such a manner that each substitution of all those metatheoretic variables in the expression by instances (formulas) from what they range over would result in a sentence of the language of the theory. For example the separation schema of Zermelo written as: $$\forall A \exists x \forall y (y \in x \leftrightarrow y \in A \land \phi) \text { is an axiom }$$; Where $\phi$ is a metatheoretic variable that ranges over all formulas of the language in which $A$ doesn't occur free.
This is considered as a single axiom. While the separation schema written as: $$for \ n=1,2,3,...\\ \forall p_1,.., \forall p_n \forall A \exists x \forall y (y \in x \leftrightarrow y \in A \land \phi)$$, that is not a single schema, it is an infinite collection of schemas, so it is not considered as a single axiom.

Now is it the case that every effectively generated first order theory (with finitely many primitives) is finitely axiomatizable in this sense?
Comment: You have to define "schema."
Comment: Correct! I've added that, see my last edition.
Answer: Let $n\mapsto\phi_n$ be a recursive enumeration of the provable formulas in the given theory, and define $\phi_n'$ to be $\phi_n\wedge\dots\wedge\phi_n$ where $\phi_n$ is repeated $n+1$ times. Given a formula you can check if it's equal to some $\phi_n'$ by seeing if it's equal to some formula repeated $n+1$ times, and then using the fact that $n\mapsto\phi_n$ is computable to calculate $\phi_n'$ and check if it's your formula. Thus the $\phi_n'$s form a decidable set of formulas, and hence a single axiom schema. This construction is also used in the proof of Craig's Theorem.
Comment: You said the $\phi'$s form a single schema! Do you mean a single schema in the sense defined in the question? or just as a decidable set of formulas.
Comment: @Zuhair I was thinking of the schema '$\phi \text{ is an axiom}$', where $\phi$ is a metatheoretic variable that ranges over the $\phi'_n$.


How to trigger/run/execute scheduled task manually?

Question: Is there a way to run a scheduled task manually without any programming?
If not, this way seems not to work properly Manual execution of scheduled rule.
After executing a rule, having another one on the list, clearing caches and running the cron, this feature automatically disappears somehow. There is something wrong in the code.
Comment: Do you want to do it with Rules? If so, when you created a component and scheduled it with rules scheduler, under the Rules Components Tab there will be links next to the listed component, in particular 'execute' whereby you may execute the component, and schedule, which allows manual scheduling of the component. This is mainly there to help debugging the rule component saving you from the trouble of advancing your hosting machines clock.
Comment: @J. Reynolds I would like to execute a scheduled rule earlier than a scheduled date. There is only 'delete' in the scheduled tab. I tried to execute the component but it seems that it's not possible to execute the specific scheduled component?
Comment: Exactly, but it seems you might not have Rules Scheduler installed. It is a sub module of Rules. When it is installed you can schedule Rules to execute at specific times via a Cron run. And you are definitely looking in the wrong tab. You need to be on the Rules Component Tab.
Comment: @J. Reynolds I suppose that this sub module has been already installed by default. I looked in the Rules Component Tab. Yes, there is a function 'execute' but it seems that it is not possible to execute the specific scheduled rule/component which is already in the Rules Schedule Tab. Is that right? For example, a transmission of userpoints has been already scheduled and I would like to execute it a little bit earlier than the scheduled date.
Comment: @J. Reynolds I have verified better and it can be concluded that there is no Rules ID in the Component executing rule set, if I am not wrong, so there is no out of box solution?
Comment: I hesitate to post this as an actual answer (I might convert my comment later on if it makes sense) ... but a possible alternative could be to just use the "execute link" for the actual rules component itself (which is executed right away). And then combine that with a "delete" of what is shown in the scheduled Rules components.
Answer: This is how i do it, I use flags module, i create a user flag for each  "run manualy my special rule" assigning flag/unflag access only to admin user and i display link on user profile page, flagging or unflagging myself to trigger my special rule, then, most of the time i use views rules module to load content, products, orders or users and perform any kind of stuff with it.
Answer: You need to use Scheduler module. This is a way : How to use.
Comment: It is needed to run some other tasks than publishing and unpublishing content. Scheduler is only aimed for that feature, is that right?
Comment: Ok so you want to run scheduler for publishing & unpublishing content.
Comment: For example, a transmission of userpoints is scheduled, if it is needed to be clarified. I suppose, if a task can be executed manually, any task will be run in this way.


May I use a grade of service problem to calculate how many doctors are needed in a hospital?

Question: I created the following problem (based on grade of service problem of Intro to Prob by Tsitsiklis book):
original problem:

My analogy problem:
A Hospital unit has 15 doctors to serve the needs of a population of 100. It is estimated that at a given time, each inhabitant will need to go to the doctor with probability .1,
independent of the others. What is the probability that there are more inhabitants
needing to be served than there are doctors?
Is it correct to use this model to answer a different problem like the one I created?
Answer: Yes, basically you've just changed the objects:

modem $\rightarrow$ doctor
customer $\rightarrow$ patient

And, since $n,c,p$ are the same, your probability is $\approx 0.04$ as well.
Comment: gunes, thank you
Comment: How could I put into words this probability? Something like e.g.: could I interpret 0.03989053 (~0.04) probability as "for every 100 patients who come to the hospital 4 would have to wait if the hospital has 15 doctors" ? or as 'if someone came 100 times at the hospital 4 times this patient would have to wait.'?
Comment: there is a 4 % chance that some patients will not find a doctor
Answer: As @gunes (+1) has said: Taken exactly as stated, you have the same question
either way. $X \sim \mathsf{Binom}(n=100, p=0.1)$ is
the probability a modem/doctor will be busy at a given
time. And you seek $P(X > 15) = 1 - P(X \le 15) = 0.0399.$
In R, where pbinom is a binomial CDF, the computation
is shown below:
1 - pbinom(15,100,.1)
[1] 0.03989053

However, neither model deals explicitly with the period
of time over which a modem/doctor may be engaged.
Also, in the hospital situation it seems artificial to
say the the potential population served is 100 people.
It might be better to get data to estimate the rate at
which patients arrive for doctors' services and model the number needing
service at any one time as Poisson.  For example, if records show the Poisson mean to be $\lambda = 9.5,$ so that $Y \sim
\mathsf{Pois}(\lambda =9.5),$ then $P(Y > 15) = 0.0335.$
1 - ppois(15,9.5)
[1] 0.033473

If you want to take into account the average 'service time'
of doctors, then you would need a queueing model with
appropriate rate of arrival and rate of service by a doctor.
Then the issues become the percentage of time there are more than
15 patients in the system, necessitating a queue (waiting line)
of patients, and the average waiting time in the queue.
Comment: I liked how you explored more the question.
Comment: How could I put into words this probability? Something like e.g.: could I interpret 0.03989053 (~0.04) probability as "for every 100 patients who come to the hospital 4 would have to wait if the hospital has 15 doctors" ? or as 'if someone came 100 times at the hospital 4 times this patient would have to wait.'?
Comment: Those are reasonable statements. Because it refers to the general population, I like the first one best. I might say 'about 4' instead of '4'.
Comment: The problem can be answered by a binomial probability because we may state as 'A person may need a doctor or not' ?