Revisions are listed, but none of them has content

Question: I observed that the Revisions tab lists an entry for every saved revision, but my Twig template doesn't show anything for them.

Is this an issue with the Twig files using {{ node.body.value|raw }}, a configuration issue, or something else?
If it is a configuration issue, how do I enable revisions for the node.body and other fields in my content types?
**UPDATE 2017-06-29 **
The site's base theme is Bootstrap and we have a child theme developed by a third party.
Bootstrap's templates/system/page.html.twig prints body content using {{ page.content }}.
When I use {{ page.content }} in child theme page.html.twig I get fields other than Body expressed.
With debugging turned on here are the extraneous elements.  I need to sort out how to safely express just the body content in a way which the Revision previewer will also display them.

Banner Image

Banner Scroll Image

Banner Quote

ABOUT Freeport-McMoRan

Answer: Yes, the issue is probably with your twig files. If your twig template gets the node from the current route, then {{ node.body.value }} won't work, because the route entity.node.revision doesn't provide a node entity and even if you would load the node with the nid from the route parameter node you only get the current revision. You would have to use the route parameter node_revision and the storage method loadRevision() to get the revision you want.
You can easily resolve this by rendering the node in the node template and print the body with {{ content.body }}. This also removes the security problem with the |raw filter, which you never should use on a body field.
Comment: In the update you ask about a *Revision previewer*. There is no such thing, this is the node template I explained in the answer. You configure which fields and how they are displayed in the content type and probably the custom theme does some more customizing. To cover this process is far beyond the topic of the question.
Comment: Thank you!  Can you point me to a reference for learning how to render the node in the node template?  {{ content.body }} currently contains more than the body field.  I appreciate any pointers as I am brand new to Drupal
Comment: You mean, the output of `{{ content.body }}` has too much html markup? If you want to change this, use a field template. If you want to target the body field use `field--body.html.twig`. Don't remove the attributes, if you want that quickedit and other modules still work. If you don't like the div's then replace them with span's.
Comment: {{ content.body }} dumps an additional img tag housing a banner img associated with the page and the title in an H2 after that.  I'm trying to grab just what was in the Body field.
Comment: This seems quite unusual for a body field. Use twig debug to see which template this is.
Comment: I have added the debugging info wrapping the extraneous fields in page.content output.  I feel quite out of my depth.


How to create model for anova with mixed effects in r

Question: I am very new to r. I was wondering what I should look into to perform an ANOVA random effects. I have some data that have different treatment groups, and an observed behavioral rates as a dependent variable. Each observation occurs at a particular spatial bin (e.g. bin 1 would represent 0-2mm away from a stimulus treatment while spatial bin 10 would be 18-20mm away)
I am attempting to pool the observations for each treatment and determine if there is a significant difference between the observations at each spatial bin. I want to account for the assay number within each treatment as a possible random effect, and avoid possible pseudo-replication of each measured observation. Additionally, I wanted to determine if there was a linear relationship between the observed rate of behavior with spatial bin.
I was originally using an ANCOVA to look for differences however that no longer seems appropriate.  Please let me know what functions/packages I would need to look into. I was looking into using lme4 or something like it to build this model and wanted some feedback on this approach. Any suggestions on a better method for approaching this question would also be greatly appreciated!
Answer: This sounds like primarily a software question, and so is probably off-topic for this site.  You can ask programming questions on Stack Overflow.
Although someone may want to weigh in on the statistical / modeling questions in your post.
lme4 is probably the premier package for building mixed effects models.  Along with it you may want to use lmerTest package, and the emmeans package.
nlme is also a very popular package.  With it, you may want to use car::Anova, although some claim it is better to use anova with nested models. You also want to investigate the emmeans package for lme models.
I don't have a favorite between these two packages.  lme4 is better if you have crossed random effects.  nlme allows you to put in correlation structures, which is helpful in some repeated measures designs.
For a few simple examples, see here, here, and here.  (Caveat: these are my own webpages.)
Comment: Thank you for your response. I had looked into some of these packages already so its nice to know I was in the right direction. I will be looking at those examples later!


Embedding of $2$-torus minus one point into $\mathbb{R}^2$ as an open set?

Question: Let $M^2$ be the $2$-torus minus one point. Is there an embedding of $M^2$ into $\mathbb{R}^2$ as an open set?
Answer: By stereographic projection we can let this embedding be to $S^2$ instead. Let $B$ be a small closed disk centered at the deleted point in $T^2 -\{p\}$, and let $\gamma = \partial B$. By the Jordan curve theorem, the image of $\gamma$ under such an embedding separates $S^2$ into two disks, and therefore the image of $T^2-int(B)$ under the embedding is a closed and open subset of a closed disk and hence is a closed disk. But $\pi_1(T^2-int(B)) \cong F_2$ the free group on two generators so such an embedding never exists.


CakePHP 3, how to use different Datasource based on the $_SERVER['SERVER_NAME']

