Add a relationship without data already in the database

Question: It appears that I can't add a relationship unless there is already some data in some Entities that obey that relationship. Is this correct? I want to be able to set up my relationships and Labels first and then populate with data and have the data just use the relationships.
I am using:
MATCH (from:this_label),(to:that_label)
WHERE from.id = to.uuid
CREATE (from)-[:hasARelationship]->(to);

Basically, I want to be able to define a bunch of relationships on nodes of a certain label, even if those node-type do not yet exist. And then when some data of those nodes comes into the database it will hook up the relationships automatically.
Comment: What does it mean for Entities to obey relationships? Does "node-type" mean a node with a label?
Comment: It sounds like you want to create a constraint on a label, enforcing that nodes with that label have a relationship of a certain type to a particular node (or any node with a particular label). Is this what you want?
Comment: @jjaderberg yes, that sounds about right. I haven't heard about constraints  on labels. thanks
Comment: Constraints on relationships / cardinalities are on the roadmap but not implemented yet.
Answer: If I understand you correctly, you want to use MERGE instead of MATCH.
MERGE (from:this_label) -[:hasARelationship]-> (to:that_label) WHERE from.id = to.uuid

If you are trying to create relationships without nodes, I guess that is not even possible in NEO4J. Infact, it wouldn't be possible in any graph in general.
Comment: So?? Sorry, but what exactly do you want to accomplish?
Comment: I want to be able to set up relationships first, and then when Nodes are created that fit the relationship they are connected. At the moment, I can't
Comment: thanks , but why would it not be possible? It is basically just a relationship schema - if you see a Node with this label and this attributes, then apply this relationship.. can't something like that be done?
Answer: It does not make sense to pre-populate your DB with relationships that connect to dummy nodes. Among the many reasons are these:

You would not be able to make any meaningful queries involving such relationships
Trying to fill in the dummy nodes later on with actual data may be a complex endeavor
It is very easy to created relationships right when they are needed. neo4j is a "schemaless" DB (except when you define uniqueness constraints, as @jjaderberg mentions). You can create a relationship of any type connecting nodes with any labels (or no labels) at any time. To keep things organized, you may choose to write your DB client code and Cypher queries to conform to your own conceptual "schema", but neo4j has no such a requirement.
Comment: thanks, so how does one set a schema to force nodes of a certain type to have a relationship with other nodes?
Comment: neo4j is a "schemaless" DB. There is no preset schema. You can create a relationship of any type connecting nodes with any labels (or no labels) at any time. You may choose to impose your own "schema" by writing your code as if there was one, but neo4j does not impose such a requirement.
Answer: It may be helpful to distinguish between the responsibilities of enforcing a constraint and fulfilling a constraint.
Neo4j allows for indices and constraints associated with labels. Indices and constraints created for a label are used to index and constrain the nodes that have that label. As of version 2.2.5, there is only one type of constraint: a uniqueness constraint for a single property. There have been talk about adding constraints for combinations of properties, and for relationships, but I don't know the status of these conversations.
The Neo4j schema constraints enforce something, but they will not fulfill, in the sense of changing your operations on the database to satisfy the constraint. If there were constraints enforcing that a node with label A may only be created if it has a relationship of type R to a node with label B, they would block your operation if it did not satisfy the constraint, but they would not satisfy it for you.
The best way to achieve this is a) to satisfy this requirement in your client application, or b) to create an extension for Neo4j. For an extension example, consider neo4j-uuid by Stefan Armbruster. It listens to transactions (using what's called a TransactionEventListener) and makes sure that any node that is created in the database has a UUID. This extension satisfies what could only be enforced by a corresponding Neo4j schema constraint (there are other differences, e.g., the constraint would be limited to the scope of a label).
A way to achieve your intention could be to either create an extension which listens to what you write to the database and satisfies your constraint, altering your operations if necessary; or, one which provides an invocation target in the server (a RESTful endpoint) that you can invoke whenever you want to create a node with a particular label. The extension would then create the node and other elements necessary to fulfill your schema. A downside to the former could be the overhead of listening to all your operations, a downside to the latter could be that it breaks your flow of interaction with the database to introduce a separate type of invocation (e.g., if you normally execute cypher statements and have to pause to issue a separate POST request and interpret the response before continuing).


How should I answer this interview question?

Question: I found this interview question for a company I'm interested in joining soon.

Consider that you have an API that is called from the UI to display some data using pagination. How would you change the API call if for a non UI client you need to retrieve all data at once without pagination (petabytes of data)?

How would you answer this?
Comment: _"How would you answer this?"_ - only by laughing at whoever is asking this, because with _petabytes_ of data, this question does not have any connection to reality IMHO.
Answer: Preface
Firstly, this is not a question for StackOverflow.  This question is better suited for software engineering Stack Exchange. Secondly, my answer would be "I don't recommend sending petabytes of data from and HTTP request".  However I will attempt to give the answer.
Chunked Transfer Encoding
The only acceptable answer to this question is to enable chunking.  Essentially chunking allows you to retrieve an unlimited amount of data through and HTTP call by dividing the stream into non-overlapping chunks.  The chunks are received independently of each other and the connection is managed appropriately.  To enable this in an http reuqest/response you can utilize the following header
Transfer-Encoding: chunked

There are a variety of optional trailing headers that can be supplied
chunked-body   = *chunk
                 last-chunk
                 trailer-part
                 CRLF

chunk          = chunk-size [ chunk-ext ] CRLF
                 chunk-data CRLF
chunk-size     = 1*HEXDIG
last-chunk     = 1*("0") [ chunk-ext ] CRLF

chunk-data     = 1*OCTET ; a sequence of chunk-size octets

Chunking became part of the standard in HTTP1.1 so this will be ineffective on HTTP1.0
However, if the issue is the size of the response you would need to implement chunking server side not as part of the client.  I feel as though this is a misunderstanding of chunking on the interviewers part ( because I can't imagine what else they would be referring to ).


Invalid property , unknown feature 'visibility' in boost build/b2/bjam

Question: I want to pass the GCC visibility flag -fvisibility=hidden to b2 using:
b2 (...) linkflags=-fvisibility=hidden (...)
but I get this error:
/usr/share/boost-build/src/build/property.jam:358: in validate1 from module property
error: Invalid property '<visibility>hidden': unknown feature 'visibility'.
/usr/share/boost-build/src/build/property.jam:367: in property.validate from module property
/usr/share/boost-build/src/build/property-set.jam:493: in property-set.create-with-validation from module property-set

How can I solve this ?
I am using b2 in version Boost.Build 2018.02-git
Answer: This is because there is a parsing problem in the b2 version that you are using: the parsing interprets the equal character = from the flag value as the setting of a feature (like variant=release).
Use a more recent version of b2. For instance the problem is not present in b2 in version B2 4.6-git from Boost 1.77.


Issues with creating class with image file path as argument

Question: I am attempting to make a class which can take a string with an image path and set it as this objects image. I have done it manually before, i.e. creating a new class with an extends main class, but this will get out of hand quickly. Here is the code I have so far:
import java.awt.Image;
import java.net.URL;
import javax.swing.ImageIcon;

public class Sprite {
private int x;
    private int y;
    private ImageIcon ia;
    private URL loc;
    private Image image;

public Sprite(int x, int y) {
    this.x = x;
    this.y = y;
}

public Sprite(int x, int y, String imgLoc) {
    this.x = x;
    this.y = y;

    URL loc = this.getClass().getResource(imgLoc); //problem area is here
    ia = new ImageIcon(loc); //and here
    image = ia.getImage();
    this.setImage(image);
}

When I had a child class, It worked in the child classI put in something like this:
public class Dude extends Sprite {
   public Dude (intx, int y) {
      super(x, y);

      URL loc = this.getClass().getResource("images/dude.png");
      ia = new ImageIcon(loc);
      image = ia.getImage();
      this.setImage(image);
   }
}

But when I try to use the second Sprite Constructor, it gave me an
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at javax.swing.ImageIcon.<init>(ImageIcon.java:217)
    at Sprite.<init>(Sprite.java:26)

Any suggestions on how to fix this?
Comment: Your resource does not exist.
Comment: What string argument did you use for the second Sprite constructor? I know it sounds stupid but is the file path correct (like slashes, missing extension and so on)?
Comment: And the question is?
Comment: Whoops, forgot to include the error I ran into it. Should be fixed now.
Comment: Just to be sure, do getClass().getClassLoader().getResource(res) instead, i had problems in the past dont remember why
Comment: I tried it, and it did not seem to help.
Comment: Looks like that solved the problem. Had to comb through my code again.
Answer: Okay, I have found the solution. It turns out that I had slightly got the image path wrong, along the lines of:
//Image is called: "images/dude2.png"
//But I called it: "images/dude.png"

I guess the lesson to learn from this is to make absolutely sure everything is called correctly.
Comment: The `NullPointerException` can be avoided by checking for `null` as well.  See also https://stackoverflow.com/a/15581779/3196753.


How to check if the expected data is sent by a post or put request?

Question: I am using requests-mock and I am trying to figure out how to assert that the put request has been called correctly:

def funtion_to_be_tested():
    requests.put(
        headers={'X-API-Key': 'api_key'},
        url=url,
        params={'param1': 'foo'},
        data='This is the data'
    )

def test_upload(requests_mock):
    url = 'http://example.com/upload'
    requests_mock.put(url, text='ok')
    funtion_to_be_tested()
    # how to check that `data` was `This is the data` and that `headers` contained the `X-API-Key`?

Edit: I refactored out the code to be tested to a function called funtion_to_be_tested
Answer: The standard way to do this is run through your function and then make assertions on the request_history:
Altering the example because it always takes me a while to make pytest work correctly, but it will work basically the same way:
import requests
import requests_mock

def funtion_to_be_tested():
    requests.put(
        headers={'X-API-Key': 'api_key'},
        url=url,
        params={'param1': 'foo'},
        data='This is the data'
    )

with requests_mock.mock() as m:
    url = 'http://example.com/upload'
    m.put(url, text='ok')
    funtion_to_be_tested()

    assert m.last_request.headers['X-API-Key'] == 'api_key'
    assert m.last_request.text == 'This is the data'

Comment: I solved it similarly but used the Matcher object directly, e.g.
`matcher = m.put(url, text='ok'); assert matcher.last_request.text == ...`
this was so I could check individual mocked endpoints rather than the full history. not sure your thoughts on that
Answer: If you just want check the method being used, you can check that by verifying the sent request.
def test_upload(requests_mock: Any):
    url = 'http://example.com/upload'
    requests_mock.put(url, text='ok')
    r = requests.put(
        headers={'X-API-Key': 'api_key'},
        url=url,
        params={'param1': 'foo'},
        data='This is the data'
    )
    print(r.request.method)  # Prints PUT/POST
    print(r.request.headers) # Prints your headers sent
    print(r.request.body)    # Prints your data sent

I have included the request headers/body in the code above in case you want to check the other parameters as well.
Comment: Thank you for your answer. My question was probably not clear enough what I want to test. I what to test if the API was called with the correct data. The handling of the request is done within the code to be tested and I have no access to the return value of `request.put`.


can't make sense of scipy.lognorm

Question: I have been trying to work with random variables in Python and more denerally.  My model works with large numbers and lohnormal distributions, but it is very hard to get a clear answer anywhere on the intuition of the parameters as various software packages see it, which stems from the fact that the mathematical explanations are equally unclear about what the parameters mean, or are even called.
My code Python Scipy code looks like this:
<code>rv = lognorm(s=1., scale=100000., loc=0)
x = numpy.arange(1, 1000000, 1000)
plt.plot(x, rv.pdf(x))
plt.show()
</code>
When s=1 you get a graph that looks like a textbook lognormal dostribution, with e believable shape that would have the right means, mode, etc.
What I find is that as I INCREASE s, the plot gets tighter to the left, and does not flatten  out as suggested by any text.  By the time s=3 or 4, the graph looks like a spike at zero, and zero everywhere else.
s is the standard deviation of the underlying random variable X which is a normal with mean equal to ln(100000) and standard deviation equal to whatit should be to achieve the desired result.  In my instance, a 10% random change (100,000 units) is what I want to model.
After hours of thinking, tinkering, and experimenting, I finally cut through the clutter and figured out the answer, which - having re-written the question - I will now give.
The tricky bit here is pulling back from the real world into the fictitious normally distributed RV, $X$, which is generating the lognormal $Y=e^x$.  That underlying RV is normally distributed with a mean of $ln(1,000,000)$ which is 12.816.  The trick is to go mentally back 'into the real world' and ask yourself "what would be the number if a one stnadrad deviation event occurred?"  In my  case that would be a 10% range, or 1,100,000 (or 900,000).
But the natural log of 1,100,000 is 12.919.  This is only about.10 difference, so the underlying RV has mean 12.816 and stdev .10.  Since stdev is what goes into the lognorm formula (often called 'shape'), it explains (1) how to get the thing to work and (2) why the 'shape' factor is usually so small (<2): when dealing with variations in the real world of reasonable sizes (plus or minus 50% standard deviations or less), the underlying RV $X$ has a very, very tight variance.
Hope this is helpful to others.  I sure spent a lot of time and never found a good resource or answer.
Comment: Actually, as noticed by @Sycorax, the documentation says it all. I cannot think of better answer then copying and pasting it. It gives you the formulas and explanation. What exactly is unclear for you? Did you read the link carefully?
Comment: Read the "Notes" section of the documentation. https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.lognorm.html
Comment: I did, and it didn't help at all.  Perhaps my problem is I am dealing with big numbers, though that shouldn't change a ting.  But to put it in perspective, I have molecules that may be 1 million daltons in size.  I have reason to believe the lognormal is right. In "real space" the SD is +/-100,000 daltons or 1%.  But trying to plot anthing like that gives flat lines, spikes, etc.  Were we in base 10, the underlying would be distribted normally with mu = 6 and sigma - =5.  But anything thnat yties to do that wityh Scipy gives odd results.
Comment: See https://stats.stackexchange.com/search?page=2&tab=Relevance&q=lognormal%20standard%20deviation for many more relevant posts on our site.
Comment: Thanks.  I can't think of any other instance where a topic or idea has so many different ways of being explained, and so many different uses of notation.
Answer: As you increase $\sigma$ you get both a heavier tail and a greater spread, but the way that looks in the plot may not correspond to your intuition.
(I doubt there's anything wrong with the function you're using. What you describe sounds quite consistent with what you should be seeing.)
For a fixed $\mu$ (I suggest considering $\mu=0$), the height at the mode of a lognormal is minimized at $\sigma=1$. The peak is higher both for larger and smaller $\sigma$.
You may find it instructive to plot the log-density against log(x); this makes comparisons of relative height and spread/heavy tailedness easier.

When s=1 you get a graph that looks like a textbook lognormal dostribution

... because they don't tend to draw the ones with really large $\sigma$, and if you don't work on the log-scale it can be hard to see much detail.
Comment: After much experimentation and thinking, I figured it out satisfactorily.  I think the documentation is very poor on this, as  are most explanations mathematically.  Imagine I am a geologist, and want to measure sreamline position (and changes) relative to some datum point that is 500 meters away, and I report everything in mm. I, perhaps, think a lognormal models this, with mu (in the real world) of zero, but stdev of 1% (5 meters).  The challenge is going back into the underling normal RV that generates the LN.  np.log(500000)
Comment: The challenge is going back into the underling normal RV that generates the LN, which has a mean of  np.log(500000) or 13.12.  Then, imagine what a one-sigma deviation would be, say, to 505,000mm.  the ln of that is 13.13. So, my 'true' normal mas a mean of 13.13, and sigma of .10.  That is why the scale number is so often close to 1 or less

can't make sense of scipy.lognorm


branch cuts of log function

Question: Suppose that I am going to take the branch cut of log as below

How would I define the range of the angles?
Generally, I know that I can take branch cuts to be any line connecting $0$ and $\infty$. In the case of the branch cut being the negative $x$ axis, I just take the range of the angle to be $(-\pi,\pi)$, but how would I possibly determine the range of the angle here?
Comment: Is this cut a straight line?
Comment: No, it is an arbitrary line.
Answer: With a curved branch cut, the allowed values of the argument (i.e. the imaginary part of $\log(z)$) will not be a fixed interval.  If $z$ is in the first quadrant and below the cut (i.e. can be connected to a point on the positive real axis by a path in the first quadrant that avoids the cut), the argument will be in $[0, \pi/2)$, if it is above the cut it will be in $[-2\pi, -3\pi/2)$.
Comment: In general, you choose some starting point $p_0$ not on the cut and choose the value for $\log(p_0)$.  For  any other point $p$ not on the cut, take a pieewise smooth curve $\gamma$ going from $p_0$ to $p$ that doesn't intersect the cut, and let $$\log(p) = \log(p_0) + \int_\gamma \dfrac{dz}{z}$$
Comment: How to get a more general result from this, can you give me any reference?
Comment: For example, what if my cut is a curve going through all of the four quadrants?
Comment: Thank you. Do you have any reference on this? I went through Stein, Simon and Gammelin, they seemed not have any detailed elaboration on this.
Comment: You might look at Marsden and Hoffman, "Basic Complex Analysis", section 2.2.
Comment: Thank you very much for being so patient and helpful
Comment: @RobertIsrael could you please explain why $z=1$ is not a branch point of $\log(z)$. The thing I can think of is that one can't factor $i\theta$ term from $\log(1+re^{i\theta})$, like in the case of  $\log(re^{i\theta})$. However, this is not very rigorous.
Comment: There's nothing special about $z=1$ from the point of view of $\log$.  The derivative $1/z$ is analytic there.
Comment: @RobertIsrael as far as I remember, the complex log $\log(f(z))$  can be defined on some domain where $f(z)\ne 0$, only if $\int_{\gamma}\frac{f'(\xi)}{f(\xi)}d\xi=0$ for any closed curve $\gamma$. So for $\log(z)$, $f(z)$ is just $z$ and the above integral is zero when choosing a closed loop $\gamma$ encircling the point $z=1$, and the argument of the log is nonzero too. Does this make seance?
Answer: Suppose your curve is given in inverse polar form $\theta(r)$.
Then, for any $z$, we can define $\log_r z$ to have an imaginary part $y$: $$\theta(|z|) +2 \pi n<y\le \theta(|z|) +2 \pi (n+1)$$ for some $n\in\mathbb Z$.

branch cuts of log function


Cannot validate argument on parameter 'Container'. The argument is null or empty

Question: I'm working on triggering an on-demand backup for my machines. But while running ps script it shows the below error.
"Cannot validate argument on parameter 'Container'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again".
$vault = Get-AzRecoveryServicesVault -ResourceGroupName "xxxx" -Name "xxxx"
Set-AzRecoveryServicesVaultContext -Vault $vault
$backupcontainer = Get-AzRecoveryServicesBackupContainer -ContainerType "AzureVM" -FriendlyName "testvm"
$item = Get-AzRecoveryServicesBackupItem -Container $backupcontainer -WorkloadType "AzureVM"

the above code was working fine couple of months ago. I have tried using different vm names in -FriendlyName but no luck.
Please suggest
Comment: The above script should add existing vm to the recovery vault? or it will only trigger backup for existing vms?
Answer: The PowerShell response is that Get-AzRecoveryServicesBackupContainer do not respond a valid container object but $null.
Why I don't know.
But you should test the return values of the CmdLets you call before using them in other CmdLets.
Comment: I did try to run the CmdLets "Get-AzRecoveryServicesBackupContainer" and its not returning any value.
Comment: That's why `$backupcontainer` is `$null`, you've got your answer.
Comment: I am not sure why is it showing null, had provided -FriendlyName with existing vm name. Can you please suggest what mistake i am doing?
Comment: Sorry, I'am not in your organisation, you can try `-verbose` to understant.
Comment: Do we need to add vm to recovery vault prior to running script? or will script be adding the vm?


Remover registros antigos MySQL automaticamente

Question: Tenho uma tabela que armazena logs de um sistema. Quero algum método de excluir automaticamente os registros com mais de 60 dias. Tem como fazer isso?
Comment: Quero fazer diretamente em SQL
Comment: Deseja fazer programaticamente através de uma linguagem ou em SQL?
Answer: Você pode criar um EVENT com seu intervalor CURRENT_TIMESTAMP + INTERVAL 1 DAY
Abaixo seguem alguns exemplos de criação de "events" no MySQL:
CREATE EVENT `Dropar tabela t`
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 5 DAY
DO DROP TABLE t;

Este evento fará com que o MySQL drope a tabela "t" 5 dias a contar do momento da criação do evento.
CREATE EVENT O_evento_principal
ON SCHEDULE AT TIMESTAMP '2009-03-10 12:00:00'
DO DROP TABLE t;

Este evento fara com que o MySQL drope a tabela "t" no dia 10 de março de 2009 às 12:00h.

ATENÇÃO:   É importante que, quando um evento é criado com a instrução
  "EVERY" diante do período, a tarefa será repetida SEMPRE no decorrer
  de um novo ciclo.

Uma instrução "EVERY YEAR/MONTH/WEEK/DAY/HOUR/MINUTE/SECOND" resulta em uma execução continua dentro de um ciclo ANUAL/MENSAL/SEMANAL/DIÁRIO/HORÀRIO/MINUTOS/SEGUNDOS.
Por exemplo:
CREATE EVENT e
ON SCHEDULE EVERY 1 YEAR
DO DROP TABLE t;

Este evento faz com que o MySQL execute um "drop" na tabela "t" a cada ano, considerando como tempo "zero" o momento da criação do evento.
No seu caso você poderia fazer
CREATE EVENT `Delete tabela t`
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 DAY
Delete FROM tabela
WHERE TIMESTAMPDIFF(DAY, SuaData + INTERVAL TIMESTAMPDIFF(MONTH,  SuaData , current_date) MONTH , current_date) >= 60;

Comment: É exatamente o que preciso, muito obrigada


Linux file copy with ETA?

Question: I'm copying a large amount of files between disks.  There's approximately 16 GB of data.
I'd like to see progress information, and even an estimated time of completion from the command line.
Any advice?
Answer: Use rsync --human-readable --progress.
For single files and block devices there's also pv.  And if you genuinely need an accurate progress bar, try using tar with pv — something like this:
source=/the/source/directory
target=/the/target/directory
size=$(du -sx "$source")
cd "$source"
find . xdev -depth -not -path ./lost+found -print0 \
    | tar --create --atime-preserve=system --null --files-from=- \
          --format=posix --no-recursion --sparse \
    | pv --size ${size}k \
    | { cd "$target"; \
        tar --extract --overwrite --preserve-permissions --sparse; }

Be warned, however, that GNU tar does not yet support ACLs or extended attributes, so if you are copying filesystems mounted with the "acl" or "xattrs" options, you need to use rsync (with the "--acls" and "--xattrs" options).  Personally, I use:
rsync --archive --inplace --hard-links --acls --xattrs --devices --specials \
    --one-file-system --8-bit-output --human-readable --progress /source /target

Also look into whether you want to use the --delete and/or --numeric-ids options.
Comment: Was posting that. However, be aware that it doesn't provide a reliable "progress over total copy time".

However, rsync brings many benefits to this kind of stuff.
Answer: Instead of dd I would suggest pv, e.g.:
% tar -cf - INPUT | pv -rbe -s SIZE | tar -xf - -C DEST

Answer: Have you tried rsync -P? If you're using dd, e.g. tar -cf - src | dd | (cd dest; tar -xf -) you should be able to use Ctrl-T (SIGINFO) to see your progress.
Comment: Linux doesn't even have `SIGINFO`.
Comment: When copying with `dd` I send SIGUSR1 to `dd` instead to cause it to print the statistics. A simple `killall -USR1 dd` will do the job. (Which works on Linux, even if, as Teddy points out, Ctrl+T doesn't work.)

Linux file copy with ETA?


VS 2010 - easy way to copy full type name of a class/interface?

Question: Is there a way to copy the full type name of a class/interface/etc. in Visual Studio to the clipboard?  In particular, I need them for Castle Windsor configuration and would love to figure out how to do this effortlessly.  (Example: highlight IInterface in the code editor and end up with My.Full.Namespace.Is.Here.IInterface on the clipboard.)
VS puts the full type name in a read-only combobox in the upper left (which is utterly useless for copying purposes); does anyone know a way?
(I have ReSharper, if there's a way to do it using that.)
Comment: For those looking for an answer for VS2012 and above (macro support has been dropped) look here: http://stackoverflow.com/questions/6948428/vs-add-on-to-copy-full-type-name-of-identifier-under-the-cursor-into-clipboard/26364337#26364337
Answer: Here's a macro which does which should get you going. The error handling is abysmal but I couldn't muster more, I absolutely hate VB :)
Also note that it only captures a class type name or interface type name, you can run it where ever you want while your cursor is inside a class or interface definition. It will capture the name of the class/interface scope.
It runs the Clipboard call in a thread, because it's a Windows Forms component and they need to run in a STAThread.
It copies the full typename to the clipboard.
<code>Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports EnvDTE90a
Imports EnvDTE100
Imports System.Diagnostics

Public Module SkurmedelMacros

    Public Sub SetClipboard(ByVal x As Object)
        System.Windows.Forms.Clipboard.SetText(CStr(x), System.Windows.Forms.TextDataFormat.Text)
    End Sub

    Public Sub GetTypeName()
        Dim solution As Solution = DTE.Solution
        Dim activePoint As TextPoint = CType(DTE.ActiveDocument.Selection, TextSelection).ActivePoint
        Dim codeElem As CodeElement = _
            DTE.ActiveDocument.ProjectItem.FileCodeModel.CodeElementFromPoint(activePoint, vsCMElement.vsCMElementClass)
        If codeElem Is Nothing Then
            codeElem = DTE.ActiveDocument.ProjectItem.FileCodeModel.CodeElementFromPoint(activePoint, vsCMElement.vsCMElementInterface)
        End If

        Dim ClipBoardThread As System.Threading.Thread = New System.Threading.Thread(AddressOf SetClipboard)
        With ClipBoardThread
            .ApartmentState = System.Threading.ApartmentState.STA
            .IsBackground = True
            .Start(codeElem.FullName)
            .Join()
        End With
        ClipBoardThread = Nothing

    End Sub

End Module
</code>
Comment: I tried this, and the first call to get DTE.Solution fails with RPC_E_SYS_CALL_FAILED.
Comment: @Joe: Woot... what version of VS you got?
Comment: 2010.  I'm finding that the code here works fairly consistently for getting the class/interface... http://www.mztools.com/articles/2006/MZ2006009.aspx
Comment: Using that code, and using Clipboard.SetDataObject(CStr(x), True) in the external thread, I seem to have this working.  I'm accepting this though since it put me on the right track.


Dependence of factors in lmer - combined vs separate analyses

Question: I'm doing an analysis of how error committement in a particular task influences some numerical reports. I use linear mixed effects models from lmer package. I can formulate a model such as:
lmer(report ~ error + (1+error|id), data)

However, there are actually two kinds of errors which can influence participant's reports: error from current trial (currerror) but also error from previous trial (preverror). I'd like to see how both kinds of these errors influence participants reports. Crucially, it seems that both errors are not independent - i.e. committement of error in previous trial is related to higher chance of committing error also in current trial. In other words, my dependent variable (report) is loaded by two corelated factors. It seems to me that I have two options:
1) First is to make a model with two factors (possibly, although not necessarily, with interaction term), like:
lmer(report ~ currerror * preverror + (1 + currerror * preverror|id), data)

2) Second option is to run two separate analyses for two kinds of errors:
lmer(report ~ currerror + (1+currerror|id), data)
lmer(report ~ preverror + (1+preverror|id), data)

My question is: is this lack of independence a problem for mixed models? Should I then choose second option (two separate models) over the first? And COULD I do it given that this second option is also somewhat more justified by my experimental plan, because I was originally interested only in the effect of previous-trial error, and the effect of current error came up later and is somewhat more exploratory.
Could I make two "lines" of analyses - first investigating effects of previous error (main interest) and second investigating effects of current error? Or should I include both factors in any analysis that I'll do?
Answer: Lack of independence in predictor variables doesn't violate any of the assumptions of linear mixed models (or linear models, for that matter; this question isn't specific to LMMs) - the only assumption on the predictors is that they are measured without error (and even that assumption can be relaxed, depending on what you're trying to do).
There is a great deal of literature about multicollinearity in linear models and what to do about it; I disagree with a lot of it. Much of the advice on removing correlated/collinear predictors from the model has to do with the idea that correlated predictors "mess up your ability to make inferences", i.e. they increase the uncertainty/standard errors of the predictors with which they are correlated. Fundamentally (IMO), what messes up your inference is that you are missing information about which of the correlated predictors is actually acting; discarding them won't help. I think Graham (2003) gives useful advice.
In your case, I would indeed suggest running both sets of models (i.e., first report the model with both terms included, then report the results from the two models that each have one term included); your first, with the interaction, is the primary outcome, as it is more conservative/honest about your ability to distinguish the effects of these two predictors. The second is more of an exploration of what each predictor could explain on its own. Make sure to be clear about your intentions when writing up the results - don't p-hack!
I wouldn't say it is forbidden to analyze only the second set of models (one term at a time) ... but if I were a peer reviewer on the paper I would probably ask to see the interaction model in any case.
Graham, Michael H. "Confronting Multicollinearity in Ecological Multiple Regression." Ecology 84, no. 11 (November 1, 2003): 2809–15. https://doi.org/10.1890/02-3114.
Comment: Thank you! So you're saying that dependence of predictors is not a problem for modelling, only that it may make me less certain about estimates of my factors? Does it have something to do with power?
I'm not sure if by "two sets of models" you mean both options I mentioned in main post (1st: single model with 2 interacting factors, 2nd: two models with single factor in each)? Or do you mean my 2nd option only (i.e. two models with single factors)? Maybe I didn't make it very clear, but I was actually wondering if it'd acceptable to ONLY run separate models (2nd option), ignoring complex one.
Answer: Is id a key column? The name after | is the grouping factor. If id is unique, you are not aggregating anything.
I'd separate my dataset, use 70% of the data to train the model then test each model on the other 30% to verify how well they fit.
lmer(report ~ currerror + (1|id), data) # each ID has an intercept, random.
lmer(report ~ preverror + (1|id), data)
lmer(report ~ currerror + (1+currerror|id), data)
lmer(report ~ preverror + (1+preverror|id), data)
lmer(report ~ currerror + preverror + (1|id), data)
lmer(report ~ currerror + preverror + (1|id), data)
lmer(report ~ currerror + preverror + (1+currerror|id), data)
lmer(report ~ currerror + preverror + (1+preverror|id), data)
lmer(report ~ currerror + preverror + (1+currerror|id) + (1+preverror|id), data)
lmer(report ~ currerror + preverror + (1+currerror|id) + (1+preverror|id), data)

Comment: Id is a grouping factor - it's a number of participant, and each participant has few hundrets trials (rows). I'm already after deciding what I want to model as random effect, and I want to keep it maximual (basically, it's theory-driven). My question is whether I COULD and/or SHOULD split my analyses for two interdependent factors. I'm inclined to do so, again due to my theoretical assumptions, but I'm wondering if that's justified from the modelling standpoint. Do you suggest to do AIC/BIC on combined and separated models, and simply see which gets lower value?
Comment: I think this answer is useful if your main goal is *prediction*, but it's not a good idea for *inference*.


Permutation tests for sharp vs weak null hypothesis

Question: Permutation tests provide an easy way to obtain well-calibrated tests for experimental (randomized) data for the sharp null of no treatment effect.
The idea: In context where either only the treatment outcome $y_i(D_i=1)$ or the control outcome $y_i(D_i=0)$ is observed, and we care about the average treatment effect:  $\hat{\tau} = \sum_{i|D_i=1}y_i-\sum_{i|D_i=0}y_i$ we can obtain it's distribution under the null of no treatment effect $$y_i(1)=y_i(0),$$ simply be repeatedly permuting the treatment vector $D$ and computing $\hat{\tau}$ (or the corresponding t-statistic). This is often referred to as a test of the "sharp null hypotheses", as opposed to the "weak null hypothesis" which would be something like "no average treatment effect":$$E[y_i(1)]=E[y_i(0)]$$
My question:
I came across papers [1, 2] which seem to imply that under certain assumptions asymptotically this is also a valid test of the "weak" hypothesis of no average treatment effect. I am now looking for a canonical/text-book reference for this statement, in particular w.r.t. the assumptions under which this is valid.
References:
[1] Chung, EunYi, and Joseph P. Romano. "Exact and asymptotically robust permutation tests." The Annals of Statistics 41.2 (2013): 484-507.
APA
 (https://arxiv.org/pdf/1304.5939.pdf)
[2] Bugni, Federico A., Ivan A. Canay, and Azeem M. Shaikh. "Inference under covariate-adaptive randomization." Journal of the American Statistical Association just-accepted (2017).
EDIT:
Additional, related reference that is sometimes cited in that context, unclear why: Janssen, Arnold. "Studentized permutation tests for non-iid hypotheses and the generalized Behrens-Fisher problem." Statistics & probability letters 36.1 (1997): 9-21. (http://www.sciencedirect.com/science/article/pii/S0167715297000436)
Comment: Consider a mixture of treatment effects, where the mixture components are symmetric about 0 under the null but biased toward larger values (or toward smaller values) under the alternative. That seems to be a case where it would work in that way.
Answer: The key is to use the studentized test statistic in a randomization test. Here are two papers under the finite-population framework with the treatment assignment being the only random component.
Ding, P. and Dasgupta, T. (2018). A Randomization-Based Perspective on Analysis of Variance: A Test Statistic Robust with Respect to Treatment Effect Heterogeneity. Biometrika, 105, 45-56.
Wu, J. and Ding, P. (2018). Randomization tests for weak null hypotheses. ArXiv: https://arxiv.org/abs/1809.07419
Comment: Thanks, you should probably point out that these are your papers. But your answer is much appreciated


Angular 9 mat-form-field no outline, no label

Question: Please tell me how can I get rid of the "line" in mat-form-fields !
Please take a look at the attached picture for better understanding !
Thank You !
Here is my code :
HTML CODE

        <mat-form-field fxFlex class="mat-block">
            <input type="number" min="10" max="12000" matInput
                    formControlName="mysettings1">
        </mat-form-field>

CSS
.mat-form-field:not(.mat-form-field-has-label) .mat-form-field-infix {
 border-top-width: 0;
 }

.mat-form-field-wrapper {
 padding-bottom: 0px;
 margin-bottom: 0px;
 margin-top: 0px;
 }

.mat-form-field-label-wrapper {
 padding-top: 0px;
 padding-bottom: 0px;
 margin-bottom: 0px;
 margin-top: 0px;
 }

Comment: Can you provide issue reproducible stackblitz to check the code and it will be easier to understand where the issue is exactly ;)
Answer: ::ng-deep .mat-form-field-underline{
  display:none;
}

It is usually done this way! But its in the middle of the cell for you. If this doesn't work, kindly provide a stackblitz example.
Comment: It is working !
The line is not displayed anymore !
Thank you very much !


Read in different data types from file

Question: ONLY NEED EXPLANATION NO CODE NEEDED!!
I have to read in from a file where the format is <double>, <double> per line where the space and comma are also present. Currently I am reading in with a scanner.nextLine() and I want to know how to parse the String I get for the two doubles I need.
I am using java but not aloud to use pre-built third party libraries.
I have tried DatainputStream and BufferedReader also
Comment: FORMAT IS ", "
Comment: I assume you meant two double-precision floating-point numbers, separated by comma and space, without any quote characters at all, right?
Comment: `String[] tokens = line.split("\\s*,\\s*");` and then parse the pair of tokens.
Answer: What you're looking for is split string
String string = "4.0,3.2";
String[] results = string.split(",");
String firstDouble = results[0];
String secondDouble = results[1];

and then parse the results to double
Double double = Double.parseDouble(firstDouble);

Answer: Scanner.nextLine() is very slow, so it's better to use BufferedReader.
You can then use indexOf() and substring():
try (BufferedReader in = Files.newBufferedReader(filePath)) {
    for (String line; (line = in.readLine()) != null; ) {
        int idx = line.indexOf(", ");
        if (idx == -1)
            throw new IllegalArgumentException("Invalid line: " + line);
        double d1, d2;
        try {
            d1 = Double.parseDouble(line.substring(0, idx));
            d2 = Double.parseDouble(line.substring(idx + 2));
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Invalid line: " + line, e);
        }
        // code using d1 and d2 here
    }
}

Read in different data types from file


Avoiding POT rule for Opengl Textures: Overlapp a transparent POT bitmap with non POT bitmap?

Question: i need to load non POT bitmaps into my opengl es app for android.
What i need is to overlap my non POT bitmap into another bitmap with POT size. I need to overlap the non POT bitmap in the center of the POT bitmap.
How can i do it?
i tryed with createScaledBitmap but it stretches the image and i dont want that.
Thanks
Answer: The way to do this is not projecting a NPOT onto a POT, but loading a POT and manipulating the UV coordinates accordingly in the texture Coordinates buffer. Right now you probably have somthing like this:
<code>private float textureCoords[] = {
        0.0f, 1.0f,
        0.0f, 0.0f,
        1.0f, 1.0f,
        1.0f, 0.0f
};
</code>
For the UV mapping of the texture onto the quad. Changing the values to something other than 0.0 or 1.0 will crop accordingly. Make sure you choose these values right or some color will get into your image.


Tirar duplicidade ignorando uma coluna com informação distinta

Question: Dei uma procurada aqui e não achei nada parecido.
Quando efetuo o seguinte Select :
SELECT
    a.idEmpregadoReserva as Controle
    ,(select EmpresaAplicativo from tbEmpresaAplicativo where tbEmpresaAplicativo.idEmpresaAplicativo = c.idEmpresaAplicativo) Colonia
    ,d.Nome
    ,d.Matricula

    ,a.NumeroDocumento as [Numero Voucher]
    ,e.ValorVoucher
    ,f.TipoVoucher
    ,c.idReserva
    ,(select tipoformapagto from tbHPG_TipoFormaPagto where tbHPG_TipoFormaPagto.idTipoFormaPagto = a.idTipoFormaPagto) [Forma Pagamento]
  FROM [APCEF].[dbo].[tbHPG_EmpregadoReserva_Financeiro] a join tbHPG_EmpregadoReserva_Reserva b on a.idEmpregadoReserva = b.idEmpregadoReserva
   join tbHPG_Reserva c on b.idReserva = c.idReserva join tbEmpregado d on c.idEmpregado = d.idEmpregado join tbEmpregadoVoucher e
    on a.NumeroDocumento = e.idEmpregadoVoucher
    join tbTipoVoucher f on e.idTipoVoucher = f.idTipoVoucher
  where c.DataEntrada between '2019-01-23' and '2019-01-27' and (c.idEmpresaAplicativo = 4 or c.idEmpresaAplicativo = 5)
  and a.idTipoFormaPagto = 1

E aparece o seguinte :

Porem eu gostaria fazer um select como se fosse um select DISTINCT porem ignorando o IDRESERVA, ou seja puxando apenas 1 Numero de voucher ( ele não pode repetir )
Comment: coloca o código do select pra nós por favor, poder dar crtl+c
Comment: @GermanoBussNiehues Fiz a substituição
Answer:     SELECT
        a.idEmpregadoReserva as Controle
        ,(select EmpresaAplicativo from tbEmpresaAplicativo where tbEmpresaAplicativo.idEmpresaAplicativo = c.idEmpresaAplicativo) Colonia
        ,d.Nome
        ,d.Matricula

        ,a.NumeroDocumento as [Numero Voucher]
        ,e.ValorVoucher
        ,f.TipoVoucher
        ,wm_concat(c.idReserva) as ids_de_reservas
        ,(select tipoformapagto from tbHPG_TipoFormaPagto where tbHPG_TipoFormaPagto.idTipoFormaPagto = a.idTipoFormaPagto) [Forma Pagamento]
      FROM [APCEF].[dbo].[tbHPG_EmpregadoReserva_Financeiro] a join tbHPG_EmpregadoReserva_Reserva b on a.idEmpregadoReserva = b.idEmpregadoReserva
       join tbHPG_Reserva c on b.idReserva = c.idReserva join tbEmpregado d on c.idEmpregado = d.idEmpregado join tbEmpregadoVoucher e
        on a.NumeroDocumento = e.idEmpregadoVoucher
        join tbTipoVoucher f on e.idTipoVoucher = f.idTipoVoucher
      where c.DataEntrada between '2019-01-23' and '2019-01-27' and (c.idEmpresaAplicativo = 4 or c.idEmpresaAplicativo = 5)
      and a.idTipoFormaPagto = 1

group by
 a.idEmpregadoReserva
        ,(select EmpresaAplicativo from tbEmpresaAplicativo where tbEmpresaAplicativo.idEmpresaAplicativo = c.idEmpresaAplicativo)
        ,d.Nome
        ,d.Matricula
        ,a.NumeroDocumento
        ,e.ValorVoucher
        ,f.TipoVoucher ,
      (select tipoformapagto from tbHPG_TipoFormaPagto where tbHPG_TipoFormaPagto.idTipoFormaPagto = a.idTipoFormaPagto)

Se eu entendi sua pergunta e a estrutura do seu banco seria isso, espero que funcione =D.
Obs.: Se for MySQL e não funcionar troca o wm_concat por concat_ws
Comment: Não funcionou nem com wm_concat e concat_ws

e não alterando o select da reserva da erro no group by
Answer: Veja se isso te ajuda, essa query é para SQL SERVER
SELECT * FROM (SELECT
    a.idEmpregadoReserva as Controle
    ,(select EmpresaAplicativo from tbEmpresaAplicativo where tbEmpresaAplicativo.idEmpresaAplicativo = c.idEmpresaAplicativo) Colonia
    ,d.Nome
    ,d.Matricula

    ,a.NumeroDocumento as [Numero Voucher]
    ,e.ValorVoucher
    ,f.TipoVoucher
    ,c.idReserva
    ,(select tipoformapagto from tbHPG_TipoFormaPagto where tbHPG_TipoFormaPagto.idTipoFormaPagto = a.idTipoFormaPagto) [Forma Pagamento]
    ,row_number() over(partition by a.NumeroDocumento order by (select null)) as rn
  FROM [APCEF].[dbo].[tbHPG_EmpregadoReserva_Financeiro] a join tbHPG_EmpregadoReserva_Reserva b on a.idEmpregadoReserva = b.idEmpregadoReserva
   join tbHPG_Reserva c on b.idReserva = c.idReserva join tbEmpregado d on c.idEmpregado = d.idEmpregado join tbEmpregadoVoucher e
    on a.NumeroDocumento = e.idEmpregadoVoucher
    join tbTipoVoucher f on e.idTipoVoucher = f.idTipoVoucher
  where c.DataEntrada between '2019-01-23' and '2019-01-27' and (c.idEmpresaAplicativo = 4 or c.idEmpresaAplicativo = 5)
  and a.idTipoFormaPagto = 1) A
  WHERE RN = 1

Comment: Cara funcionou, Poderia me explicar o que foi feito com esse sub select dentro do select ?  Você meio que atribuiu o numero documento como um 'contador' e pediu para mostrar apenas o primeiro ?


Google DNS is too slow connecting to Google APIs

Question: I have a linux server in Germany. The server is configured with Google DNS. When I call from the server some Google API, the connection is too slow, it takes always 2 or 3 seconds to connect to the Google server. I have no problem connecting to other servers.
Paradoxically it seems there are problems resolving Google URLs with Google DNS.
I have temporarily resolved inserting a row in the file hosts.txt that associates the Google IP corresponding to the Google API that I use.
Can I resolve this problem in another (clean) way?
Thank you!
Answer: Don't use Google's public DNS servers where performance matters to you. Both they and the Level 3 servers (126.96.36.199, etc) are under heavy loads and will typically perform worse than a locally hosted resolver or even your ISP's resolvers.
Comment: Ok, but why there are problems only with requests to Google Server?
Comment: Who knows, but Google's public recursive resolvers certainly aren't their authoritative name servers, so they have to be resolved from 126.96.36.199 just like they would from any other name server.
Answer: You can use either namebench or DNS Benchmark from GRC to do a test which DNS server is fastest from your location.
I recommend you to use namebench instead of GRC's DNS Benchmark because GRC is tailored to the US. namebench on the other hand will scan your regional's dns server and it is normally the fastest dns server to choose from.
I just tried it and the namebench shows me how slow google dns servers are compared to my local dns servers (which is a whopping 243% faster than google!).
Here is a screenshot of my benchmark... (sorry had to censure the IPs due to company policy)..

Here is the link to namebench: https://code.google.com/p/namebench/


Touching ball scenario in 8-ball

Question: In the game of 8-ball: suppose my opponent plays his/her shot without a foul, and the cue ball ends in a touching-ball situation (that is, the white ball stops right next to a ball, declared to be touching upon a close inspection). So now it is my turn to play, having been handed a touching ball situation, I see two scenarios:

The cue ball is in a touching situation with one of my own balls (say I had called stripes at the start of the game). Then I can call the touching ball to be my next shot, and it suffices to shoot the cue ball away from it, and it would count as if I had hit the called ball.

The cue ball is in a touching situation with one of my opponent's balls (solid color). Then by the same token, no matter what shot I call, shooting away would appear as if I had first hit my opponent's ball, because the cue ball was in touching with an opponent's ball. But that wouldn't make any sense, because I would then simply have no legal shots, and any play would be foul before me making any shot.

To remedy the 2nd scenario, I've been reading the rules again, and there's no bit that directly addresses this situation, namely, a touching situation where the two balls are the cue ball and one of opponent's ball. In one case, the rules say the following:

5.9 Touching Balls
If the cue ball is touching an object ball, the shooter must not play
the cue ball in the direction of that ball. He is considered to have
hit the touching ball when he shoots away from it if the ball is on
for the shot.

But it does not specify, what if the touching ball is an opponent's ball, it seems to assume the touching ball is one of my own balls, hence the remark at the end "...if the ball is on for the shot." It can only be on for a shot if it is one of my own balls (stripes).
Another source suggests something somewhat orthogonal:

3.18     FAILURE TO CONTACT OBJECT BALL
It is a foul if on a stroke the cue ball fails to make contact with any legal object ball first.
Playing away from a touching ball does not constitute having hit that
ball.

Question:
How are such touching ball situations resolved? What legal shots do I have in case of 1. and 2.? Specially in case of 2., can I hit away from the touching ball even if the cue ball had been in touching/frozen situation with one of opponent's balls?
It would be incredibly useful if you could also include a link to the rules with which you answer the question.
Comment: Your first rule "5.9 Touching Ball" is not from the 8Ball rules but from the Blackball rules. In the same rules under "3.9 Fouls" it is stated that you have to use the rules  "6.7 Double Hit / Frozen Balls" .  This are the touching ball rules that apply for 8Ball.    In your first link there are many different games in one rule. For 8Ball, only the 1.x and 3.x rules apply .    .... So, your second link is correct.
Answer: The rules for these cases are deliberately exceptional, to avoid players seeking to create touching ball scenarios instead of shooting their own object balls, i.e. playing pool.
Scenario 2 would indeed make no sense if it was a guaranteed foul, so touching ball on the opponent's ball is never considered a foul.
It is treated for all intents and purposes as if the cue ball can't be legally played in that direction, but it is perfectly fine to play away, with the usual restrictions that the shooter's own object ball must be contacted and must be contacted first.
Scenario 1 is much the same, though for a different reason. When the cue strikes the cue ball, the cue ball is immediately in contact with the object ball, while the cue remains in contact with the cue ball. This would normally be a push shot and a foul, again making no sense.
Thus, the rules consider this to be an object ball already struck by the cue ball. They then require the cue ball to be played away freely, as this avoids further nonsense such as merely tapping the cue on the cue ball and leaving it in exactly the same place, and putting the opponent in Scenario 2.
Comment: Thanks for the clarifications. So in a nutshell, in either scenario, one is to play away the cue ball, and may or may not call the object ball in contact as the considered shot (of course only in scenario 1), otherwise, in scenario 2, we play away [+] and have to hit a certain called object ball (of our own).
[+]: *hitting away* is a bit vague, e.g. in scenario 2, does it mean that the object ball of opponent being in touching with the cue ball, shouldn't even move at all (not even shake on its spot) when we hit away the cue ball? In case shaken or slightly moved, is that a foul?
Comment: Finally, is there a specific source that you recommend for looking up such rules?
Comment: Correct, playing away from the touching ball should not ever move it - this is usually the defining point of whether a foul occurred. Correct, the only difference between the situations is whether the shooter has "officially" played their own ball yet. No particular source is a favourite, though I haven't seen any disagreement on whether touching object ball counts as played, and never seen or heard of a foul called for touching opponent ball.
Comment: Although I would make exception for a table with unusually poor felt or surface, on calling foul for moving a touching ball, e.g. if there is a dip causing the ball to move because it was being held back by the cue ball, even though the cue ball is played away cleanly.

Touching ball scenario in 8-ball


Equations with the floor function

Question: I am trying to solve the following problem:

For what real numbers $x$ is: $\lfloor2x-3\rfloor-3\lfloor x+2\rfloor=0$?

I have no idea how to do this, please help me
Comment: Try plotting $x \mapsto \lfloor 2x-3 \rfloor$ and $x \mapsto 3 \lfloor x+2 \rfloor$. Note that $\lfloor x + n\rfloor = \lfloor x \rfloor +n$ for any integer $n$.
Answer: As for integer $a, \lfloor{y+a}\rfloor=\lfloor y\rfloor+a$
$$6+3=\lfloor{2x}\rfloor-3\lfloor x\rfloor$$
Now let $x=I+f$
If $f<.5,$
$$9=2I-3I\iff I=?$$
Else $f\ge.5,$  $$9=2I+1-3I\iff I=?$$
Comment: @samjoe, Thanks, please find the updated version
Comment: This method is pretty nifty!
Comment: @samjoe, Thanks for your help
Comment: You forgot to multiple $\lfloor x\rfloor$ by $3$
Comment: @Holo, Thanks for ur input
Answer: Hint:
We know:

$x,y\in [z,z+1)$ then $\lfloor x\rfloor=\lfloor y\rfloor$
$\lfloor a+b\rfloor=\lfloor a\rfloor+b$ for integer $b$

With those 2:
$\lfloor2x-3\rfloor-3\lfloor x+2\rfloor=\lfloor2x\rfloor-3-3(\lfloor x\rfloor+2)=\lfloor2x\rfloor-3\lfloor x\rfloor-9=0\\\implies\lfloor2x\rfloor-3\lfloor x\rfloor=9$
Now divide it into 2 cases, when $\lfloor x\rfloor=\lfloor x+0.5\rfloor$ and when $\lfloor x\rfloor+1=\lfloor x+0.5\rfloor$
Can you continue from here?

Explanation about the cases:
I got to the equation $\lfloor2x\rfloor-3\lfloor x\rfloor=9$, let's look only on $\lfloor2x\rfloor$, if $\lfloor x+0.5\rfloor=\lfloor x\rfloor+1$ then $\lfloor2x\rfloor=2\lfloor x\rfloor+1$ elsewhere $\lfloor2x\rfloor=2\lfloor x\rfloor$
Solution to case one:
If  $\lfloor x+0.5\rfloor=\lfloor x\rfloor+1$:
$$\lfloor2x\rfloor-3\lfloor x\rfloor=9\\2\lfloor x\rfloor+1-3\lfloor x\rfloor=9\\\lfloor x\rfloor=-8\\x=-8+c,c\in[0,1)\\\text{we know that $\lfloor x+0.5\rfloor=\lfloor x\rfloor+1$ so:}\\\lfloor -8+c+0.5\rfloor=\lfloor-8+c\rfloor+1=\lfloor-8+c+1\rfloor\\c\in[0.5,1)$$
Comment: I understand what you have done but when you divide it into 2 cases, from where did you get the 0,5? Please help me i don't know how to continue
Comment: @CarlosToapanta add edit the solution, see if it is clearer
Comment: I think that x must be equal to -7+c instead of -8+c
Comment: @CarlosToapanta no, you maybe did a mistake because of the $-$, try to put values in the form of $-8+c=k\in(-7,-7.5]$ and you will see.
Comment: Yes you are right, so to finally solve the case i have to apply x=-8+c yo get x?
Comment: @CarlosToapanta no, the answer **is** $k=-8+c,c\in[0.5,1)\rightarrow k\in[-7.5,-7)$.now you have to note that this is the answer for the case of $\lfloor x+0.5\rfloor=\lfloor x\rfloor+1$, try to find yourself the answer for the case where $\lfloor x+0.5\rfloor=\lfloor x\rfloor$
Comment: Ok i got [-9+c]=[-9+c+0.5], so what would be the values for c? I'm stuck on that
Comment: @CarlosToapanta you can find it like this, $-9$ is an integer so you get $\lfloor c\rfloor=\lfloor c+0.5\rfloor$ so $c\in[0,0.5)$

Equations with the floor function


Modeling count data with left-skewed distribution

Question: I have 'count' data for species. My count is the number of 15-stop segments in which a species was detected (range 0-15). Sample size range from 350 to 400. I have about 20 predictor variables (e.g., the percentage of land cover type, rainfall in mm, number of assistants) and two interactions.
 For most of my species, I have lots of zeros, right-skewed distribution, and overdispersion.  Hence, I was planning to use negative binomial regression in R (glm.nb).  However, for two of my species, there is a low 0-count, high 15-count, overdispersion, and left-skewed distribution, as can be seen in the example below:

My search online did not reveal any solution for modeling this type of count data.  Should I be using a negative binomial model for species with this type of left-skewed distribution? Is there another type of count model I could use? I am also considering converting the data to the proportion of 15-stop segments in which the species was detected and running a linear model. Is that a wise step?
Alternatively, as discussed here can I invert my variable to the number of 15-stop segments in which the species was not detected and run a negative binomial regression?
Any help/suggestion is welcome.
Comment: Is there some reason why you don't see values above 15?
Comment: We surveyed 15 segments (routes) and therefore 15 was the upper limit.
Comment: Ah; I didn't understand the explanation at the start of the question sufficiently.
Answer: You have data that is bounded above by 15 (and a lot of actual 15s) so a negative binomial has no hope of being suitable.
My first thought would be a binomial GLM; the binomial at least can obey the constraints of it being on 0-15.
It's possible that this is unsuitable -- you may need a quasi-binomial or a 0-inflated model or a beta-binomial or some other way of dealing with the overdispersion depending on its nature -- but the negative binomial isn't going to work at all.
It's hard to give much more specific advice outside of "don't use the negative binomial for this" without more context.


Array de frases em Java

Question: Estou estudando Java, e desenvolvimento Android, e quero fazer esta aplicação para entender como funciona.
Estou utilizando a classe Toast para que ao clicar na imagem, apareça uma frase, consegui fazer funcionar com números, mas no lugar dos números quero colocar algumas frases e quando eu clicar em cima da imagem, a frase apareça por alguns segundos na tela.
Como faço isso sem muitas alterações neste código que ja tenho?
<code>    package android.tutorial.android;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
  }

// public void mostrarMensagem(View view) {
    //Toast toast = Toast.makeText(this.sorteia(), Toast.LENGTH_SHORT);
    //toast.show();

  //}

 public void mostrarMensagem(View view) {
     int[] lista = new int[]
             {
                1, 2, 3, 4, 5, 6, 7, 8, 9, 10
             };
     StringBuilder builder = new StringBuilder();
     for(int i : lista)
     {
          builder.append("" + i + " ");
     }
     Toast.makeText(this, builder, Toast.LENGTH_LONG).show();

      }

}
</code>
Comment: Não entendi por que do *array* de frases, pois se quiser exibir somente uma frase basta trocar a variável `builder` dentro do `Toast` por uma string. É isso?
Comment: @PauloRodrigues O que Eu quero é que a cada clique apareça uma mensagem diferente!
Comment: @PauloRodrigues com este código abaixo, se eu cadastrar 5 mensagens no array e der um unico toque na tela irão aparecer as 5 mesnagens, uma seguida  da outra e não é isso que eu quero. 1 toque, 1 mensagem.                                                    String [] arr = new String []{"sentence one", "sentence two"};
  for(String str : arr)
      Toast.makeText(this, str, Toast.LENGTH_LONG).show();
 }
Answer: Faça algo assim:
<code>public void mostrarMensagem(View view) {
    String[] lista = new String []{"sentence one", "sentence two"};
    String randomStr = lista[new Random().nextInt(lista.length)];

    Toast.makeText(this, randomStr, Toast.LENGTH_LONG).show();
}
</code>
Lembrando que não há nenhuma regra de não poder repetir a frase, para isso teria que fazer algo mais.
Comment: Por hora era isso mesmo que Eu queria, vai me servir como base de estudos, vou entender estes códigos ai. Se não for abusar muito, você pode me dar o caminho das pedras para evitar a repetição das frases? Muitissimo obrigado pela ajuda!

Array de frases em Java


Opening excels from different folders with python

Question: Hi have a folder and inside that folder I have got nfolders(400)
In each of those folders I have several documents and one of them is an excel with a key name
Is there any possibility of oppening those excel as df1, df2,dfn?
Does anyone know how to Do a foor loop that opens each of those 400 folders?
Thanks!!
Comment: Google os.walk.
Answer: Assuming your excel files have extension '.xlsx'.
I use os.walk(path) from os package. os.walk traverses all the subfolders.
Put the path to the parent folder in path variable.
<code>import os
import pandas as pd
path_to_parentfolder = 'Parent_Folder/'
files = []
for r, d, f in os.walk(path_to_parentfolder):
    for file in f:
        if '.xlsx' in file:          #Enter the extension for your file type
            files.append(os.path.join(r, file).replace('/','\\'))
df_list = [pd.read_excel(open(file)) for file in files] #All your data is stored in the list
</code>
Read about os.walk in its docs


What exactly do truth tables mean?

Question: I'm struggling understanding truth tables.
Let's denote a true proposition by 1 and a false proposition by 0.
We will be considering the propositional
operation, $\Rightarrow$ (implies).
The truth table looks like the following
\begin{array}{c|cc}\rightarrow & 0 & 1\\\hline\\0 & 1 & 1\\1 & 0 & 1\end{array}
Does this say that $(0 \land 0) \rightarrow 1$?
If it does, what exactly does that mean -- are we looking at $(0\rightarrow0)$ as one proposition and saying it is true?
Can you please explain this in english -- using sentences like (x>5 for propositions instead of just writing $P$ or $Q$ for propositions)
EDIT
Comment: That truth table is not correct.
Comment: It's the truth table for the implication, not for $\wedge$.
Comment: Adeeb: see [this link](http://math.stackexchange.com/questions/70736/not-understanding-this-row-of-truth-table-for-logical-implication?rq=1)
Comment: @Adeeb By definition (of *statement*) any statement has a truth value and that includes conditional statements.
Comment: In a simpler fashion, my question is --- using the question found here [link](http://math.stackexchange.com/questions/68318/determining-the-truth-value-of-a-statement?rq=1), how can you say the statement "If 2 is even then New York has a large population." is true. This is a conditional statement, it can neither be true nor false, so I'm confused when we classify $A \Rightarrow B$ as true or false when certain conditions are met by A or B.
Comment: JDH's explaination, [here](http://math.stackexchange.com/questions/70736/not-understanding-this-row-of-truth-table-for-logical-implication?rq=1) makes sense. Thanks @amWhy
Comment: as an example: the truth table (if corrected) means that $0 \Rightarrow 0$(upper left corner) is a true statement.
Comment: You're welcome, Adeeb!
Answer:
What you've posted is the truth table for material implication (the conditional) $p \rightarrow q$.
EDIT:
To better understand the material conditional (the connective $\rightarrow$, i.e. implication), see the following posts:

Not understanding the truth table for logical implication
How is $p\rightarrow q$ true when both $p$ and $q$ are false?
How to interpret material implication and explain it to a freshman?
Help to understand material implication

At each of those links, you'll find more linked questions that are also relevant.
You are not alone: logical implication (e.g. $p\rightarrow q$) is perhaps the most difficult connective to grasp, in terms of its truth-table and how it is defined, in classical logic, (which is, in part, explained by the fact that in natural language, the term "implies" is used in ways whose meaning is not captured by its narrower meaning, as defined in logic).
If you have any further questions, I'll be happy to try and answer them!
Comment: I was raised under the terminology that material implication is a connective between formulas (or propositions) and logical implication is a statement *about* formulas (or propositions).
Comment: @Asaf: Yes, I customarily do the same, but it seems the convention isn't universally followed (or, perhaps the distinction is not universally understood).
Comment: Convincing answer Amy. :+)
Answer: See this answer, or any of the other fine answers to that question.
Comment: Cameron - the op clarified that he meant $\rightarrow$: implication.
Comment: @amWhy: Thanks for letting me know.
Comment: In any standard logical language, $\land$ is a propositional connective, and can only connect propositional clauses. In such languages, $(P_1\land Q_1)(x)$ is therefore ill-formed.
Comment: @Peter Smith, can you please simplify that sentence. I don't understand what you mean.
Comment: @PeterSmith: Fair enough. Here, though, $P_1,Q_1$ are functions $\Bbb Z\to\{0,1\}$ defined by the truth or falsity of the corresponding statement, and $\land$ is a (well-defined) operator on the set of such functions. Also, I have edited my answer in response to the OP's correction, so $P_1,Q_1$ are no longer even mentioned in the answer.
Answer: If (as both the question title and initial sentence suggest) you are struggling with truth tables more generally, read a good introductory logic book. To help you with this sort of thing is exactly what such books are there for. If one doesn't work for you, try another. But you'll find patient explanations (more extended and careful that we can give here).
For example, you could look at Paul Teller's A Modern Logic Primer. Download the first four chapters from here: http://tellerprimer.ucdavis.edu/pdf/
Or you could look at my Introduction to Formal Logic or Sam Guttenplan's The Languages of Logic or Paul Tomasi's Logic (to mention just a few other books which aim to be particularly accessible at this introductory, and are thought to succeed).

What exactly do truth tables mean?


How to see Websphere application Server (WAS) responses

Question: On occasion Post request sent to our WAS leave the browser (IE) waiting for a response forever (until manually cancelled - e.g. by closing the browser).
Looking at the Trace and SystemOut logs on WAS everything looks fine. in the http_error log we can see the Get and Post requests but not the responses (even for successful requests). Is there a way to see the responses, or at least when they are sent? We need this to ensure that a response is being sent to the browser. Thanks.
Answer: I would issue a SIGQUIT signal to the Websphere process in order to produce a javacore, i.e. a threadump, in order to see what my WebContainer threads are actually doing.
Try running a kill -3 <WAS process ID> as root in a unix platform or invoke DumpThreads through wsadmin if running on a Windows platform.
Answer: You should enable trace for servlet container. This is done by setting trace string to *=info:com.ibm.ws.webcontainer*=all:com.ibm.wsspi.webcontainer*=all:HTTPChannel=all:GenericBNF=all
Setting up a trace


How can I get hardware ids/serial numbers through command prompt?

Question: Eventually I'm going to be using this in Java Applet for extra security to the user. I know it's possible because I remember doing it before, I just can't remember the line that gets the correct information.
I'm searching for a line that will return the Processor ID, Serial number. Just these two are fine.
I have used google and tried a few commands like "wmic bios get serialnumber" and it doesn't return anything.
The Processor ID and Serial number should be two unique numbers or Strings.
Answer: The BIOS serial number often is not set.
This should always give you unique hardware information with a similar command:
wmic csproduct get uuid

You could also combine this info with more information to be sure it is unique. Some examples:
wmic csproduct get uuid,name
wmic bios get name,version

Comment: How is the uuid set? Is it different per computer or are they able to change it manually etc? I'm trying to get information which differs per computer and is rather hard if not impossible to change.
Comment: @Kieran I think it's a hardware property. I don't know if you can directly overwrite it, but i'm sure that you can fake it or modify the wmic program. If the uniqueness of this is dependant on the security of you program then you should rethink, because there is no security. A user that knows what he does can fake everything he wants.
Comment: hmm okay thanks, I'll have to think of something. One last question, does this work on every operating system or just a certain version of Windows?
Comment: @Kieran wmic is a windows application. msdn says its supported since windows XP. see http://msdn.microsoft.com/en-us/library/windows/desktop/aa394531(v=vs.85).aspx
Comment: WMIC is not supplied (at least by default) with XP/Home.
Comment: `wmic cpu get ProcessorId`
Comment: The UUID from `wmic csproduct get uuid` comes from the SMBIOS of the Motherboard. It is not guaranteed to be unique since some manufacturers are lazy and reuse the same number. More details in the comments here: https://stackoverflow.com/a/58416992/8874388


Any way to have "Path Will Be Viewed" trigger?

Question: I would like to restrict certain roles from visiting certain pages, ideally by using Rules.
I am able to do this with Nodes, however for Pages such as a Views Page, I can't see any way of triggering this redirect?
Answer: If you simply want to restrict the access to the View, you should alter the settings for the View.
Under the access settings, select Role instead of Permission, and select the appropriate role.
However, if you have to use Rules for some other reason, I would create a rule that triggered every time Drupal is initializing. And then, add a condition with custom PHP code. You could do something like
global $user;
$rid = 1;
return ($_GET['q'] == 'my/forbidden/path' && isset($user->roles[$rid]));

and then add an action that redirects the user to another page.
Answer: I guess you can achieve what you're looking for using Page Manager Redirect instead of Rules.
Comment: I have never tried it myself, but the module description fits. Always try http://drupalmodules.com to look for modules.
Answer: Selection rules like this are why we typically use Panels for displaying all pages.  Rather than use different access methods for different page types, you get a consistent interface.
In you case, you would set up your view as a Content Pane and not a Page.  You would then build a new panel page, and when you can add content, your view will show up in the View Panes tab.
You can then set up your selection rules.  Among the rules are User Permissions and User Roles.
Answer: Sure there is a way to exactly do what you are asking for, i.e. "... restrict certain roles from visiting certain pages, ideally by using Rules.".
The trick (clue) to actually do this is like so:

Use Rules Event "Drupal is initializing".
Add the appropriate Rules Conditions to check for the "Roles" you want to verify, and the "Path(s)" you want to apply this to.
Typical Rules Actions you might want to do are to set some Drupal Message, and/or some redirect to some other page.

Below is an example of such rule (in Rules export format) that is pretty close to what you asked for:
{ "rules_limit_access_to_some_urls_" : {
    "LABEL" : "Limit access to some URLs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "NOT user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      },
      { "OR" : [
          { "data_is" : {
              "data" : [ "site:current-page:path" ],
              "op" : "IN",
              "value" : { "value" : [
                  "abc\/x123",
                  "efg\/y456",
                  "hij\/z789"
                ]
              }
            }
          },
          { "text_matches" : {
              "text" : [ "site:current-page:path" ],
              "match" : "node\/\\d+\/something",
              "operation" : "regex"
            }
          }
        ]
      }
    ],
    "DO" : [
      { "redirect" : { "url" : "some_path" } },
      { "drupal_message" : {
          "message" : "Access to the content located at \u0022\u003Cstrong\u003E[site:current-page:path]\u003C\/strong\u003E\u0022 is not allowed.",
          "type" : "warning"
        }
      }
    ]
  }
}

Some more details about verification in the Rules Conditions in the above example:

check if the current user is not an administrator (for administrators the Rules Action does not apply)
check if the "path that will be viewed" is either abc/x123, efg/y456 or hij/z789, or if it is a path with a pattern like node/x/something (with x some digit(s)).

If both Rules Conditions are true, then the Rules Action will perform a redirect (to a path like some_path), and some message is shown to the user.
To make the above rule work in your case, just adapt the paths (change them to whatever fits), and the message to be shown for those who are not allowed to access those paths.
Note that it doesn't matter what these paths relate to: they can be nodes, views pages, user profiles, etc (all such cases should work).


Java time problems

Question: I have a problem of inconsistency with time objects
Time time1 =  new Time(72000000); //21:00
Time time2 = new Time(new Date().getTime()); //before 21 pm

time2.before(time1);

The last line returns always false, why?
Comment: Java Time is about the amount of ms since January 1, 1970.
Comment: This is one of those questions that always gets upvoted but are answered straight in the API.
Comment: The answers offered give a good explanation of whats happening. I'd recommend using the JodaTime (http://www.joda.org/joda-time/) if you can as the API for time and Date manipulation is a lot nicer.
Answer: Time:
A thin wrapper around the java.util.Date class that allows the JDBC API to identify this as an SQL TIME value. The Time class adds formatting and parsing operations to support the JDBC escape syntax for time values.
The date components should be set to the "zero epoch" value of January 1, 1970 and should not be accessed.
http://docs.oracle.com/javase/7/docs/api/java/sql/Time.html
Basically you're comparing 21:00 at the first of january 1970 to your current date at some point in the day. Obviously the former time happens earlier and is 'smaller'.
Answer: This is not doing what you think it's supposed to do!
Time time1 =  new Time(72000000);

See this:

Time

public Time(long time)

Constructs a Time object using a milliseconds time value.

Parameters:
    time - milliseconds since January 1, 1970, 00:00:00 GMT; a negative number is milliseconds before January 1, 1970, 00:00:00 GMT

Now, hopefully you understand...
Comment: The other guy answered it first
Answer: Since you didn't specify otherwise, I assume that the Time object is java.sql.Time.
This object uses a superclass of java.util.Date so it is actually a full date object.  For the purposes of JDBC (SQL) it only concerns itself with the time portion of the date.
This:
Time time1 =  new Time(72000000);

...creates an object that represents 1-January-1970 21:00 hours.  It will always be before any current time.
Answer: Seems that time1 is 14:00 . Run the below code snippet.
 Time time1 =  new Time(72000000); //21:00
 System.out.println(time1); //prints 14:00
 System.out.println(new Date());
 Time time2 = new Time(new Date().getTime()); //before 21 pm

Java time problems


Best approach to store a set of static String values

Question: I have a requirement to retrieve query params lets say clId,clCtx and clName from an odata uri and use them throughout the program across many classes. Retrieving the query params is an expensive process each time in our customised client framework. What is the best approach to retrieve and store the params once per request and utilise the same throughout the program?
My thoughts were to create a singleton class with a static java map as below. For the first time I can retrieve and store them in a map to use them later.
Also Would like to know Is my approach has any issues like memory leak or drawbacks.
public class ClientContainer {

  private static Map<String,String> clientMap;
  private static ClientContainer instance;

  private ClientContainer(){}

 public static ClientContainer getInstance(){
    if(instance == null){
        instance = new ClientContainer();
    }
    return instance;
  }

  private void updateClientMap(HashMap<String,String> clientMap){
    if(this.clientMap==null){
        this.clientMap =clientMap;
    }
  }

  private HashMap<String,String> getClientMap(){
     return this.clientMap;
   }
}

Comment: Using a map is also expensive if you already know the parameter names, and they are not dynamic. I guess, I would rather use the good old bean, it is fast and clean. Also, depending on the implementation behind your system you might be just replacing a map by another map, in which case the suggested approach would be harmful.
Comment: Victor, The query params which I retrieve is not a plain Java map. There are about 4 transformations(scala data to Java data) to be done to get a Java Map with those params. I have to repeat this process 10-11 times in different classes.As this affects the performance of program, Instead I need a efficient and optimized way to store them up some where in program as one-time step and fetch them in an easy way whenever I need them.
Comment: How many are the parameters? do know know their names ahead of time? if they are few and you know them, I would use a bean.
Comment: in that case, I like your solution, but you like to check if you map calls for volatile and you be even more comfortable if besides being volatile was immutable and final.considering that you add a client key as well.
Comment: Thanks Victor for your suggestion. It would rather be good to use a bean, as my approach is buggy and may cause memory leaks in real time which is even more expensive.
Answer:
Also Would like to know Is my approach has any issues like memory leak
  or drawbacks.

1) Your ClientContainer class stores only the parameters for one client.
You use a Map<String,String> (values by param) in and not a Map<Client, Map<String, String>> (values by param and all that by client).
As you can instantiate a single time the class with the singleton pattern you are so stuck to store data not more than for one client request.
2) The lifespan of the requests (param-value) will be endless in this way.
The Map will indeed never be garbage collected as this is referenced by the singleton instance that has never a chance to be garbage collected too.
So if you keep the singleton pattern you should at least consider the key-values according to the client and you should also think to clean the cache at each time that a request was completely handled to avoid memory leak.
But If I was you, I probably would use another solution:

either I would create the Map as a local variable a single time : at the time where I receive the request and then I would pass it explicitly to each method that needs that.
or I would use ThreadLocal to store the Map if each request is handled by a specific thread.

Note that I prefer the first way that exposes clearly the dependency of the method.
Note also that using a Map is not necessary the best thing if the number of fields to use is stable and known : using a custom class may be much clearer, readable and more robust.
Comment: up for that: either I would create the Map as a local variable a single time : at the time where I receive the request and then I would pass it explicitly to each method that needs that.
Comment: likewise, good luck. but just to clarify, yes you need sync if 2 levels. but for the last level not. on that case there are 2 maps and I was referring to the inner one.
Comment: Thanks David for a clear explanation. This was really helpful.
Comment: @Lokesh Reddy I am glad if it was helpful for you.
Comment: the centralized cache as described in this answer would also benefit from being volatile, possibly final, with extra logic for assuring the map is mutable.  the map it self does not call for being synchronized, as long it is read only.
Comment: @Victor I agree for all but "the map it self does not call for being synchronized, as long it is read only."  From the moment where you change the state of the map (to add parameters of a client request or to clear the cache of a client request) you may (at least in theory) corrupt the map state if you have race condition in the map access.  Synchronization is so required to avoid that.
Comment: Thanks again! Victor and David ,both your inputs helps me in deciding a best way as per my context. Up for both :)
Comment: @Lokesh Reddy  "Up" means "I upvoted" :) You cannot for the moment (you don't have enough reputation) but whatever thanks for you good words :)
Answer: If you are using ClientContainer class in multithreading environment, then make sense to make getInstance() method thread-safe in order to avoid duplication of constructor. To avoid of memory leaks you can use WeakHashMap instead of HashMap.


How to generate random variables which are correlated and yet marginally identically distributed?

Question: I am wondering if there is a process to which we can generate random variables where there is a correlation structure between them, yet they are still marginally identically distributed? One idea that comes to mind is to work with perhaps random variables which are generated according to a stable law distribution. However, I am not sure how to modulate the correlation. Any ideas would be greatly appreciated.
Comment: Moreover, there's clearly an infinite number of ways to do this. The most obvious is to simply use a multivariate normal, but I assume that's not what you want. Providing us with more constraints can help us think of a solution that meets your actual needs.
Comment: I was going to point you to an [answer](https://stats.stackexchange.com/a/330290/76981) I wrote in regards to simulating from copula models. But then I realized you were the one who asked that question! Is the issue with using a Gaussian copula that it doesn't necessarily preserve the correlation matrix (i.e., pairwise correlations are not preserved due to non-linear transfromations)?
Comment: Where marginal distributions follow any distribution?
Comment: Thanks, sorry for the confusion, I meant that the marginals would follow the same distribution. I'll change it above
Comment: Maybe this is a [lead](https://books.google.ca/books?id=C9hECgAAQBAJ&pg=PA101&lpg=PA101&dq=%22marginally+identically+distributed%22&source=bl&ots=qBBQaJHkcf&sig=2RG2hgXs3xdfIzPxzuWFe5cnJmk&hl=en&sa=X&ved=2ahUKEwil8K3DqIzfAhWaGDQIHeNZBhkQ6AEwA3oECDEQAQ#v=onepage&q=%22marginally%20identically%20distributed%22&f=false)
Comment: Are you asking for a solution when the marginal distribution are *specified* or are you just asking about how to do this generally and don't care what the marginal distribution might be?
Comment: You could perhaps start with simulating random draws for your marginally identically distributed, uncorrelated, random variables. Then transform these uncorrelated variables into variables with your desired covariance structure, via the Cholesky transformation.
Answer: This question is very broad, the class of random vectors you describe is very large, and there is no reason to expect one unified simulation algorithm for all of them. So the best we can do is giving examples.

Some multivariate normal vectors, it is enough to require that the mean vector is constant $\mu \mathbf{1}_n$ and the covariance matrix is constant along the diagonal $\text{diag}(\Sigma) = \sigma^2 \mathbf{1}_n$. Then see Generating values from a multivariate Gaussian distribution.  Similar ideas for any elliptically-contoured distribution.
Stationary time series model will do.  For a short series the idea from 1. can be used, where the covariance matrix is a toeplitz matrix. General ARMA covariance matrix could be done as well.
Else, for instance Simulating state space model with AR(1) dynamics
Any exchangeable vector can be used. A very simple example is the following.  Let $X_1, X_2, \dotsc, X_n$ be iid and $Z$ be independent of the $X$'s. Then $X_1+Z, X_2+Z, \dotsc, X_n+Z$ will satisfy your requirements. This is related to the representation theorem of de Finetti so quite general.
A copula is a joint distribution where all marginals are uniform on $[0,1]$. After simulating that, you can just transform the marginals with the usual quantile transform (probability integral transform).


Redirect anonymous user to login page

Question: I need to redirect an anonymous user when they hit the url 'node/add/project' to 'user/login' - otherwise, just leave them enter that url.
Not sure if I'm going about this the correct way (probably not as it doesn't appear to work!) - Can someone shed some light, or advice!

function local_menu() {
    $items['node/add/project'] = array(
        'page callback' => 'local_project_anonymous',
        'access callback' => TRUE,
        'type' => MENU_CALLBACK,
    );

    return $items;
}

function local_project_anonymous(){
    global $user;
    if($user->uid == 0){
        drupal_goto('user/login');
    }
}

Cheers
Comment: Why don't you create a permission, and use it for the menu callback?
Answer: <code>function MODULE_init(){
  global $user;
  if ($user->uid == 0  && $_GET['q'] == 'node/add/project' ) {
    drupal_goto('user/login');
  }
}
</code>
Comment: This causes problems with drush. To prevent that you can use if (!function_exists('drush_main')) { ... } to check if you're in drush environment . See also http://stackoverflow.com/questions/6825256/drush-status-unrecoverable-error-caused-by-drupal-goto-in-hook-init
Answer: Maybe you can use the LoginToboggan module.

The LoginToboggan module offers several modifications of the Drupal login system in an external module by offering the following features and usability improvements:

Allow users to login using either their username OR their e-mail address.
Allow users to login immediately.
Provide a login form on Access Denied pages for non-logged-in (anonymous) users.
The module provides two login block options: One uses JavaScript to display the form within the block immediately upon clicking "log in". The other brings the user to a separate page, but returns the user to their original page upon login.
Customize the registration form with two e-mail fields to ensure accuracy.
Optionally redirect the user to a specific page when using the 'immediate login' feature.
Optionally redirect the user to a specific page upon validation of their e-mail address.
Optionally display a user message indicating a successful login.
Optionally combine both the login and registration form on one page.
Optionally have unvalidated users purged from the system at a pre-defined interval.
Integrates with the Rules module to do various tasks when a user validates via email validation process (see http://drupal.org/node/880904 for an example).
Comment: http://drupal.org/project/logintoboggan is made for this!

Redirect anonymous user to login page


NHibernate QueryOver with an Or subquery

Question: Ok I'm losing on this one. I have an NHibernate query that looks something like this
  var subQuery = QueryOver.Of<Lead>()
            .Where(x => x.Client == user.Client)
            .And(x => x.LeadType == leadType && x.LeadType != LeadTypeEnum.Self)
            .Select(Projections.Distinct(Projections.Id()));

I use this
  var query = Session.QueryOver<Lead>()
            .WithSubquery.WhereProperty(x => x.Id).In(subQuery);

This produces what I need
Where lead.id in (select Id from .......)

However, I need to add another subquery. Easy to do like above, but I need this to produce the following
Where lead.id in (select id from .....)
or lead.id in (select id from .......)

The problem is I'm always getting the following
Where lead.id in (select id from .....)
and lead.id in (select id from .......)

Could someone point me in the correct direction to get the Or please
Answer: I'm an NH newbie myself , but you might want to try created a disjunction and adding the conditions to it, then adding the disjunction to the QueryOver Where call.
var disjunction = new Disjunction();
disjunction.Add(subQuery1);
disjunction.Add(subQuery2);
var query = Session.QueryOver<Lead>()
    .Where(disjunction);

Comment: Have you tried something like `disjunction.Add(subQuery1.UnderlyingCriteria)` or `disjunction.Add(subQuery1.DetachedCriteria)`?
Comment: I thought about something similar however, I get

Error 13 Argument 1: cannot convert from 'NHibernate.Criterion.QueryOver' to 'NHibernate.Criterion.ICriterion'
Comment: Not at my computer now, but if memory serves me I get the same or similar issue


Any Ajax or Flash slider which displays websites/url aside from images

Question: Hi there guys I was wondering if you have any suggestions on any flash or ajax slider (plugin/library) which can display websites instead of images with features like transition effects animation and infinite looping.
I am currently playing with anythingslider a jquery plugin but couldn't get to display url's/websites with it.
Also Id like to know if you guys know if there are any alternatives to anythingslider.  Any flash or ajax plugin will do as long as it has the features i mentioned above.
I know that what i want can be achieved using iframe and javascript which accepts a list of urls and then loops through the list displaying websites instead of images.  But im looking for a more flexible and flashy way to do this.
Thanks in advance.
Answer: Check out 30 great sliders here.. http://www.themeflash.com/30-stunning-jquery-slider-plugins-and-tutorials-to-boost-your-work/
Honestly I doubt anyone can tell you which one is the best as you would be the only person who can determine which one works best for "you"
Comment: @royjavelosa: My favorite one is http://sorgalla.com/jcarousel/ ... I put together a quick example for you. You will need to fix a few things here and there such as css etc but it gives you an idea on how to do this.. http://jsfiddle.net/zSrrW/
Comment: Thanks for the reply Eddy :) but i was looking for something that can display webpages instead of images.
Comment: @royjavelosa: That's why I suggested that you have to use some of those plugins to understand how it works. Most of the sliders aren't just for images. They can display any html data. So all you basically have to do is insert the code for iframe. Using jquery to loop through the list of urls shouldn't be that difficult.
Comment: @Eddy: I did look at your list.  Also I already encountered some of them during my google searching, and tested some of them even before i posted this question here, that is why was strongly considering anythingslider.  My inquiry was are there any specific plugin you might know or recommend which can display an actual website e.g. google->yahoo->bing and so on.  Id appreciate if you can recommend something which you had actually used which really stoodout among the other options. Thanks.
Comment: @Adil: Thank you so much exactly what I was looking for!!!  Easy to use flexible and with all the features in my wish list :)  Also thank you for the example it was very helpful.  Just one last question, I already know how to set it to scroll automatically but is it possible to remove the control buttons (back and next arrow buttons) Again thanks!!!
Comment: @royjavelosa: You welcome. It's possible. You have to use the following configuration.. `buttonNextHTML: null, buttonPrevHTML: null` ..for an example check out http://sorgalla.com/projects/jcarousel/examples/static_controls.html


React Router 6 - How to pass components to Route-path with conditional logic

Question: I am currently updating my React-app from React Router Version 5 to 6 and I can't figure out how to properly refractor one of my routes, which looks as follows:
React Router Version 5:
<Route path="/">
  {!authCtx.isLoggedIn && <Login />}
  {authCtx.isLoggedIn && <Layout />}
</Route>

What I tried in React Router Version 6:
<Route path="/" element={!authCtx.isLoggedIn ? <Login /> : <Layout />} />

The routing works in Version 6 (the Login or Layout Components get loaded in the browser, depeneding on whether a user is authenticated or not) but I see the following error messages appearing in the console, which i don't see in Version 5:

react-jsx-dev-runtime.development.js:117 Warning: Each child in a
list should have a unique "key" prop.
react-dom.development.js:67 Warning: Received true for a
non-boolean attribute exact.
Warning: React does not recognize the activeClassName prop on a DOM
element. If you intentionally want it to appear in the DOM as a
custom attribute, spell it as lowercase activeclassname instead. If
you accidentally passed it from a parent component, remove it from
the DOM element.

So my question is: What is the proper way to pass a Component to the element props of a Route in React-Router Version 6, if I want to use some conditional logic, that determines which Component gets passed?
Many thanks in advance!
Comment: All those warning appear to be occurring in a `Disclosure` component. Please update your question to include all the relevant code you've an issue with or questions about.
Answer: You need to compare the !authCtx.isLoggedIn to some condition, but I assume it'll be something like !authCtx.isLoggedIn === true/false
Can you try it like this to see if this works or not, but I hope it does, I'm learning React, too, so maybe I could be wrong, pardon me :)
<Route path="/" element={!authCtx.isLoggedIn === true ? <Login /> : <Layout />} />

Comment: Don't compare boolean values directly to `true`|`false`, this is an anti-pattern. Nothing at all incorrect with using the boolean value directly in an expression.
Answer: This is the exact way how you would conditionally render the component. There is no bug in your rendering. But for the warning of key you need to add an attribute to the child elements whereever you are mapping over a list and assign a unique value to that key attribute for every list item (either an id or the index of element).


Inner Join não funciona - Erro 1054

Question: Alguém poderia me explicar por que essa query não funciona?
select mensagem.mnsg, aluno.nome as nomea, aluno.curso as cursoa
from mensagem
inner join aluno on aluno.rm=mensagem.RM
order by id asc;

-- Table aluno

CREATE TABLE `aluno` (
`RM` INT(11) NOT NULL,
`Turma_ID` INT(11) NOT NULL DEFAULT '0',
`Foto` TINYBLOB NULL,
`Nome` VARCHAR(50) NULL DEFAULT NULL,
`Email` VARCHAR(50) NULL DEFAULT NULL,
`Senha` VARCHAR(50) NULL DEFAULT NULL,
PRIMARY KEY (`RM`),
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
;

-- Table mensagem

CREATE TABLE `mensagem` (
`ID` INT(11) NOT NULL AUTO_INCREMENT,
`RM` INT(11) NOT NULL,
`mnsg` TEXT NULL,
`RM_PROF` INT(11) NULL DEFAULT NULL,
`Turma_ID` INT(11) NULL DEFAULT NULL,
PRIMARY KEY (`ID`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=3
;

-- Table turma

CREATE TABLE `turma` (
`Turma_ID` INT(11) NOT NULL DEFAULT '0',
`curso` VARCHAR(50) NULL DEFAULT NULL,
`ano` INT(11) NULL DEFAULT NULL,
`QNT_ALUNO` INT(11) NULL DEFAULT NULL,
PRIMARY KEY (`Turma_ID`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
;

Comment: Não sei se é o caso, mas tem opção de chat no Stack, acredito que sirva para esses propósito também.
Comment: Retorna algum erro?
Comment: Mas o select está ali amigo :(
Comment: O erro retornado está no título, 1054
Comment: Tenta isso:  select mensagem.mnsg, mensagem.RM, aluno.nome as nomea, aluno.curso as cursoa, aluno.rm from mensagem inner join aluno on aluno.rm=mensagem.RM order by id asc;
Comment: Ops, como não estava na mesma formatação, acabei não vendo, foi mal, vou excluir meu comentário.
Comment: Estou recebendo muitos votos negativos, o que eu fiz de errado?
Comment: Quando são coisas muito básicas ou pedidos para fazer o código, geralmente as pessoas não gostam e negativam. No seu caso acredito que foi falta de atenção para resolver o problema, fique mais atento à estrutura do BD
Comment: Entendi, obrigado
Answer: Você está buscando aluno.curso em aluno, mas na criação da tabela aluno não existe a coluna curso...
Junte a tabela curso através do turma_ID que vai dar certo.
assim que chegar em casa edito a resposta com o código para você.
Comment: Muito obrigado Luis! Você me ajudou novamente!
Answer: Select mensagem.mnsg,
      aluno.nome as nomea,
      turma.curso as cursoa
From mensagem
Inner join aluno on
     aluno.rm=mensagem.RM
Inner join turma on
     turma.Turma_ID = mensagem.Turma_ID
Order by id asc;

Você estava selecionando o curso no aluno, sendo que o curso está na tabela turma.
Comment: Obrigado! Deu certo!

Inner Join não funciona - Erro 1054