Question: I have 2 Datasources defined in the app.php.
'Datasources' => [
        'default' => [...
        'test' => [...

I would like to ask how can i use different datasource during the init of the app using $_SERVER['SERVER_NAME'] or any CakePHP method?
Many thanks for any advice.
Answer: In your config/app.php file create your new datasource(s) using your server names.
'Datasources' => [
    'default' => [...
    'test' => [...
    'YOUR_SERVER_NAME_HERE' => [...
    'YOUR_SERVER_NAME2_HERE' => [...

Then in config/bootstrap.php add
ConnectionManager::alias('default', $_SERVER['SERVER_NAME']);

From then on any time the app tries to access the default connection it'll instead be routed to the new connection you've added.
If you're not looking to add new datasources but instead have a scenario where one server is your test server in your config/bootstrap.php add a switch to check your $_SERVER['SERVER_NAME'] and then in your case add the ConnectionManager::alias('default', 'test or whatever datasource you want');


How do I prevent users from messing with their own .ssh folder?

Question: I'm administrating a RedHat server where users log in through SSH with private/pub key based authentication.
I'd like to prevent them from accidentally changing / deleting /chmoding the content of their ~/.ssh folders. Some of them have already recursively 777-chmoded their whole own home folder because "it was easier to share files with colleagues this way" and shot themselves in the foot.
Any idea how I can achieve this? Preferably with standard Linux permission system.
Comment: This is not a technical problem and shouldn't be solved using technical measures. Human stupidity should be solved using administrative measures.
Comment: Once they change their .ssh permissions, they aren't a user anymore, so no longer a problem :)
Comment: The root, ba-dum-tss, problem is that you are forcing people to use Linux who should not be using Linux.
Comment: Also run a cron job every 15mins resetting the permission on their home dirs, they will soon learn
Comment: @hardlib never do this. I bill a minimum of 2 hours a day if any automated tasks need to be undone. Until they learn. Do not mess with user space.
Comment: How about using SSSD and pull the keys out of LDAP instead of storing them locally?
Answer: Short answer is you can't.
SSH is very picky about permissions and will not play with files it doesn't like the look of. Further, the users ssh_config is parsed before the system-wide config.
Having said that, it may be possible to put the files somewhere else and mount the directory as a read-only filesystem under $HOME/.ssh for each user. (It is possible - but I don't know how ssh and associated tools would treat this).

Some of them have already recursively 777-chmoded their whole own home folder

Then you have much bigger SECURITY and training issues.
Comment: @PeterCordes: Last time I tried it, a root-owned authorized_keys was rejected if the user wasn't root.
Comment: Anyway, when you say ssh or sshd are picky, would they reject root-owned files?  Also, instead of a read-only (bind) mount, perhaps just `chattr +i` to make some files "immutable".  Or `+a` only allows append, which could perhaps work for `known_hosts` (but it doesn't prevent rename or changing permissions).  (Oh, there's another answer that mentions `chattr`.)
Comment: @joshudson: Oh, so just `chattr +i` if you want to make things totally unmodifiable by the user.  Clueless users who think `chmod 777 -R ~` is a good idea aren't going to know how to undo that.
Comment: @joshudson Root-owned `authorized_keys` worked fine for me, check out my answer, where I explain that option and more!
Comment: SSH will handle the setup you describe just fine AFAICT, provided that the permissions are correct on all of the files. If you were going to go to that level of trouble though, centralized configuration via `AuthorizedKeysCommand` is probably a better approach though.
Comment: I wondered about making `.ssh` owned by root, with the files in it also owned by root, so the user couldn't chmod them.  Unless they're competent enough to know that they can `cp .ssh .ssh_new` and move aside the old name, unless you set the sticky bit in their home dirs.  In which case insanity like `chmod 777 -R ~` is unlikely.)  Of course, then they couldn't change things *at all* in their `.ssh` directory, including not adding new host keys to `.ssh/known_hosts`.
Comment: Anyone who does `chmod -R 777 ~` deserves to be locked out of the system for a while until their problem is fixed.  Maybe the pain will help them realize that's a bad thing to do.
Answer: It is hard to protect users from their own ignorance and incompetence.
But depending on how much you need to allow your users to manage themselves and how much you manage for them: you can configure sshd to look for keys in an alternative location outside their home directory and elsewhere than ~/.ssh/authorized_keys.
AuthorizedKeysCommand
A relatively complex solution is the /etc/ssh/sshd_config AuthorizedKeysCommand  directive which rather than relying on authorized_keys files specifies a program to be used for lookup of the user's public keys in for example:

a LDAP directory

a database

a (trivial) web service

or when your usernames are identical to Github usernames, you can allow users to authenticate with the keypair(s) that they've uploaded there:
AuthorizedKeysCommand /usr/bin/curl https://github.com/%u.keys

As mentioned in this answer; you'll need to created a suitable SELinux policy for the  AuthorizedKeysCommand  as that gets blocked by the default policies.
I love this approach as it can solve many issues surrounding the management of authorized keys: it adds centralised management, removes the chicken-and-egg problem of getting authorized keys to servers when you want to disable password auth in ssh and more.
It leverages the fact that public keys are not particularly sensitive (unlike their associated private keys) so centralising their management doesn't add risk IMHO and probably even improves your control and reporting capabilities.
AuthorizedKeysFile
Slightly less complex is to store keys in a directory outside of their home directory.
For example   use /etc/ssh/<username> (replacing <username> with their actual username). This directory should have 755 permissions and be owned by the user. Move the authorized_keys file into it. The authorized_keys file should still have 644 permissions and be owned by the user.
In /etc/ssh/sshd_config adjust the AuthorizedKeysFile setting
AuthorizedKeysFile    /etc/ssh/%u/authorized_keys

And restart the ssh daemon
Comment: Love that github method
Comment: AFAIK that also works for on premise Gitlab and you'll almost certainly have the same usernames there
Comment: For `/etc/ssh/...`, the key files can be owned root:root rather than being owned by the user, to further reduce the ability of the user to modify their keys.
Comment: While there's no risk to exposure of public keys there _is_ risk to injection. Allowing logins to anyone with access to an unrelated third party is a pretty big risk.
Answer: The best solution I can think of is to make .ssh and authorized_keys root-owned.
Root-owned .ssh / authorized_keys
SSH is picky with permissions, but not unreasonably so. First, it requires that the user itself has read access to authorized_keys (which requires read access to all parent directories). Second, it denies access if any user other than the user itself or root has write access to /home, .ssh, or authorized_keys. This disallows o+w, and g+w for a group that has other users in it.
This setup works for me, the user can log in:
drwxr-xr-x 19 root root 4096 Sep 22 11:24 /
drwxr-xr-x  3 root root 4096 Sep 22 11:19 /home/
drwx------ 14 test test 4096 Sep 22 11:44 /home/test/
drwxr-x---  2 root test 4096 Sep 22 11:42 /home/test/.ssh/
-rw-r--r--  1 root test   98 Sep 22 11:36 /home/test/.ssh/authorized_keys

Since .ssh and authorized_keys are root-owned, the user cannot change permissions on them, or remove them. They also cannot edit their own authorized_keys file.
If you want to allow the user to edit their authorized_keys, you can add group-write permissions. This requires that the test group has no other members than test itself:
-rw-rw-r--  1 root test   99 Sep 22 12:04 /home/test/.ssh/authorized_keys

With either approach, the user can no longer create their own files under .ssh, so you may want to provide some extra files for them as well. Some that come to mind are: known_hosts, config, and id_rsa{.pub,} or other key types.
Alternative: chattr
Some Linux filesystems supports file attributes, notably an immutable flag. Files/directories with the immutable flag set cannot be deleted, modified, or have their permissions changed. Only root can set/clear this flag.
This command would do the trick, even with the default ownership/permissions:
# chattr +i ~test/.ssh/{authorized_keys,}

Now .ssh and authorized_keys cannot be modified in any way, not even by root. If root needs to update these files, you'll need to chattr -i them first. Use lsattr to check for attributes.
This approach is simpler, but less flexible. It also needs filesystem support; I believe it's supported on at least ext2/3/4, XFS, and btrfs.
Posix ACLs?
There's also Posix ACLs (Access Control Lists), which allow a bit finer-grained control. I'm not too familiar with them, and I'm unsure if they are any help here.
StrictModes
Note: highly discouraged, but provided for completeness.
The OpenSSH server has a configuration directive called StrictModes, which determines how picky SSH is with permissions:

Specifies whether sshd should check file modes and ownership of the user's files and home directory before accepting login. This is normally desirable because novices sometimes accidentally leave their directory or files world-writable. The default is yes.

If you disable that option, you have more liberty in how to set up ownership and permissions. However, SSH is strict by default for good reasons. A user 777-chmodding their SSH files is a security risk.
Comment: "If you want to allow the user to edit their `authorized_keys`, …" – `sshd` from OpenSSH checks `authorized_keys` *and* `authorized_keys2`, so I think you can "hijack" one and allow the user to edit the other. I would "hijack" `authorized_keys2` because I expect tools like `ssh-copy-id` to append to `authorized_keys` by default and I wouldn't want to break them.
Comment: `authorized_keys2` has been deprecated for two decades now.  That it is still supported suggests that it may never be removed (as was announced years ago).  However, since sshd checks whatever files (with legitimate ownership and permissions) is specified in `sshd_config` at `AuthorizedKeysFile`, if you want an alternate filename or location, set it explicitly in config rather than depending on a feature added to support connecting not only with ssh 1.3 and 1.5 but also with the brand new protocol version 2.0
Answer: Run a cron job to fix permissions each night.
Deleting files is a bit harder.  You could possibly restore missing files from backup from cron also.  But, it seems like you could get into weird edge cases with that... may need more intelligence than a script can provide.  I'd start small and add features cautiously to a restore function.
Comment: Perhaps have the cron job *detect* when users have set bad permissions, so you can teach them not to do it again for this or other directories.  Just silently changing permissions without alerting a human is maybe going to confuse the user or lead them to find some nasty workaround that's worse than we can imagine.


Title fields are displayed as a link

Question: For me, all referenced fields or all title fields are displayed as links. This fits in the node as well as in views. However, I don't want this at all, but I would like these fields to be displayed exclusively as text fields.
How can I prevent this?
Comment: You can override the twig template(s) to stop putting out the title as a link, for one. Two in Views if you are outputting fields, you can uncheck the linking options.
Comment: Same goes for rendering ER fields on via the *Label* formatter - just edit the settings and uncheck the link option.
Answer: You can override node.html.twig from whatever base theme you are using, and alter it so the title does not display as a link.

Title fields are displayed as a link


Call assignment from another function - python 3

Question: How do i call an assignment that belongs to another function?
Example:
def get(event):
    barcode = e.get()

def check():
    ic = get.barcode()

I get error like: 'get' is not defined.
How do i call my barcode in the check()?
Thank you.
Answer: Return the barcode in get:
def get(event):
    barcode = event.get()
    return barcode

Then in check, you can call get to obtain the barcode:
def check():
    your_event_variable = 'something' # whatever it may be
    barcode = get(your_event_variable)
    ic = barcode.barcode()

Comment: what if i took away the (event)?
Comment: Well it's the input to the function. If you don't pass it in, how are you going to get the barcode?


Como obter o produto escalar de dois vetores em JavaScript?

Question: Em python, se tenho dois vetores, consigo obter o produto escalar usando numpy. Segue exemplo:
x=np.array([2,4,6])
y=np.array([1,3,5])
np.dot(x,y)

Retorna:
44

Estou procurando uma função equivalente no Javascript. Encontrei uma chamada math.do. Mas, infelizmente, não estou conseguindo usar essa função. Eu tentei:

let a=[2,4,6];
let b=[1,3,5];
console.log(math.dot(a,b))

Que retorna o erro:
ReferenceError: math is not defined

Eu tentei escrever Math como maiúsculo:

let a=[2,4,6];
let b=[1,3,5];
console.log(Math.dot(a,b))

Mas retornou o erro:
TypeError: Math.dot is not a function

O que estou fazendo errado aqui? Como posso obter um produto escalar no Javascript?
Comment: Não precisa pedir desculpas!! :) Você consegue acessar o "módulo" [`Math`](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Math) porque ele é um objeto global _built-in_ do JavaScript. Já a biblioteca em questão (`mathjs`) ao qual você se referiu não é "nativa", então você precisa importá-la de alguma maneira. Só estou tentando entender o que você fez (porque atualmente a pergunta precisa de mais detalhes).
Comment: Tente reproduzir o erro aqui, por favor? Uma sugestão é utilizar o snippet de códigos.
Comment: Editei a pergunta para incluir o snippet
Comment: Como você fez para incluir a biblioteca? Utilizou algum `
Comment: Estou rodando no node.js
Comment: Você instalou a biblioteca utilizando `npm`? Está utilizando o `require`? Ainda faltam detalhes em sua pergunta.
Comment: Não estou usando o `require`. Desculpe, sou um completo newbie em Javascript. Esse módulo `Math` funciona no navegador, mas para usar no node eu preciso importar? Como faço para importar?
Answer: Se você está no Node.js[Comentário], deve instalar a biblioteca através de um gerenciador de pacotes. No Node.js, os gerenciadores de pacote mais comuns são o npm (que já vem instalado por padrão com o Node.js) e Yarn, que pode ser instalado à parte.
Para instalar uma biblioteca utilizando Node.js, a partir da pasta raiz do seu projeto, execute o comando:

npm install <nome da biblioteca>

No seu caso, deverá fazer npm install mathjs, conforme a documentação aponta. Você pode verificar a página da biblioteca mathjs no site do npm aqui.
Uma vez que você tenha instalado a biblioteca, pode utilizar o require para importá-la:
const math = require('mathjs');

let a = [2,4,6];
let b = [1,3,5];
console.log(math.dot(a, b)); //=> 44

Note que ao contrário de CDNs (utilizadas comumente nos browsers para a importação de bibliotecas), no Node.js os objetos não são expostos globalmente. Assim, você deve importar a biblioteca que quer utilizar explicitamente.
O require do Node.js segue o padrão CommonJS. Existe também o ECMAScript modules, que pode ser utilizado como "sintaxe" alternativa ao CommonJS em versões mais recentes do Node.js.
A título de curiosidade, se estiver em versão do Node.js que suporte, pode utilizar a sintaxe de ECMAScript modules:
import * as math from 'mathjs';

let a = [2,4,6];
let b = [1,3,5];
console.log(math.dot(a, b)); //=> 44

Saiba mais sobre o CommonJS no contexto do Node.js. E sobre o ECMAScript modules.
Answer: O math.js funciona perfeito e retorna o mesmo resultado:

let a=[2,4,6];
let b=[1,3,5];
console.log(math.dot(a,b))

Pela mensagem não adicionou a lib corretamente, pode fazer o download ou usar o link para um cdn na internet e adicionar na tag


Super fast scales and octaves, How?

Question: I looked at the sheet music for a piano transcription of The Four Seasons and I see in the third movement of Summer, 2 things that I don't know if I can do. It has partly to do with the Presto tempo but that alone isn't the issue. Here are the 2 things I see.
Alternating between right hand and left hand octave with 1 note shared(the middle note). This I'm pretty sure I can't do at a fast tempo. The middle note would probably not sound out.  But I have a few alternatives.

I could have the left hand do an octave tremolo while I have the right hand playing the upper note at half the note speed of the tremolo
I could have both hands play static octaves and just play the right hand of the beginning section 8va
I could get rid of the static octaves all together and use octave tremolos instead, playing the right hand 8va. I tend to get less tension at a fast tempo with tremolos than with static octaves

But there is another issue I see, scales being played so fast I am essentially doing a fingered glissando. I don't often do glissandos anyway but I have never done scales at Presto before. It seems very intimidating. And while I do have fast, nimble, and strong fingers, I'm not sure how I would go about playing a scale at Presto. Would I just speed up a scale played at Allegro gradually to Presto or what?
So how would I play a scale at Presto and which of the 3 alternatives do you think is best to get that same richness and fast octaves sound without having the right hand and left hand share a note in the octaves?
Comment: As I say to everyone all of the time: *if you want to play fast, you have to play slow*. Speed comes naturally and quickly when you truly know the material.
Comment: Can I see the sheet music of this transcription, please, or at least the relevant portion? As an amateur piano transcriber, I believe it's quite possible that the transcription was also created by an amateur who didn't take the difficulty of the passage into account--or did and decided to keep the passage fiendishly difficult anyway.
Comment: To add the obvious:  practice, practice, practice.  Don't increase the practice tempo until you can play it at a certain speed easily and correctly every time.
Answer: Take a look at other piano versions. On IMSLP there are two piano versions:
https://imslp.org/wiki/Violin_Concerto_in_G_minor%2C_RV_315_(Vivaldi%2C_Antonio)
Scroll down to "Sheet Music" and click on "Arrangements and Transcriptions (13)".
There you will find two piano versions, one made by Justin Bird and one made by Roberto Novegno. They are very different. Those versions can give you great ideas on what you can do in order to play "Summer" on piano.
Also compare with the original score.
The main point is playing something which reflects the music and at the same time fits the instrument.
Answer: Technique is literally in your head.  When you practice, your brain hard wires your movement into "muscle memory" and like it or not, flawed or not, that is what your brain will regurgitate to your hands until you re-wire those movements.
If you have difficulty with speed, your technique is flawed.  NO AMOUNT OF PRACTICE WILL FIX THAT.  Practice doesn't make perfect, perfect practice makes perfect.
You need to find a new teacher who can teach you proper ergonomic movement.
Comment: This is a quote I like: "practice makes _permanent_" Make sure what you are making permanent is what you really want.
Comment: It seems a good answer but I think you meant 'no amount of the same sort of practice' will help, while good practice would be the solution to ergonomics.
Answer: Guitarist Robert Fripp has spoken of economy of movement, e.g., do not bother lifting fingers that do not need to be lifted right then and using as little motion in the fingers as necessary.

Super fast scales and octaves, How?


How to play the dynamic correctly?

Question: Is there any rule of thumb for how loud/quiet the dynamics should be played?
Like, when I see "pp" I know to play it softer than "mf" or "f", for example, but I have no way of knowing if I'm playing it soft enough, or if I'm making it different enough to when I play"p".
Is there any tips or practices that I can do to help with this, or do I simply have to listen to the piece that I'm trying to play, and copy it?
Comment: Three words: **Use your ears** - both to listen to other people playing of the type of music that you want to play, and also to *listen to yourself while you are playing* - it might surprise you to learn how many students *don't* do that simple but important thing, because their brain is too busy trying to read the score, play the notes,  etc, etc.
Answer: I use this mental guideline (not as in decibels but more in the sense of 'effect'):
pp: whispering, as silent as you can play
p: having an intimate conversation with someone standing next to you
mp: having a normal conversation with someone standing next to you
mf: having a conversation with a group of people in a meeting, everybody needs to understand you, even in the back
f: shouting
ff: roaaaaaaarrr, as load as you can play
Answer: When you listen to a recording of the piece you want to play, listen to several different ones. You'll notice that it's not the same dynamics for each player.
As a rough guide, pp ( or ppp) is just about as quiet as you can play, to ff (or fff) just about as loud as you can play. Problem is, it depends a lot on the instrument, the room it's in, you as a player, and probably other factors too. And it'll depend on where you yourself put the mid point, from which all the markings are relative.
There's no exact middle point, either. It goes from mp to mf, as there can't be an 'm'. So, it's all rather relative. Obviously f is louder than mf, and pp is quieter than p, but there are no decibel readings for any of the dynamics.
In fact, they're there as a guide rather than etched in stone, and while some pieces sound great when the dynamics are adhered to exactly (although even that is subjective), others can benefit from your own interpretation, or even a re-jigging of it all. Most players will let the music do the speaking, and rise or fall accordingly. We're back to ears again, I'm afraid!
Answer: It varies with the piece, the instrument, the size and acoustics of the room...   Just make sure you can fit all the required dynamics into the overall scale you choose.
Answer: Generally speaking, Pianissimo would be as soft as possible, Piano would just be soft, Mezzo-Piano would be semi(or half) soft, Mezzo Forte would be semi(or half) hard, Forte would be loud (hard) and Fortissimo would be as loud or hard as possible.
With all these things said you are allowed a fair amount of artistic license in these matters, as long as Piano is softer than Mezzo-Piano and Fortissimo are louder than Forte, you should be OK.
These matters are not an exact science, as long as your music portrays the correct character the finer details on how loud is loud is not important.
Answer: From my personal experience, it is kind of relative. It helps to look at the overall dynamic range of the piece you're playing and set the loudest and softest you want to go before you start playing. But really, as long as there is a noticeable difference between pp, p, mp, mf, f, and ff, and you can switch between them and make sure the change is noticeable to your audience, then you've done it right. If your audience (or you when you're listening to yourself) can't tell that you just switched between mp and mf, then maybe your overall range is too small, and you need to make your louds louder and your softs softer, to ensure a good dynamic variety.

How to play the dynamic correctly?


Do I have to enter the public IP into the HOME_NET variable?

Question: Do I have to enter the public IP of eth0 as HOME_NET in the suricata.yaml?
vars:
  # more specific is better for alert accuracy and performance
  address-groups:
    HOME_NET: "[192.168.0.0/16,10.0.0.0/8,172.16.0.0/12]"

My understanding is that only private addresses belong in the variable HOME_NET
Answer: $HOME_NET is supposed to list the IP addresses of your protected hosts/networks. It doesn't matter if these addresses are private or public.


Recursion in C only works when printing unrelated things

Question: I've just started learning C, and I decided to work on some of the Euler Problems for practice.
The program that isn't working is meant to solve Problem2, which asks to compute the sum of all even Fibonacci numbers below 4,000,000.
What's really weird about this program is that it actually works, but only if I print something during recursion: whenever I try commenting out the printf("bazooka"); line in the recursive function, I get results that seem completely random, and vary between large positive numbers and large negative numbers (eg  -882154758 and 770491113) upon successive executions of the same program.
On the other hand, if I print something, no matter what, in the recursive function, I get the correct output.
I find this behavior extremely weird and interesting, and I would really like to know what's going on: what really puzzles me is that the outputted number changes even when the program is not altered at all. Also, I don't understand why printing during recursion should have any effect on the integer computations being performed.
This is my main function:
int first = 1; int second = 2; int total = 0;
total = Fibo(first,second, total);
printf("\nthis is my result for Euler 2: ");
printf("%d",total);

And this is my recursive function:
  int Fibo(int first, int second, int total) {
  printf("bazooka");
  if (second < 4000000) {
    int add;
    second = first+second;
    first = second-first;
    if (first%2 == 0) {
      add = first;
    }
      total = add+Fibo(first,second,total);
  }
  return total;
}

Can anybody help me figure this out? I really appreciate your help.
Comment: You need to initialize `int add = 0;`. Otherwise it can (and apparently does) take whatever value happens to be written in the location where it is stored in the line `total = add+Fibo(first,second,total);`
Comment: @andy_programs as Rad Lexus pointed out, it doesn't really solve it (at least not in a reliable manner) - it may just have been a side-effect on your particular system where the call to `printf` changed values in the memory location which was later occupied by `add`. There is no guarantee for that behavior though
Comment: No it isn't, it suggests that you dump your solution and start over, since programming is about finding the simplest solution. Build your skill with the difficulty of the questions, not make them more complicated than they are.
Comment: Even with your `bazooka` fix, I get `-1900183196`. Surely that is wrong.
Comment: A recursive function is complete over-kill. Save that technique for the more difficult questions. One simple loop will do it. As the limit is 4000000 `int` is adequate with 32-bit machine.
Comment: Thanks a lot @UnholySheep! I thought that the add variable would be newly initialized to 0 every time the recursive function was called, but apparently that's not the case. I'm still puzzled by the fact that printing something resolved the problem. Does anybody know why that happens?
Comment: @WeatherVane thanks for the input but that's pretty unrelated to my question. The purpose of this program for me is not only to solve the problems but, more importantly, to learn as much C syntax quickly. Recursion seemed like a fun way to learn about function calling and the like.
Comment: @UnholySheep that makes sense. Thank you!
Answer: add is not initialized if first is odd. Make sure to initialize the variable in both cases and the bug will go away.
Now, for explaining the observed behavior: using an uninitialized variable can show as a random "value" or it can cause the program to malfunction in other random ways. (The technical term in C-like languages is undefined behavior.) In your case it is likely that the value was a garbage left over from the previous usage of the memory location used for the stack frame of the function, or the previous value of the register. A call to printf can appear to fix things because its implementation happens to use and clear the relevant portion of the memory. Needless to say, this is not something you can depend on.
Note that this kind of bug will be diagnosed by the compiler with the appropriate warning settings, such as -Wall for GCC or Clang.
Answer: Well, I cannot relate 100% about that behavior, but for sure when you get numbers like the negative number, is because you are exceeding the max value of the int value:
INT_MIN = -2147483648
INT_MAX = +2147483647

Change this type to long, or long long if getting the same result.
Here you can check the data type boundaries.
Comment: This was a fair guess, but as you can see by the other answer, it's not the cause here. A good way to check if this is the problem is to actually print out the intermediate values; doing so shows it never reaches that high.
Comment: Ignore my previous comment, it seems the values presented in your link are strange and not very representative. One of the reasons why I prefer [cppreference](http://en.cppreference.com/w/c/types/limits) over cplusplus.com - the information there is usually more accurate. (Also `INT_MIN` and `INT_MAX` are not actually constants, they depend on the compiler)
Comment: As it happens, `int` is adequate for the [problem](https://projecteuler.net/problem=2).


Extended UIButton border is not initially drawn

Question: I am trying to create a custom UIButton which extends from UIButtonType.RoundedRect.
My added functionality is working, but there is an issue with the initial rounded border state of my button. The border of my extended button is not drawn until after it has been tapped.

Update (January 24th 2013): Added the result of red background test, as requested by Richard Marskell, which concludes only the label of the button is drawn. BackgroundColor = UIColor.Red;

Below is my source code for creating my custom button.
public class TestView : UIView
{
    public TestView(IntPtr p) : base(p) { }

    public TestView(RectangleF bounds)
    {
        Frame = bounds;
        BackgroundColor = UIColor.White;

        UIButton button1 = new UIButton(UIButtonType.RoundedRect);
        button1.Frame = new RectangleF(20,20,100,50);
        button1.SetTitle("Button 1", UIControlState.Normal);
        AddSubview(button1); // Drawn Correctly

        MyButton button2 = new MyButton();
        button2.Frame = new RectangleF(20,90,100,50);
        button2.SetTitle("Button 2", UIControlState.Normal);
        AddSubview(button2); // Only drawn correctly after Tap

        // EDIT: Added to test Miguel's theory
        UIButton button3 = UIButton.FromType(UIButtonType.RoundedRect);
        button3.Frame = new RectangleF(20,160,100,50);
        button3.SetTitle("Button 3", UIControlState.Normal);
        AddSubview(button3); // Drawn Correctly
    }
}

public class MyButton : UIButton
{
    public MyButton() : base(UIButtonType.RoundedRect) { }
}

I'm just not sure how to force the border to be drawn correctly on loading of the view.
I don't need a button of type UIButtonType.Custom, as I don't want to style the button myself.
When I debug I the type of MyButton is correctly set to UIButtonType.RoundedRect.
The UIButton base properties of MyButton (button2) match the properties of the UIButton instance (button1).

How can I resolve this issue?

Update (January 31st 2013): Herman Schoenfeld provided a suitable solution for this bug.
Comment: +1 for a well formatted question.
Comment: A factory class cannot be inherited from. That said, it is strange that a public constructor is provided for a factory class such as this. There is nothing from your code that would lead one to believe that the behavior of the factory method would differ from that of the constructor with the `UIButtonType` parameter.
Comment: Can you try UIButton.FromXXX method to create the button instead of the constructor?   Just to try out a theory
Comment: @miguel.de.icaza Thanks for looking into this. I have tried creating a UIButton using the `UIButton.FromType` method, and it is drawn correctly. I am not sure how I am supposed to use this method of create an instance of MyButton using this method.
Comment: @aardila Thanks for the clarification about the Factory class. Yeah it does seem odd.
Comment: Does the same thing happen if you create both buttons in the same way, either both through the base class or both through the custom one? Perhaps the custom class issue is a red herring.
Comment: @StephenHewlett I am not sure entirely what you mean by "create both buttons in the same way". Can you provide code for what you mean or elaborate on your approach please, then I can try it out? Thanks.
Comment: Try replacing `MyButton button2 = new MyButton();` with `UIButton button2 = new UIButton(UIButtonType.RoundedRect);` and vice versa, to see if the buttons still display properly.
Comment: @StephenHewlett I see what you are saying now. I tried this test before posting to SO. Changing the second button as `UIButton(UIButtonType.RoundedRect)` is drawn correctly, and setting button1 as `MyButton` is not drawn correctly. Same issue.
Comment: Out of curiosity, does changing `BackgroundColor = UIColor.White;` to something like red give any indication of, say, a white border or weird draw bounds?
Comment: @RichardMarskell-Drackir thanks for the suggestion. Only the label is drawn. I have updated the question to include a screenshot of the outcome.
Answer: This works
public class MyButton : UIButton
{
    public MyButton() : base(UIButtonType.RoundedRect) { }

    public override RectangleF Frame {
        get {
            return base.Frame;
        }
        set {
            var temp = TranslatesAutoresizingMaskIntoConstraints;
            TranslatesAutoresizingMaskIntoConstraints = false;
            var constraints = new [] {
                NSLayoutConstraint.Create(this, NSLayoutAttribute.Width, NSLayoutRelation.Equal, null, NSLayoutAttribute.NoAttribute, 1.0f, value.Width),
                NSLayoutConstraint.Create(this, NSLayoutAttribute.Height, NSLayoutRelation.Equal, null, NSLayoutAttribute.NoAttribute, 1.0f, value.Height)
            };
            AddConstraints(constraints);
            SizeToFit();
            RemoveConstraints(constraints);
            base.Frame = value;
            TranslatesAutoresizingMaskIntoConstraints = temp;
        }
    }
}

This is only a workaround, it appears to be a bug. The SizeToFit() fixes the issue, the other code maintains the frame.
Comment: Thanks Herman, a good solution to this bug. I have overriden the `Frame` property of my button so the fix is applied without the need to call the separate method `Fix()`.
Comment: Updated with your suggestion.


Between doesn't yield expected results in pgsql in function

Question: I have the following sequence in pgsql in PostgresSQL 9.2.10. The SELECT statement works as expected.
foreman=> SELECT 'architectures', id, created_at FROM architectures WHERE created_at BETWEEN '2015-05-04 12:03:38.234225' AND now()
;
 ?column? | id | created_at
----------+----+------------
(0 rows)

The following is the function definition:
foreman=> CREATE OR REPLACE FUNCTION getTableIfUpdated(_created_at_text TEXT)
foreman-> RETURNS SETOF tablecreatedat_rs
foreman-> AS
foreman-> $func$
foreman$> DECLARE
foreman$>   created_at TIMESTAMP;
foreman$>   t CHARACTER VARYING;
foreman$>   r RECORD;
foreman$> BEGIN
foreman$>   created_at = to_timestamp(_created_at_text, 'DD/MM/YYYY hh24:mi:ss');
foreman$>   FOR t IN SELECT table_name FROM information_schema.tables t1 WHERE EXISTS (SELECT column_name FROM information_schema.columns t2 WHERE column_name='created_at' AND t1.table_name=t2.table_name) AND EXISTS (SELECT column_name FROM information_schema.columns t3 WHERE column_name='id' AND t1.table_name=t3.table_name) ORDER BY table_name
foreman$>     LOOP
foreman$>       FOR r in EXECUTE 'SELECT $1, id, created_at FROM ' || t || ' WHERE created_at BETWEEN $2 AND now()' USING t, created_at
foreman$>       LOOP
foreman$>         RETURN NEXT r;
foreman$>       END LOOP;
foreman$>     END LOOP;
foreman$> END
foreman$> $func$ LANGUAGE plpgsql;
CREATE FUNCTION

The following is the function invocation:
foreman=> select getTableIfUpdated('2015-05-04 12:03:38.234225');
                         gettableifupdated
--------------------------------------------------------------------
 (architectures,2,"2015-05-04 01:34:40.800257")
 (architectures,1,"2015-05-04 01:34:40.796382")
 (audits,1,"2015-05-04 01:34:24.950228")
 (audits,2,"2015-05-04 01:34:25.330426")
 (audits,3,"2015-05-04 01:34:32.385152")

Note that I expect 0 rows from the function. However, the values returned all have created_at which occurs before the specified value. Suggestions?
Comment: Why don't you just pass a `timestamp` directly to the function. Passing dates, timestamps or numbers as varchar is almost always a bad choice
Answer: line
created_at = to_timestamp(_created_at_text, 'DD/MM/YYYY hh24:mi:ss');

should be replaced with
created_at = to_timestamp(_created_at_text, 'YYYY-MM-DD hh24:mi:ss');

because it converts timestamp incorrectly:
select to_timestamp('2015-05-04 12:03:38.234225', 'DD/MM/YYYY hh24:mi:ss');
  to_timestamp
------------------------
0009-11-05 12:03:38+00


question about the dimension of the global section space of a vector bundle

Question: Suppose that $L,L^{'}$ are a line bundle over a compact riemann surface $C$. Take $H^0(C,L\otimes L^{'})$.
Is it true that $h^0(C,L\otimes L^{'})=h^0(C,L)+h^0(C,L^{'})$ where $h^0(V)$ ,means the complex dimension?
Comment: No. Have you tried some examples?
Comment: @Alex Youcis is the statement  negative even if i suppose that both of lines bundle satisfy the relation that the double tensor product is equivalent to the caninical bundle?
Answer: This is false: let $C = \mathbb{P}^1_{\mathbb{C}}$ and let $L = \mathcal{O}(-1)$ and $L' = \mathcal{O}(1)$. Then,
$$2 = \underbrace{h^0(C,L)}_{=0} + \underbrace{h^0(C,L')}_{=2} \neq h^0(C, L \otimes L') = 1.$$
It might be more reasonable to expect the dimensions to multiply i.e. have
$$
h^0(C,L) \cdot h^0(C,L') = h^0(C,L\otimes L'),
$$
because there is a natural map $H^0(C,L) \otimes_{\mathbb{C}} H^0(C,L') \to H^0(C,L \otimes L')$. However, this will not always be true, since this map is not an isomorphism, in general. (If $C$ is an affine scheme over $\mathbb{C}$, then this will be true: see the excellent answer here by Georges Elencwajg.)
Comment: I think you made a mistake. $h^0(C,L\otimes L')=0$. Maybe $L=\mathcal{O}(-1)$ and $L'=\mathcal{O}(1)$
Comment: Good catch, thanks!


Sampling Correlated Binary Values

Question: Say I have two variables X, Y.  We progress through iterations 1 to i, and pull a binary TRUE/FALSE for each variable.  Each variable has it's own probability of getting TRUE each period P(X) and P(Y) (and each period is independent).
In addition, though, there is a probability of each variable getting a TRUE each period IF, in that period, another variable got a TRUE.  i.e. there exists a P(X) and a P(Y) draws TRUE, but there also exists a P(X|Y), P(Y|X) where P(X|Y) does not have to equal P(Y|X).
The question is, how can I sample accurately for both X and Y taking into account both P(X) and P(Y), as well as the contingent probabilities P(X|Y) and P(Y|X), such that the sampled values for X and Y in periods 1 to n end up having TRUEs at a frequency similar to P(X) and P(Y) for X and Y respectively?
Then, can that solution be expanded to the three variable problem?  Up to N number of variables.
**My first attempt was to sample against P(X) and P(Y) independently, and then each period IF one or the other was TRUE, test if the other should be changed to TRUE.  Clearly, though, this leads to TRUE frequencies that are greater than P(X) and P(Y) at the limit.
<code>##define P(X) and P(Y)
p_x <- .15
p_y <- .2

##let the columns be the contingency in the joint distribution (i.e. X in P(Y|X))
j_mat <- matrix(1, nrow = 2, ncol = 2)
j_mat[1,2] <- .7
j_mat[2,1] <- .3

##we can then clearly sample independently for TRUEs at the correct probability

sample_length <- 1000

x_sample <- runif(sample_length, 0, 1) <= p_x
y_sample <- runif(sample_length, 0, 1) <= p_y

##but how to also factor in "j_mat"?
```
</code>
Comment: j_mat is the matrix of contingent probabilities for the variables X and Y.  So the diagonals of the matrix are P(X|X) and P(Y|Y), which equal 1, and then the off diagonals are P(X|Y) and P(Y|X), which I have defined as 0.7 and 0.3
Comment: Can you describe more what `j_mat` is?
Comment: Three parameters are needed to determined your distribution. For example, P(A), P(B|A=0) and P(B|(B|A=1). or P{(0,0)}, P{(0,1)} and P{(1.0)}. So you need to find value of three parameters, then you can goto next step. Currently, you just give 2 parameter(0.15 and 0.2), and it is not enough to keep going.
Answer: Can you represent your dependence structure as correlation as your title suggests?
<code>library(copula)
r <- 0.75 # correlation coefficient
p1 <- 0.15 # parameter for the first marginal binomial distribution (X)
p2 <- 0.2 # parameter for the second marginal binomial distribution (Y)
N <- 1000 # size of bivariate sample
cop <- normalCopula(r) # define the copula as Gaussian with correlation r
# define the population with binomial marginal distributions
P <- mvdc(cop,c("binom","binom"),list(list(size=1,prob=p1),list(size=1,prob=p2)))
d <- rMvdc(1000,P) # sample from the bivariate population
</code>
Then "d" is the sample you want.
Edit: Thinking about this more, I have an idea that I concede is not complete.
You're playng with $P(X=x|Y=y)$ and $P(Y=y|X=x)$. However, you also are specifying $P(X=x)$ and $P(Y=y)$. If you specify three of them, Bayes' theorem gives you the fourth, so you can't tweak all four to your heart's content. The fourth is locked in once you specify three. Therefore, focus on only one conditional probability, let's say $P(Y=0|X=0) = p$. Then we also have that $P(Y=1|X=0) = 1-p.$
When we consider continuous correlated variables (say Gaussian marginals), we think that positive correlation means that X and Y are similar while negative correlation means that $X$ and $Y$ are opposite. For instance, with correlation of 0.9 and standard normal marginals, if we know that X is negative, we have a good idea that Y is also negative. In your case, you only have two values for each marginal variable. If $X$ is 0 and there a positive correlation between $X$ and $Y$, we expect $Y$ to be 0. That's related to $P(Y=0|X=0)$, except that we need some kind of transformation between $[0,1]$ where probability lives and $[-1,1]$ where correlation lives. What I'm proposing is that we transform between the two spaces using the linear function between (0,-1) and (1,1) where probability is in the first coordinate and correlation is in the second. That equation is $corr = 2*P(Y=0|X=0) -1$.
Something funky happens with discrete distributions where the copula isn't unique, so it makes sense to me that you might be able to represent any dependence between binary variables as a Gaussian copula.
Comment: I'll work through this tomorrow, I like the idea.  I'm maybe a bit worried that my dependence structure isn't quite correlation (admittedly an imprecise use of the term in the title) because the potential set for every relationship is [0,1].
Comment: @garm00 Do you say the set is [0,1] because it's a probability?
Comment: Correct yes that's why
Comment: I like the transformation idea.  That reminds me in a way of creating a process for sampling from a multi-variate normal distribution for correlated normal errors.
Answer: Given
<code>  p_x <- .15            means P(X=1) = 0.15
  p_y <- .2             means P(Y=1) = 0.20
  j_mat[1,2] <- .7      means P(X=1|Y=1) =0.70
</code>
We need $P(X=1|Y=0)$, which can be derived as:
$P(X=1|Y=0) = (0.15 - 0.2*0.7)/(1-0.2) = 0.0125$
So change
<code> x_sample <- runif(sample_length, 0, 1) <= p_x
 y_sample <- runif(sample_length, 0, 1) <= p_y
</code>
to
<code> y_sample <- runif(sample_length, 0, 1) <= p_y
 x_sample <- ((runif(sample_length, 0, 1) <= 0.7)*(y_sample=1) +
             ((runif(sample_length, 0, 1) <= 0.0125)*(y_sample=0)
</code>
The meaning is if Y = 1 then get X from Bernoulli distribution with p =0.7, and if Y = 0 then get X from Bernoulli distribution with p =0.0125,
This method can be expended to the N variables situation, but need to specify 2$^N$ parameters.
Comment: Can you explain this a bit?  It looks like in your last snippet of code you're adding Boolean type results together?
Comment: I added the explanation into Answer.

Sampling Correlated Binary Values


Why is it useful to sample probability distributions?

Question: I was reading the book Deep Learning by Goodfellow, Bengio & Courville and it seemed to imply that samples are only useful to:

approximate sum/integrals (why is this sooo important?)
when the goal is to generate samples itself (which is trivial since of course its important to sample if that is the goal)

However, I remain unable to appreciate why sample is so important and why so much hard work has gone to study such a topic. Why is sampling important? Are there no other motivations? Are these really important enough on its own?
I'd love to be able to appreciate why sampling is an important topic.

My own thoughts
As someone inclined for ML, minimizing the expected loss is my goal:
$$ E_{x,y \sim p*_{x,y}} [Loss(f(X),Y)]$$
where $p^*$ is the true unknown distribution.
so I guess since this expectation is a sum or an integral we could try approximating the true generalization of our model if we could create more samples or create a model of the true distribution. This seems important, though it seems that this is not the approach people do for ML for some reason...

To provide further context on the exact extract I was reading from the deep learning book on the chapter on sampling (and Monte Carlo Methods) here is exact paragraph I was reading, title:
Why Sampling:

There are many reasons that we may wish to draw samples from a
  probability distribution. Sampling provides a flexible way to
  approximate many sums and integrals at reduced cost. Sometimes we use
  this to provide a significant speedup toa costly but tractable sum, as
  in the case when we subsample the full training costwith minibatches.
  In other cases, our learning algorithm requires us to approximatean
  intractable sum or integral, such as the gradient of the log partition
  function ofan undirected model. In many other cases, sampling is
  actually our goal, in thesense that we want to train a model that can
  sample from the training distribution. (Chapter 17)

for me just reading that section equates to "drawing samples (from a model) is only useful to approximate sums/integrals and when you want to do sampling". For someone with much less of a statistics background, this justification seems quite shallow. I have seen a lot of mathematics and textbooks (like Koller's PGM book) devoted to sampling from models. This seems quite an important topic and it just seems that this book lacked a proper motivation for the why. This is where my question stems from.
Comment: Could you identify any scientific study anywhere that does not rely on a sample?  That might help us understand what you might mean by "samples."
Comment: I am struggling to understand what you are talking about.  Could you indicate what the context, situation, or application is that you have in mind?
Comment: @whuber maybe I should re-phrase, why is sampling from a model important? Of course we need sample given by the true process (frequentist mindset) to do anything.

Maybe what I mean is, what is the point of sampling if we can just rely on the true true distribution for "correct" samples. Why would we need to make up samples?
Comment: We have a site with (quite literally) thousands of questions which involve sampling distributions in one way or another (some [search and research](http://stats.stackexchange.com/help/how-to-ask) may be needed for your question). Can you focus your question a bit?
Comment: @whuber I provided the exact paragraph from the book I am reading, hope it helps provide further context. What I am really going for is more for the **why** of sampling (from a model $p_{model}(x) $) rather than the **how**. There seems to be plenty of literature on the how, but very few comments on the why.

For example, if I made a probabilistic model to sample more images seems like a silly model if we can get natural images really easy. This is just a silly example, though.
Comment: @whuber unfortunately that is actually the **whole** section that book uses to motivate sampling (the **why** of its importance). Then it seems they move on to just talk about how to sample. I will keep reading the book and provide more details to the question as I discover more. Thanks for the help, I appreciate it, I am trying to help out as much as I can :) I will keep working on it. (though maybe Deep Learning is what I am most interested right now, not sure if it helps)
Comment: The quotation helps because it shows you are using "sampling" in a very narrow context.  Because neither you nor the quotation has described that context in any detail, your question seems vague and puzzling.  That's why you are getting these requests to focus it.
Answer: Often enough, we are not only interested in evaluating an integral, e.g., for calculating the expectation of a random variable, but in understanding the entire distribution, say for deriving quantiles. Which is important, e.g., in inventory control. And often enough, the underlying distribution is not analytically tractable, so sampling is the easiest and fastest way of going about this.
A simple example from my daily life: suppose we want to have a quantile forecast for retail sales. We believe than each day's sales are negative binomially distributed with known (forecasted) parameters. However, we don't need quantiles per day, but across, say, three or five days (because the truck arrives to fill up the store shelves twice a week, so each delivery has to cover multiple days). The sum of negbins is not analytically tractable, but it's trivial to simulate from each day's negbin, add the simulated values and get an appropriate quantile from the simulated sum that will achieve our desired service level.
(Plus, there are lots of other applications in cryptography etc. if you are really interested in why people invest so much effort in random-generation.)
Comment: @Glen_b already gave a good explanation for why quantiles are important in inventory control. Simply put, you don't only want enough milk in the supermarket to cover *average* demand - you want (say) 95% of shoppers to get what they want, not run out of product after half the shoppers have arrived. You need quantiles for that. Regarding crypto, I'm not a expert - [Crypto.SE](https://crypto.stackexchange.com/questions/tagged/random-number-generator) might be useful.
Comment: sorry if this is a trivial question but why are quantiles super important? That random-generation like you gave sent me to a lot of questions...is there one I should read or do you mind providing a comment on crypto?
Comment: Using Stephan's example, let's say you want to have a 75% chance (or pick any other number you like) not to run out of stock before the following shipment arrives. How much will you need to order for the next few days?
Answer: This is an important question to ask. I think you've hit a bit of a wall with it because of the common misconception that to draw a line between "sampling from a probability distribution" and "sampling from a population" is to create a false dichotomy. Let's look at a simple Bayesian example:
You flip a coin $n$ times and record $X$ heads. The number of heads in $n$ flips is given by the binomial distribution:
$$P(x|\theta)= \binom nx \theta^x (1-\theta)^{n-x}$$
We're interested in finding out plausible values for $\theta$, the probability of the coin landing Heads. We are interested in the posterior distribution of $\theta$:
$$p(\theta|x)=\frac{p(x|\theta)*p(\theta)}{A}$$
$A$ is just a normalizing constant, and yet it is often too complicated to solve for. This means we want to be able to sample from unnormalized distributions (distributions that do not add up to 1). So, instead of sampling from $p(\theta|x)$ we are interested in sampling from the unnormalized distribution $p(x|\theta)*p(\theta)$. Finally, we want to sample under different priors (different assumptions about the prior distribution $p(\theta)$).
If we assume 3 different priors for $\theta$, we want to be able to sample from  all 3 unnormalized probability distributions:
$$p(x|\theta)*p(\theta)=p(x|\theta)*prior_1$$
$$p(x|\theta)*p(\theta)=p(x|\theta)*prior_2$$
$$p(x|\theta)*p(\theta)=p(x|\theta)*prior_3$$
What this example tried to illustrate is that we need the ability to sample from any nonnegative function that we may want to write down on paper; I don't call it a probability distribution because some may think this refers to sampling from named distributions only (Normal, Binomial, Poisson, etc.); yet in practice we are sampling from some unnamed complicated nonnegative function. The other reason I do not call it a probability distribution is so that we do not mistake our mission for that of sampling from normalized distributions only; very often we need to sample from unnormalized distributions.
Now, finally, I am ready to actually answer your question. The reason it is important to learn how to sample from any nonnegative function we may write down (unnormalized probability distribution) is that real life phenomena are very complex. We model that complexity with a statistical model. Whether with a Monte Carlo simulation or a Bayesian statistical model (e.g. Hierarchical Model), at the end of the day we are interested in some random variable that more often than not has a very complicated probability distribution. To learn about our random variable of interest, we need to be able to sample from its complicated (likely unnormalized) probability distribution. And that is why sampling methods such as Metropolis-Hastings are so important to all of science. Important enough that it was named one of the 10 most important algorithms of the 20th century.
Answer: In Bayesian statistics the denominator of the posterior, the "evidence", is an integral that's usually solved by estimation. Bayesian statistics is used to tune the hyper-parameters of neural networks.
In reinforcement learning, the expected total reward over time is an integral that's usually solved by estimation.
Also this: "ELFI is a statistical software package written in Python for performing inference with generative models. The term "likelihood-free inference" refers to a family of inference methods that replace the use of the likelihood function with a data generating simulator function. This is useful when the likelihood function is not computable or otherwise available but it is possible to make simulations of the process."
https://github.com/elfi-dev/elfi
Answer: Sampling is important, because if you can sample, you can evaluate expectations. But that's just to restate the motivation for the first question. So, to provide some examples (supplementing Stephen's answer) of what this implies:
Probabilities
Say you had no way to evaluate a distribution $F$ but could draw samples from it, then you can still answer questions about probabilities under $F$. When $X \sim F$ and $X^{(i)}$ are samples drawn from $F$ and $A$ is some sensible set of interest, $I$ the indicator function.
$\mathbb P(X \in A) = \mathbb E[I(X \in A)] \approx \frac{1}{N} \sum_{i=1}^N I(X^{(i)} \in A)$
So one reason sampling is so important is because it allows us to trade off difficult analytical problems (LHS) for a more tractable computational problems (RHS).
Make $A$ clicked ads, or the set of cat pics and you can get all kinds of useful things doing this.
Gradients
As another example, elsewhere in ML-land [1], sampling is used for gradient descent in the (rough) sense of, when $L$ is a loss function:
$\nabla L = \mathbb E[\nabla l(X)] \approx \frac{1}{N}  \sum_{i=1}^N \nabla l(X^{(i)})$
For some appropriate $l$ (sparing details, see the link). Again this lets us swap analysis for computation, which can be useful when the analysis is intractable.
[1] https://arxiv.org/abs/1506.03431


Unity multitouch cant reach its methods

Question: I followed this tutorial and basically I did everything same. However I can't reach methods inside the testTouch class. Here is TouchInput class:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class touchInput : MonoBehaviour
{
    public LayerMask touchInputMask;
    private List<GameObject> touchList = new List<GameObject>();
    private GameObject[] touchesOld;
    private RaycastHit hit;
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

#if UNITY_EDITOR

//same things for unity editor as be shown in tutorial
#endif
        if (Input.touchCount > 0)
        {
            touchesOld = new GameObject[touchList.Count];
            touchList.CopyTo(touchesOld);
            touchList.Clear();
            foreach (Touch touch in Input.touches)
            {
                Ray ray = GetComponent<Camera>().ScreenPointToRay(touch.position);

                if (Physics.Raycast(ray, out hit, touchInputMask))
                {
                    GameObject recepient = hit.transform.gameObject;
                    touchList.Add(recepient);

                    if (touch.phase == TouchPhase.Began)
                    {
                        recepient.SendMessage("OnTouchDown", hit.point, SendMessageOptions.DontRequireReceiver);
                    }

                    if (touch.phase == TouchPhase.Ended)
                    {
                        recepient.SendMessage("OnTouchUp", hit.point, SendMessageOptions.DontRequireReceiver);
                    }

                    if (touch.phase == TouchPhase.Stationary)
                    {
                        recepient.SendMessage("OnTouchStay", hit.point, SendMessageOptions.DontRequireReceiver);
                    }

                    if (touch.phase == TouchPhase.Canceled)
                    {
                        recepient.SendMessage("OnTouchExit", hit.point, SendMessageOptions.DontRequireReceiver);
                    }
                }
            }
            foreach (GameObject g in touchesOld)
            {
                if (!touchList.Contains(g))
                    g.SendMessage("OnTouchExit", hit.point, SendMessageOptions.DontRequireReceiver);
            }
        }
    }
}

and here is testTouch class:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class testTouch : MonoBehaviour
{

    public Color defaultColor;  //set manually in the editor
    public Color selectedColor;  //set manually in the editor
    public Material mat;

    void Start()
    {
        mat = this.GetComponent<SpriteRenderer>().material;
     // mat.color = selectedColor;
    }

    void OnTouchDown()
    {
        mat.color = selectedColor;
        Debug.Log("hello");
    }

    void OnTouchUp()
    {
        mat.color = defaultColor;
        Debug.Log("hello");
    }

    void OnTouchStay()
    {
        mat.color = selectedColor;
        Debug.Log("hello");
    }

    void OnTouchExit()
    {
        mat.color = defaultColor;
        Debug.Log("hello");
    }

I don't get any errors and I can't reach those Debug.Logs as well. When I click the 2Dcircle nothing happens.

I tried on editor and on my android phone. Both of them is not working.
Answer: 3D Raycasting (Physics.Raycast()) on a 2D colliders does not work.
Replace 2D circle collider with 3D circle collider.
There is no overload of the Raycast method that takes a layerMask as a third argument.
https://docs.unity3d.com/ScriptReference/Physics.Raycast.html
You are mistakenly calling another overload of the Raycast method.
public static bool Raycast(Ray ray, out RaycastHit hitInfo,
float maxDistance = Mathf.Infinity, int layerMask = DefaultRaycastLayers,
QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal);

Unity multitouch cant reach its methods


Required value 'resultCombinationList' missing at $ (Android, Kotlin)

Question: estou tentando consumir uma API, com o seguinte formato JSON:
{ "USDBRL": {
"code": "USD",
"codein": "BRL",
"name": "Dólar Americano/Real Brasileiro",
"high": "5.567",
"low": "5.567",
"varBid": "0.0004",
"pctChange": "0.01",
"bid": "5.5666",
"ask": "5.5675",
"timestamp": "1642541401",
"create_date": "2022-01-18 18:30:01"} }

Pelo que entendi, retorna um objeto, com outro objeto dentro.
Criei minha classe de dados:
data class CoinResultRequest(
val resultCombinationList : Map<String, ConversionCombination>
){
constructor() : this(hashMapOf())}

Que contem o objeto com dados recebidos:
data class ConversionCombination(
@SerializedName("code")
val coinCode: String,

@SerializedName("codein")
val coinCodeIn: String,

@SerializedName("name")
val combinationName: String,

@SerializedName("high")
val high: String,

@SerializedName("low")
val low: String,

@SerializedName("varBid")
val varBid: String,

@SerializedName("pctChange")
val pctChange: String,

@SerializedName("bid")
val bid: String,

@SerializedName("ask")
val ask: String,

@SerializedName("timestamp")
val timestamp: String,

@SerializedName("create_date")
val create_date: String,)

Porém sempre acabo caindo no erro ao fazer a chamada na API,
Required value 'resultCombinationList' missing at $

Answer: É bem simples de transformar um json em Objeto. O que você precisa é espelhar a classe corretamente conforme a estrutura do JSON.
No seu exemplo eu não entendi como você tentou transformar o JSON em objeto. Existe uma biblioteca muito boa chamada Gson, que faz esse trabalho, no nesse link mostra como adicionar a biblioteca ao seu projeto.
Em resumo, faça a seguinte classe:
data class ValorMoeda (
val code: String,
val codein: String,
val name: String,
val high: String,
val low: String,
val varBid: String,
val pctChange: String,
val bid: String,
val ask: String,
val timestamp: String,
val createDate: String)

A Classe Usdbrl tem a mesma estrutura do objeto json. É preciso também criar uma classe com a estrutura do objeto raiz.
data class Conversao(@SerializedName("USDBRL", alternate=["EURBRL", "LIBBRL", "IENBRL"]) val valorMoeda: ValorMoeda)

Caso queira manter o nome da propriedade na classe diferente do nome no JSON, adicione a annotation SerializedName.
Por último transforme a sua string json em um objeto no kotlin
val item = Gson().fromJson(jsonText, Conversao::class.java)

println(item.toString())

Nesse Tutorial tem mais detalhes de como fazer isso.
Comment: Sim, funciona dessa forma, porém dependendo da conversão, o "USDBRL" muda, e com outro nome na minha variável, ele não reconhece o objeto na hora do request com a API, como por exemplo, se fosse "EURBRL".
Comment: Coloque uma anotação sobre a propriedade da sua classe com o nome da propriedade do JSON. @SerializedName("USDBRL") val NomeDaPropriedade: Usdbrl
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).
Comment: Entendi Fábio, o problema está mesmo na parte que esse nome "USDBRL", muda conforme a conversão, se eu converter de euro pra real, o nome na API fica como "EURBRL", e após isso ele não consegue mais converter pra objeto, devido esse nome ser diferente..., ele só consegue converter se a propriedade do meu objeto for igual a propriedade da API.
Comment: Nesse caso pode por quais são os nomes alternativos, por exemplo @SerializedName(value="USDBRL", alternate=["EURBRL", "LIBBRL", "IENBRL"])
Pode ver o link abaixo, é um caso parecido com o seu: https://stackoverflow.com/questions/25707728/multiple-gson-serializedname-per-field?rq=1
Comment: Show, resolvi usando a interface Map mesmo, (chave/valor). Mas muito obrigado por sua atenção!


True false question regarding algebraic closure?

Question: Let $G$ be a finite subgroup of $GL_n(\mathbb{k})$ where $\mathbb{k}$ is an algebraically closed field.
which  of the  following statement  is true/false ?
(A) Every element of $G$ is diagonalizable;
(B) Every element of $G$ is diagonalizable if $\mathbb{k}$ is an algebraic closure of $\mathbb{Q}$;
(C) Every element of $G$ is diagonalizable if $\mathbb{k}$ is an algebraic closure of $\mathbb{F_p}$;
(D) There exists a basis of $\mathbb{k}^n$ with respect to which every element of $G$ is a diagonal matrix.
My attempts  :  option  b) will be True  every element of $G$, the general linear group of square matrices of order $n$ over some algebraic closed field $\mathbb{k}$, is diagnonalizable if $\mathbb{k}$ is an algebraic closure of $\mathbb{Q}$
i don't  know the other option
Any hints/solution  will be apprecaited
thanks u
Comment: Jordan normal form may help
Comment: @RichardMartin  im not getting
Answer: Hint: The group generated by
$$\begin{pmatrix}1 &1 \\ 0 & 1\end{pmatrix}$$
is a finite subgroup of $GL(2,\bar{\mathbb F}_p)$.
Comment: @jasmine c) states that every element of $G$ is diagonalizable. But for $G$ given above, there exists an element that is not diagonalizable, i.e. the generator itself.
Comment: @@Eclipse Im not  getting   option c) and d)  ....  as  i can  discard option 1)    from ur   counter example
Comment: @jasmine This is also a counterexample for c) and d). Here $\mathbb{k}=\bar{\mathbb F}_p$ is the algebraic closure of $\mathbb F_p$.
Comment: still not getting    can u elaborate  more  option c)
Comment: @ Eclispse  sun....  thanks u


non linear differential equation that i cant solve

Question: Can anyone help me to solve this differential equation. Obviously this is not a linear differential equation. So the only way that I know to solve non linear differential equations is by "manipulating" the $y$ variable in order to become a linear differential equation.
But in this case I cant find a way. My main problem is that there is a $dy/dx$ inside and an $\ln$ outside .
\begin{align}
\ y - \ln(\dot y) = x\dot y \
     \end{align}
Comment: Use normal text for text which is not contained in a mathematical expression i.e. $\mbox{use this rarely!}$ , I'll change it this time, and sort out some English grammar. In any case, your attempt was well-directed (and wouldn't work here as I can vouch for as well) but you'll do well to remember what's written here.
Answer: A differential equation of the form $y(x)=xy'+f(y')$ is called a Clairaut equation. To solve Clairaut's equation, one first differentiates with respect to $x$. In this case,
$$y'=xy''+y'+\frac{y''}{y'}=y'+y''\left(x+\frac{1}{y'}\right).$$
Which implies
$$y''\left(x+\frac{1}{y'}\right)=0.$$
In Clairaut's equation, either $y''=0$ or $x+f'(y')=0$.
For $y''=0$,
$$y'=\int0dx=C\implies y=\ln(C)+Cx.$$
For $x+\frac{1}{y'}=0$,
$$y'=-\frac{1}{x}\implies y=\ln\left(-\frac{1}{x}\right)-1.$$
That is,
$$y=\ln\left(-\frac{1}{x}\right)-1\wedge y=\ln(C)+Cx.$$
Answer: This can be solved by maxima using the contrib_ode package.  The equation eq is defined at line (%i2) and solved at line (%i3).  Two solutions are returned as a list at line (%o3).
The solution method is given in the variable method as clairault, indicating it was solved using the Clairaut method.
(%i1) load('contrib_ode)$
(%i2) eq:y-log('diff(y,x))=x*'diff(y,x);
                                      dy      dy
(%o2)                         y - log(--) = x --
                                      dx      dx
(%i3) contrib_ode(eq,y,x);
                                      dy      dy
(%t3)                         y - log(--) = x --
                                      dx      dx

                     first order equation not linear in y'

                                                        %t x + 1
(%o3)   [y = %c x + log(%c), [y - %t x - log(%t) = 0, - -------- = 0]]
                                                           %t
(%i4) method;
(%o4)                              clairault

The two solutions are returned as a list.
The first solution y = %c x + log(%c) has a integration constant %c
The second solution
                             %t x + 1
  [y - %t x - log(%t) = 0, - -------- = 0]]
                                %t

is a parametric solution with parameter %t.  It is a singular solution as it doesn't have an integration constant %c.  The parameter %t can be eliminated with a little algebra: first solve for %t in terms of x (%o7), then substitute this result to obtain (%o8).
(%i6) soln[2][2];
                                  %t x + 1
(%o6)                           - -------- = 0
                                     %t
(%i7) solve(soln[2][2],%t);
                                          1
(%o7)                             [%t = - -]
                                          x
(%i8) subst(%,soln[2][1]);
                                       1
(%o8)                        y - log(- -) + 1 = 0
                                       x

Comment: Your solution does not help readers understand how such problems are solved. In particular, it is not clear how Maxima solves them. Take a look at the other answers: you will see that they offer first some general knowledge about this type of equations, and then proceed to solving the given one. This is what one expects from a good answer, not solutions spit by a computer algebra system.
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Comment: Thanks for the feedback.  I can't improve on the other answers, so I will leave it as is.


How to convert S3ObjectInputStream to Base64 url?

Question: I have a png image file in an AWS S3 bucket. I'm trying to get this image using Java SDK. So far, here is what I have done:
public String encodeBase64URL(BufferedImage imgBuf) throws IOException {
    String base64;

    if (imgBuf == null) {
        base64 = null;
    } else {
        Base64 encoder = new Base64();
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        ImageIO.write(imgBuf, "PNG", out);

        byte[] bytes = out.toByteArray();
        base64 = "data:image/png;base64," + encoder.encode(bytes)
                .toString();
    }

    return base64;
}

public String saveImageToS3(BufferedImage imgBuf, String id) throws IOException {
    AmazonS3 s3 = new AmazonS3Client();

    File file = File.createTempFile(id, ".png");
    file.deleteOnExit();

    ImageIO.write(imgBuf, "png", file);

    s3.putObject(new PutObjectRequest(bucketName, id, file));
    file.delete();

    return bucketName;
}

public String downloadImageFromS3(String id) throws IOException {
    AmazonS3 s3 = new AmazonS3Client();

    S3Object obj = s3.getObject(new GetObjectRequest(bucketName, id));
    BufferedImage imgBuf = ImageIO.read(obj.getObjectContent());

    String base64 = encodeBase64URL(imgBuf);
    return base64;
}

The saveImageToS3 method works exactly as expected. However, the second method returns data:image/png;base64,[B@428d24fa while it should have been a valid Base64.
What am I doing wrong? Please help.
Comment: it worked! thank you very much! this is a stupidity that I'll never repeat!
Comment: In addition to the fix by @Kayaman, you probably want to remove the `ImageIO.read/write`s, and instead just Base64 encode the bytes from the PNG file directly.
Comment: Well, your `encodeBase64URL` method is wrong at least. You seem to be doing a `toString()` on a `byte[]` in it (that's where the `[B@428d24fa` comes from).
Comment: I included the `encodeBase64URL` method. Yes, there is a `toString()` on the `byte[]`. What do you suggest I do?
Comment: Did you try my answer?
Answer: Instead of calling toString() on the resulting byte[] which will result in the very unhelpful [B@428d24fa format, you need to create a new String using the returned bytes:
base64 = "data:image/png;base64," + new String(encoder.encode(bytes), "UTF-8");
Answer: I had some problems with Base64 encoder = new Base64();
So I resolved it by not using encoder and I have replaced "encoder" by Base64.getEncoder() everywhere.
Example:-
if (img == null) {

    base64 = null;

} else {

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    ImageIO.write(img,"PNG",out);

    byte bytes[] = out.toByteArray();

    base64 = new String(Base64.getEncoder().encode(bytes),"UTF-8");
}


Difference between one-tailed and two-tailed testing?

Question: While studying for my stats course, I was trying to understand the difference between one-tailed and two-tailed hypothesis tests. Specifically, why does the one-tailed test reject the null while the two-tailed one does not?
An example:
Comment: Note that you are only rejecting at a specified significance level.  You can still reject both hypothesis by raising the significance level to 10%.  you would also fail to reject both if you lowered the significance level to 1%.
Answer: A two tailed test tests for a difference in either direction. Thus the P value would be the area under the t distribution to the right of t=1.92 PLUS the area under the distribution to the left of t=-1.92. That's twice as much area as the one-tailed test and so the P value is twice as large.
If you use a one tailed test you gain power, but at the potential cost of having to ignore a difference that is in the opposite direction to that hypothesised before the data were obtained. If you got the data before you formalised and recorded the hypothesis you really should use a two tailed test. Similarly, if you would be interested in an effect in either direction you use a two tailed test. In fact, you may wish to use a two-tailed test as your default approach and only use a one-tailed test in the unusual case where an effect can only exist in one direction.
Comment: @probabilityislogic -I agree entirely, except for when one wants the alpha value to reflect the actual long term false positive error rate (i.e. one wants to use the Neyman-Pearson approach). If you use a one-sided test and decide on the direction of change to test for on the basis of the observed effect then you get exactly twice as many false positive results as your alpha level would imply.
Comment: Thank you for your comment, Michael. Here is what I don't understand: how can the area under the curve be twice as large for the two-tailed test? Shouldn't P be the same in both cases, since alpha= 0.05?
Comment: alpha, in your question, is just your cutoff for making a decision about what p-means (reject null or not).  So, it doesn't influence what the value of p is.
Comment: A bit nit-picky but the notion that you need to choose the hypothesis before seeing the data is not necessary.  You can do two one sided tests.  You will always reject the direction not favoured by the data.  Thus it makes sense to go with the one sided test which is favoured by the data.
Comment: It is only the long term error rate for someone who keeps ignoring previous data.  This is not a good way to achieve good long run performance.  the error rate given by significance is over all the data sets we could have observed *once*.
Answer: The area under the curve is not twice as large for a two tailed test: For a two tailed test with critical p= .05, you are testing how often the observed data could be drawn from lower or upper 2.5% of a null distribution (.05 in total). With a 1-tailed test, you are testing how often the data would come from the extreme 5% tail of one (pre-specified) tail.
Partly the answer to your question is one of practice: Most researchers view experiments reporting 1-tailed tests as unlikely to replicate (i.e., they assume the researcher chose this to get their stats to be "significant").
There are however valid use cases. If you know that any result in the reverse direction is impossible under the theory being tested, then, as a previous comment noted, you can specify this ahead of time and conduct a 1-tailed test. Most people, again, would still view this circumspectly.
Answer: The reason for the difference is "hidden" in the test statistic used for each test.  note that for hypothesis testing you choose a statistic (ie a function of the data) to base the test on.  call this statistic $S(D)$.  You also require a rejection region $RR$ such that if the statistic is in the region, we reject the null. now the significance level is calculated as the probability that the statistic is in the rejection region, when the null is true.
Now for the two sided test the test statistic is $S(D)=|t|$ with rejection region $|t|>t_{0}$ where $t_{0}$ is chosen to achieve significance $\alpha$ which is 5% in your case.  for the one sided test the test statistic is $S(D)=t$ and the rejection region is $t>t_{1}$ for suitably chosen $t_{1}$.  now we will always have $Pr(|t|>t_{0}|H_{0})\geq Pr(t>t_{0}|H_{0})$.  so in order to achieve same significance we must have $t_{0}\geq t_{1}$.
This leads to the question: why use different test statistics? The reason is that the alternatives are different and so the power of each test statistic is different.  Specifically the power of each test is reduced (provided we use same significance) if we use the test statistic and rejection region from the other test.


C# - Como criar um contrato de implementação com subclasses a serem implementadas?

Question: Gostaria de criar uma interface (chamei de InterfaceX)
interface InterfaceX
{
...
}

Onde sua futura implementação retornasse a seguinte estrutura:
ClasseDaInterfaceX.ClasseA.Metodo1daClasseA(parametro);
ClasseDaInterfaceX.ClasseA.Metodo2daClasseA(parametro);
ClasseDaInterfaceX.ClasseB.Metodo1daClasseB(parametro);
...

Ou seja: o resultado seria uma classe com duas classes aninhadas.
Porem, que os métodos das classes ClasseA e ClasseB também precisem ser implementados.
Segue o exemplo concreto:
Imagine um sistema que pode usar como "base de dados", qualquer coisa.
Num determinado lugar posso usar SQL Server.
Num outro lugar Firebird.
Num outro posso usar um webservice ou mesmo um arquivos texto!
A implementação dessa DLL dependerá das condições que encontrarei no lugar que usará o sistema.
Então preciso criar uma interface com todas as rotinas, suas entradas e seus retornos, para que as futuras DLLs possam implementa-la, seguindo assim o contrato.
Porem, imagine que esse sistema pode ter centenas de métodos de acesso a base de dados.
Imagine uma interface com 250 métodos, por exemplo. Ao meu ver, é bizarro.
Então eu pensei: será que não existe uma forma de eu organizar essa interface com "subclasses" ou com "subinterfaces".
Seria algo como o exemplo abaixo:
interface IDatabase
{

    interface ClienteDB
    {
        public bool Create(Cliente);
        public Cliente Read();
        public Cliente Update();
        public bool Delete();
    }

    interface FornecedorDB
    {
        public bool Create(Fornecedor);
        public Fornecedor Read();
        public Fornecedor Update();
        public bool Delete();
    }

    ...
}

Com isso, teria um contrato bem definido e relativamente organizado, que forçaria a implementação da DLL seguindo a mesma organização.
E o acesso ao métodos ficaria assim:
Database.Clientes.Create(...);
Existe alguma forma de criar uma interface assim em C#?
Comment: O que você quer, se é que deu para entender, não tem como e nem faz sentido. Se não quer fazer fazer algo bizarro não faça, o problema não é o código, é a ideia errada. Parece que está querendo reinventar o Entity Framework do jeito errado.
Comment: Explica isso melhor, faça um exemplo mais concreto.
Comment: Reforço o comentário do Maniero, sem explicar melhor não tem como ajudar.
Comment: Vou editar a pergunta com um exemplo concreto.
Comment: Eu não sei o quão flexivel o Entity Framework é. Tem gente que ainda usa sistemas em clipper, por exemplo. Será que o EF acessa .dbf, arquivos binários, etc? O entity eu posso usar numa implementação específica da DLL, para mapear as tabelas, etc.
Answer: Bom dia!
Você pode usar um Design pattern conhecido com Rrepository, pois ele abstrai o armazenamento do modelo.
Esse Design pattern tem como objetivo isolar o código de persistência de dados das regras de negócios assim quando for necessário alterar o banco ficará mais simples sendo apenas necessário modificar o repositório.
Exemplo de código:
public interface Repository<T> {
    bool Create(T item);

    T update(T item);

    bool remove(T item);

   T Read(int id);
}

public class ClienteRepository : Repository<Cliente>
{
    public bool Create(Cliente item){
        //DB insert
    }
    public Cliente update(Cliente item) {
        //DB update
    }

    public Cliente update(Cliente item) {
        //DB delete
    }

    public Cliente update(Cliente item) {
        //DB delete
    }

    public Cliente Read(int id){
        //DB Select
    }
}

public class Cliente
{
    public int Id { get; set; }
    public string Nome { get; set; }
}

Saiba mais sobre o Design pattern nos links abaixo:

https://medium.com/falafel-software/implement-step-by-step-generic-repository-pattern-in-c-3422b6da43fd
https://martinfowler.com/eaaCatalog/repository.html
http://www.macoratti.net/11/10/net_pr1.htm
https://docs.microsoft.com/pt-br/aspnet/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application
Comment: Obrigado!
Vou estudar esse pattern.


OpenQA.Selenium.NoSuchElementException was unhandled by user code in c# selenium

Question: I want to wait my selenium programe for max 30 seconds (GlobalVar.timetomaximumwait) with explicit wait.But when ever its unable to locate the element its pausing at wait.until(...) line and displaying OpenQA.Selenium.NoSuchElementException was unhandled by user code
If i press continue or press F10 its trying again to find the element and continuing the same for my defined time spam.
Not able to understand why the programme paused and the error message is coming in between.
I am using VS2010, c#, selenium 2.45,Ie 9
Any kind of help is much appreciated .
 public string SetValueInTextBox(string InputData, string xPathVal)
        {
            try
            {
                WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(GlobalVar.timetomaximumwait));
                 wait.Until<IWebElement>((d) =>
                {
                    return d.FindElement(By.XPath(xPathVal));
                });
                 IWebElement TargetElement = driver.FindElement(By.XPath(xPathVal));

               // IWebElement TargetElement = driver.FindElement(By.XPath(xPathVal));

                elementHighlight(TargetElement);
                TargetElement.Clear();
                TargetElement.SendKeys(InputData);

                //driver.FindElement(By.XPath(xPathVal)).SendKeys(InputData);

                return "Pass";
            }
            catch (Exception e)
            {
                return "Fail";
            }
            finally
            {
               // string SSName = "temp.jpg";
                TakeScreenshot("SetValueInTextBox");

            }
        }

Answer: The problem lies here:
wait.Until<IWebElement>((d) =>
{
    return d.FindElement(By.XPath(xPathVal));
});

You need to handle the exception that gets thrown when the element is not found.
wait.Until<IWebElement>((d) =>
{
    try
    {
        return d.FindElement(By.XPath(xPathVal));
    }
    catch(NoSuchElementException e)
    {
        return null;
    }
});

I would suggest adding in some logging into the catch block, so you know every time the driver fails to find the element.
Comment: Thanks @aholt for your time and support.let me check the same in emulator .


Why is `do{} while(0);` so fast?

Question: I'v tried the following 3 for loops:
#define loop 1000000000
NSDate *start;
NSDate *end;

// 1: empty for loop
start = [NSDate date];
for (NSInteger i = 0; i < loop; i++) {
}
end = [NSDate date];
NSLog(@"time interval: %f", [end timeIntervalSince1970] - [start timeIntervalSince1970]);

// 2: do-while for loop
start = [NSDate date];
for (NSInteger i = 0; i < loop; i++) {
    do {
    } while (0);
}
end = [NSDate date];
NSLog(@"time interval: %f", [end timeIntervalSince1970] - [start timeIntervalSince1970]);

// 3: @try-@finally for loop
start = [NSDate date];
for (NSInteger i = 0; i < loop; i++) {
    @try {
    }
    @finally {
    }
}
end = [NSDate date];
NSLog(@"time interval: %f", [end timeIntervalSince1970] - [start timeIntervalSince1970]);

I test those three for loops about 1 billion on my '07 Macbook Pro. And I recorded the timestamp to calculate the execution duration. Here are the results:
1: empty for loop => 2.947088 sec
2: do-while for loop => 2.581905 sec
3: @try-@finally for loop => 4.216685 sec

What? do-while for loop is faster than empty for loop!
Why?

UPDATED
I add some additional code (j++) in the for loop:
NSInteger j;
#define loop 1000000000

// 1: empty for loop
j = 0
for (NSInteger i = 0; i < loop; i++) {
    j++;
}

// 2: do-while for loop
j = 0;
for (NSInteger i = 0; i < loop; i++) {
    do {
        j++;
    } while (0);
}

// 3: @try-@finally for loop
j = 0;
for (NSInteger i = 0; i < loop; i++) {
    @try {
        j++;
    }
    @finally {
    }
}

Output:
1: empty for loop => 2.590103 sec
2: do-while for loop => 2.138528 sec
3: @try-@finally for loop => 3.983589 sec

Those 3 are much faster than previous code, and do-while for loop is still fastest. Weird!
Comment: @李岡諭, These results are entirely compiler dependent. You may get different results if you try on a different compiler with different optimization mechanisms.
Comment: Measuring performance of optimized micro-benchmark code is difficult. For example, if you are testing many iterations of very small loops then the precise alignment of the loop's instructions becomes significant.
Comment: Do you try to look at generated assembly? It can answer your question.
Comment: Interesting, i wanna know why, too
Comment: On my OS, NSInteger is just `long` type (`typedef long NSInteger;`).
Comment: YES, @try-@finally is Objective-C. But the first two is pure C code.
Comment: Add the whole test code please
Comment: @ShafikYaghmour `NSInteger` **is** C. `@try {} @finally {}` isn't.
Comment: @ShafikYaghmour It's a typedef in the Foundation framework.
Comment: @ShafikYaghmour We can learn every day :)
Answer: It's not.  The output depends a lot on the particular compiler being used as well as the optimization settings in effect.  Any compiler worth its salt will optimize away both of the loops.  When I compile the following sample code, both Clang and GCC completely remove the loops at any non-zero optimization level (i.e. -O1 and above):
#include <stdio.h>
#include <stdint.h>
#include <sys/time.h>

#define loop 1000000000

int main(void)
{
  struct timeval t1, t2, t3;
  gettimeofday(&t1, NULL);

  for (long i = 0; i < loop; i++) {
  }

  gettimeofday(&t2, NULL);

  for (long i = 0; i < loop; i++) {
    do {
    } while (0);
  }

  gettimeofday(&t3, NULL);

  int64_t d1 = (t2.tv_sec - t1.tv_sec) * 1000000ll + (t2.tv_usec - t1.tv_usec);
  int64_t d2 = (t3.tv_sec - t2.tv_sec) * 1000000ll + (t3.tv_usec - t2.tv_usec);

  printf("Empty for loop:    %lld.%06d\n", d1 / 1000000, (int)(d1 % 1000000));
  printf("do-while for loop: %lld.%06d\n", d2 / 1000000, (int)(d2 % 1000000));

  return 0;
}

At optimization level 0 (-O0, unoptimized code), both Clang and GCC produce code where either both loops run with the same speed (to within experimental error), or the do-while loop runs slightly slower due to the extra unoptimized code.  My results on a 64-bit Mac, using Clang 4.1 and GCC 4.2.1:
Clang, 32-bit, -O0:
Empty for loop:    2.632714
do-while for loop: 2.633194

Clang, 64-bit, -O0:
Empty for loop:    2.632078
do-while for loop: 2.632046

Clang, 32-bit, -O1:
Empty for loop:    0.000000
do-while for loop: 0.000000

Clang, 64-bit, -O1:
Empty for loop:    0.000000
do-while for loop: 0.000000

GCC, 32-bit, -O0:
Empty for loop:    2.633221
do-while for loop: 2.633754

GCC, 64-bit, -O0:
Empty for loop:    2.778056
do-while for loop: 2.983421  (!!!)

GCC, 32-bit, -O1:
Empty for loop:    0.000001
do-while for loop: 0.000000

GCC, 64-bit, -O1:
Empty for loop:    0.000000
do-while for loop: 0.000000

Comment: @李岡諭: Turn on optimization on your compiler.  If you enable optimizations, I would be **very** surprised if you got different results.  There's almost no point in measuring performance when optimizations aren't enabled.
Comment: Thanks. I tested your code. And the results are: => `Empty for loop:    3.120945`; => `do-while for loop: 2.164982`.
Running on Mac OS 10.9, '07 Macbook Pro, Xcode 5 (iOS Simulator mode). But I think you are right. :)

Why is `do{} while(0);` so fast?