$\overline{\mathbb{Q}}$-valued points of a $\mathbb{C}$-scheme

Question: I've just read the definition of a $T$-valued point on an $S$-scheme from Ravi Vakil's notes (i.e. the morphisms $T \to S$), and something about the definition doesn't seem to make sense intuitively.
To make everything as "nice" as possible, I'm going to phrase my question with $\overline{k}$-varieties. Let's say I have the $\mathbb{C}$-variety $V := \text{Spec}(\mathbb{C}[x] / ((x-i)(x-\pi))$. In classical algebraic geometry, one could easily talk about the algebraic points on $V$, i.e. the point $i$. However, using the definition of a $\overline{\mathbb{Q}}$-valued point on $V$, we get $V(\overline{\mathbb{Q}}) = \emptyset$ since there exist no morphisms $\mathbb{C}[x] / ((x-i)(x-\pi)) \to \mathbb{Q}$. Am I missing something here, or is this just an unfortunate side-effect of using schemes?
Answer: Since $\overline{\mathbb{Q}}$ is no $\mathbb{C}$-algebra, it doesn't make sense to talk about the $\overline{\mathbb{Q}}$-valued points of a $\mathbb{C}$-variety. Of course you could look at the underlying variety over $\mathbb{Q}$, say, but then there are again no points, as you have observed correctly. Your $\mathbb{C}$-variety has exactly two $\mathbb{C}$-valued points.
Comment: You have to think of $\mathbb{C}[x]/((x-i)(x-\pi))$ as a whole, not just of one piece of it. Put differently, you cannot write down the equation $(x-i) \cdot (x-\pi)=0$ over $\overline{\mathbb{Q}}$.
Comment: Right, but since $i$ is indeed an element of $\overline{\mathbb{Q}}$, my intuition tells me that it should correspond to a $\overline{\mathbb{Q}}$-valued point of $V$ (if we define $T$-valued points "correctly"). Why is my intuition failing here, or is there perhaps some more general definition of $T$-valued points?


Chef: how to run actions if git deploy has pulled new code?

Question: Most of the time there's nothing new in the git repo that is deployed to a local directory, but if there are any changes, the node.js application should be restarted to start working with the latest changes. It should not be touched if no new code was pulled.
How to achieve that with chef?
Comment: Can't you use the git 'post-update' hook?
Answer: The git sync action actually triggers notifications if the revision has changed. So add an execute block that runs only on notification, and you're done!
git "/home/code" do
    ...
    action :sync
    notifies :run, "execute[restart-node-app]", :immediately
end

execute "restart-node-app" do
    command "..."
    action :nothing
end

Comment: Also check `deploy` resource which is more suited for deployment tasks https://docs.chef.io/resource_deploy.html


How to add permanent route with Netmask?

Question: I am  new to linux. I want to add below permanent route:
[root@Docker1 ~]# route -n | grep 10.246.179.0
10.246.179.0    0.0.0.0         255.255.255.192 U     0      0        0 eth0

I added a file named route-eth0 in network-scripts as below:
10.246.179.0/24 via 0.0.0.0 dev eth0

But instead of 255.255.255.192, I am getting route as below:
10.246.179.0    0.0.0.0    255.255.255.0   U   0    0     0    eth0

What should I do to get the desired result? I am on RHEL 6.
Comment: Dude...that's not linux specific. Would you please check your CIDR notation and netmask and _maybe_ find the error?
Answer: You are providing a /24 netmask, which results in .0.
There are several subnet calculators available on the internet, you can use any one of them to get that the correct netmask for .192 is /26.
10.246.179.0/26 via 0.0.0.0 dev eth0

Comment: Oh it works like this. Thanks.


Mail not delivered from custom email server (MS Exchange)

Question: I have my own Exchange Server 2013 (SP1). I am able to receive emails ok but sending emails is not reliable. Emails sent to gmail or seznam.cz (email provider in Czech Republic) is ok.
The problem is sending emails to outlook.com. I guess it is somehow discarded by spam filter but I don't know why. The delivery report says The message was successfully handed off to a different email system. This is as far as we can track it. but email is not delivered and nothing returns back.
This I have already done:

set MX record for my domain (aaa.com to mail.aaa.com)
set A recored (mail.aaa.com to x.x.x.x)
set reverse IP record (x.x.x.x to mail.aaa.com)
set TXT record v=spf1 mx a -all
removed internal hostnames of outbound emails (link)
set FQDN for send connector (mail.aaa.com)
set FQDN for FrontendTransport receive connectors (mail.aaa.com)

The mail server is not listed in any blacklist in http://mxtoolbox.com/blacklists.aspx.
Is there anything else I should do? I really don't know where to start looking right now.
Comment: If your mail server is getting a successful SMTP message out, and recipients aren't receiving it, you *must* ask the people who own the next-hop mailserver. There is literally no other way for you to find out what that mailserver did with what your server gave them. You can guess all day long, and you should (in general) follow best practices and check if you're on DNS RBLs, etc, but it's still just guessing.
Comment: If your Exchange server lives at a consumer-level ISP, it's possible that it's blocked for that reason.  E.G. http://www.spamhaus.org/pbl/
Comment: If your issue is with Outlook.com then contact them to investigate: http://smallbusiness.support.microsoft.com/en-US/contact and turn up SMTP logging in Exchange http://technet.microsoft.com/en-us/library/bb124531%28v=exchg.150%29.aspx to verbose and view those logs to see what the connection details look like while the mail is being sent to Outlook.com.
Answer: Adding this as an answer : If your mail server is getting a successful SMTP message out, and recipients aren't receiving it, you must ask the people who own the next-hop mailserver. There is literally no other way for you to find out what that mailserver did with what your server gave them. You can guess all day long, and you should (in general) follow best practices and check if you're on DNS RBLs, etc, but it's still just guessing.
Comment: I contacted the Outlook.com support. There is actually a form for that exact problem - [link](https://support.live.com/eform.aspx?productKey=edfsmsbl3&ct=eformts&wa). They contected me few hour later that the spam filter will be minigated for that IP address. The emails are now delivered to outlook.com mail boxes.
Comment: ok, I'm going to contact the MS support
Comment: Don't forget to mark an answer.
Answer: I believe that there is no issue with the exchange server. Please check for the mail whether it is being moved to Spam in outlook.com. Try adding the exchange server mail id in outlook.com contact and try re sending the mail.
If you are thinking that exchange server is prompting false message with out sending mail. The check whether you are able to ping the below server from that exchange server machine network.
Incoming mail server: pop3.live.com

Outgoing mail server (SMTP): smtp.live.com

Also try opening the below ports in firewall and check. (For verification purpose mostly not a fix)
SMTP port: 587,995

Comment: This is not a good answer at all. Any mailserver that is reporting a successful SMTP transmission when there's an actual failure to connect on the TCP port is terrible software, and I've never heard of Exchange doing it. Plus, ping is ICMP - a system can block ICMP and still allow connections on TCP 25 (SMTP), so testing via ping is less than useless, it could actually mislead you if you assume it correlates with SMTP connectivity.


Why cannot anonymous users vote, even though they have permission for it?

Question: I installed the Fivestar module and added the Stars (rated while viewing) field in a content type.
I gave to the rate content permission anonymous users. They can see all the content and the voting widget, but they can't vote. Why?
Comment: There are settings for how many times you can vote in voting API module admin/config/search/votingapi check there for the amount of time that must pass before two anonymous vote. If you are testing functionality it could be from there
Comment: So does clicking a star rating trigger some AJAX or other JS error?
Comment: @ShawnConn no nothing. i used diffchecker and the markup is identical. really strange
Answer: A possible explanation for this might be what is described in this issue on D.O: Fivestar Not Working for Anonymous Users with Cache Enabled.
A possible workaround for it is mentioned in Comment #9 of that issue, which states:

... When I set the author to anonymous on the field also set the field to allow users to vote on their own content, this appears to work as a crude work around.

Curious to hear if this somehow helps ...


How do I discover what is in the permanent generation

Question: Given a heapdump or a running VM, how do I discover what the contents of the permanent generation is ? I know about 'jmap -permstat' but that's not available on Windows.
Comment: The problem here is that the permgen (or the equivalent in other JVMs) is not exposed by the JVMTI interface, and so tools have no means to introspect it. It's a major issue with tool vendors.
Comment: please state the java version.  in earlier sun jvm's, gc was finicky about collecting classes.  also, if you get a heapdump you can guess at whether interned strings are your problem.
Comment: Not answering your question, but perhaps giving an answer to you problem - Sun JVM has a permgen, but there are other JVMs that do not suffer from this.
Answer: The permanent generation contains the class object.
So you should check the heap dump or other form of object list for classes.
If you have problem with the size of permanent generation usually it is caused by two reason:

your program or a library you use creates classes dynamically and the default size of permanent generation is too small - simple increate the size with -XX:MaxPermSize=256m
your program or a library you use creates new classes dynamically every time it is called, so the size of permanent generation increases non-stop - this is a programming error you should fix it (or search a fix/create a bug report)

To see which is your case check the size of the permanent generation over a larger period.
And a good overview about permanent generation:
http://blogs.oracle.com/jonthecollector/entry/presenting_the_permanent_generation
Comment: This reply is incomplete: we currently have an app that is leaking permgen memory and the number of loaded classes is absolutely constant. Both facts can be seen by using JConsole. We suffer from the same problem as the original poster in that we have no way to analyze the permgen in detail.
Answer: This article Memory Monitoring with Java SE 5 describes how to programmatically discover information on heap usage, memory pools (including permgen space) and so on. Its very simple:
<code>    MemoryUsage usage = ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage();
    long nonHeapFree = usage.getMax() - usage.getUsed();
    long nonHeapTotal = usage.getMax();
</code>
In my testing on OSX (Sun VM) "non heap memory usage" matches the values returned for the permgen pool closely and presumably will do something useful on VMs that don't have permgen.
Answer: See my blog post about thr permsize of Eclipse
In short the Memory Analyzer can doit, but you need the SAP JVM.
Answer: Permanent generation really only contains two kinds of things: Class definitions and interned strings. Latter very rarely gives you problems, but it is often blamed for problems. More often former is the one giving problems, due to code generation and partial hot reloading (dangling references).
Unlike name suggests, permgen does eventually get GC'ed too, just not part of regular GC cycle. Hence unreferenced interned Strings and unused classes do get cleaned up.
But permgen also does not grow dynamically which means that it is sometimes necessary to manually resize its settings for JVM start.
Answer: Do you have a specific problem to solve? The use of String.intern() is one of the typical causes for permgen problems. Additionally projects with a lot of classes also have permgen problems.
I do not know how to get into the permgen and see what it is there...
Answer: I'm looking into the same thing but due to memory constraints of an embedded platform.
Look at the code for jmap, the permstat tool is only available if the sun.jvm.hotspot.tools.HeapSummary class is available.  This class is part of the serviceability agent.  According to OpenJDK documentation (http://openjdk.java.net/groups/serviceability/svcjdk.html#bsa):
Serviceability Agent components are built as part of the standard build of the HotSpot repository. These components are:
-libsaproc.so: this is the native code component of SA.
-sa-jdi.jar: This is contains the Java classes of SA. It includes an implementation of JDI which allows JDI clients to do read-only debugging on core files and hung processes.
SA is used by jinfo, jmap, jstack
NOTE: The Serviceability Agent and the technologies that use it are not currently included in JDK releases on the Windows platforms.
Looks to be the case for Oracle JDK as well.  I'm looking to modify the jmap tool to get more info.
Answer: One technique that helped me was to use the <code>-verbose:class</code> command-line option to java, and you'll get log output telling you as classes are loaded/unloaded. Since classes are loaded to the permgen, this can help in certain circumstances.
Answer: you can use JConsole or jvisualvm.exe(with jdk 1.6 7) to find what is where. If you want to know how all of your objects are related to each other and tree of objects, then you might want to try Eclipse Memory Analyzer -- http://www.eclipse.org/mat/.
IN summary, you will get want you want from "http://www.eclipse.org/mat/".
Good luck,
Comment: I am looking specifically for which objects are in the permanent generation. These tools will not answer that question.
Comment: Hi Tom,
MAT can answer your question but you would have to use the SAP JVM, which is unfortunately at the moment a little bit difficult to get.
You would need to get NW CE from https://www.sdn.sap.com/irj/sdn/nw-ce


Can you choose the start point of an iterator in Python 3.4?

Question: Given this list:
numbers=[1, 2, 3, 4, 5]

My aim is to add these numbers one by one, and each in time doing so, I want to start adding from the  nth place, and save the result:
added=[]
num=[1,2,3,4,5]

for i in range(len(num)):
        add=itertools.accumulate([int (i) for i in num])
        added.append([i for i in add])

        num.insert(len(num),num[0])
        num.pop(0)

return added

>>>[[1, 3, 6, 10, 15], [2, 5, 9, 14, 15], [3, 7, 12, 13, 15], [4, 9, 10, 12, 15], [5, 6, 8, 11, 15]]

Each time I do this however, I also want to save from the nth position, like so:
[[1, 3, 6, 10, 15], [15, 2, 5, 9, 14], [13, 15, 3, 7, 12], [10, 12, 15, 4, 9], [6, 8, 11, 15, 5]]

The way to achieve this is quite tricky, but being able to choose the start point for i would make this procedure effortless, because no extra code (mainly other for loops) would need to be created to accommodate procedures such as this.
Just to be clear, I wish to save in the nth position, as in the second list of lists:
[[1, 3, 6, 10, 15], [2, 5, 9, 14, 15], [3, 7, 12, 13, 15], [4, 9, 10, 12, 15], [5, 6, 8, 11, 15]]
[[1, 3, 6, 10, 15], [15, 2, 5, 9, 14], [13, 15, 3, 7, 12], [10, 12, 15, 4, 9], [6, 8, 11, 15, 5]]

Thanks in advance for any help.
Comment: Is this what you want? `for i in range(start, end, step)` e.g. `for i in range(2, 10, 2)` = `2, 4, 6, 8`
Comment: Her OdraEncoded, thanks for the help, but does that work for when you want to iterate over a sequence e.g a list and when you want to choose it's start point?
Comment: If you want to rotate the iterator, try this `itertools.accumulate([num[j % len(num)] for j in range(i, i + len(num))])`
Answer: Using itertools.islice, itertools.cycle:
>>> from itertools import accumulate, islice, cycle
>>>
>>> numbers = [1, 2, 3, 4, 5]
>>> n = len(numbers)
>>> [list(accumulate(islice(cycle(numbers), i, i+n))) for i in range(n)]
[[1, 3, 6, 10, 15],
 [2, 5, 9, 14, 15],
 [3, 7, 12, 13, 15],
 [4, 9, 10, 12, 15],
 [5, 6, 8, 11, 15]]

Combining with collections.deque.rotate, you can get the final result:
>>> from collections import deque
>>> xs = [deque(accumulate(islice(cycle(numbers), i, i+n))) for i in range(n)]
>>> for i, x in enumerate(xs):
...     x.rotate(i)  # if i == 1, [1, 2, 3] become [3, 1, 2].
...
>>> [list(x) for x in xs]
[[1, 3, 6, 10, 15],
 [15, 2, 5, 9, 14],
 [13, 15, 3, 7, 12],
 [10, 12, 15, 4, 9],
 [6, 8, 11, 15, 5]]

Comment: Hey, thanks, but the real aim is to save in the nth position, which is the advantage of being able to choose the position of which i iterates from.
Comment: @user2901512, I updated the answer to include the code that yield the second list.
Comment: Bah - had almost exactly the same open in an editor - beat me to it +1
Answer: Sure:
Say you have this list (as you specified):
numbers=[1, 2, 3, 4, 5]

And you want to start from 2, then you simply do:
numbers[2:]

Answer: You can cycle the results through:
from itertools import islice, cycle, accumulate
num = [1, 2, 3, 4, 5]
added = []
for n in range(len(num)):
    added.append(list(islice(cycle(accumulate(islice(cycle(num),n,n+len(num)))),len(num)-n,2*len(num)-n)))


Subversion merge fails with "Entry for ... has no URL"

Question: I'm trying to roll back a range of commits.  Say my working copy is revision 10, and I'm wanting to roll back all changes made in revisions 4 through 7.  I'm attempting to do so with:
svn merge -r 7:4 .

This fails with:

svn: Entry for 'library' has no URL

In looking around on the SO and in the subversion manuals it sounds like this is due to a missing folder.  The suggestion I've seen to address this is to do svn cleanup then svn update prior to merging.  I've tried that and it hasn't made any difference.
Anyone have anything else I might try, or even some more insight into why it's failing?  I looked for a "verbose" option to svn but didn't find one.
Answer:
Format of merge command is clean: merge SOURCE[@REV] [TARGET_WCPATH], i.e:

you can skip target definition (because . is assumed and it's OK if you are in the root of WC), but must use source of merge

You can always test any merge using --dry-run option before real merge
You can split big reverse-merge into smaller chunks and undo one revision in command with -c -N

PS: start from p.1 and use URL of you Working Copy as source-path
Comment: Thanks but this doesn't address my question.  I understand how to *do* the merge (syntax in my question is correcct), what I don't understand is why when attempting to do so I'm seeing the error in my question, or how to fix it.
Answer: The issue turned out to be that I had local modifications to a file prior to attempting to do the merge, despite the fact that I had done an update immediately before.  I reverted the file and retried the merge, worked as expected.


Split textarea into smaller variables

Question: How can I save a textarea's information that contains more text than 4kb, in cookie's? I'm only open to Javascript, unfortunately. I can't tell the user that they can't use more than 4000 characters and set a limit is not acceptable in the situation. Tried to search through Google but it won't give me a result. Don't have to be friendly to any browser but Google Chrome.
Any ideas?
Comment: Time to explore [`localStorage`](http://stackoverflow.com/tags/local-storage/info).
Comment: What do you want to do with that 4KB text?
Comment: I want to make a text editor that can save the text you enter, meaning it most lightly will be more than 4kb, a cookies max capacity.
Comment: @Xweque Definitely use `localStorage`. The text editor's contents are not relevant in a request to the server. See also: [Are cookies fit for just client side usage?](http://stackoverflow.com/q/10413833?are-cookies-fit-for-just-client-side-usage) (scroll down a bit for non-localStorage fallbacks in older browsers).
Answer: Depending on your compatibility requirements you could use local storage. Up to 5MB if I remember correctly.
Currently, localStorage is supported by Firefox 3.5+, Safari 4+, IE8+, and Chrome
Answer: Cookies are the old, way, you should look into using localStorage.
<code>//Setting the value
var myList = document.getElementById('myToDoList');
localStorage.setItem('toDoData', myList.value);

//Reading the value
var myToDo = localStorage.getItem('toDoData');
if(myToDo){
    myList.value= myToDo;
}
</code>

Split textarea into smaller variables


addition of two negative numbers using signed 10's complement

Question: the question given was:-
(-9742)+(-641)
since we take the complement of the negative numbers, the 10's complement of first number was 258 and for the second it was 9359, but after adding both of these two complements the result is 9617 to which i further subtract by the 10000 to get -383. i wanted to know where i am going wrong because the correct answer will be -10383? is my approach wrong? if yes, then what's the correct method?
Comment: Well, to begin with, $9617-10000\neq-382$.
Comment: thanks for correction, but getting the answer of the actual question will be more appreciated .
Comment: Providing that answer would be more useful (more useful than not providing it).
Answer: Your problem is that the computation overflows when you're using only 4 digits. Even your input is out of range: Representing $-9742$ as 0258 leaves no clue that the original input was actually $-9742$ rather than $258$.
The way out of this is to use enough digits that both the inputs and the result has a sign digit at the front. With 5 digits
$$ (-9742)+(-641) = ? $$
gets represented as
$$ \mathtt{90258} + \mathtt{99359} = {}_1\mathtt{89617}$$
where the small ${}_1$ denotes a carry out that you ignore because you're working with a word lenght of 5 digits only.
Assuming there was no overflow (which there isn't in this case, though it might have been prudent to use yet another digit), the leading 8 tells us that the result is negative (if we're assuming a symmetric overflow interval this is the case when the leading digit rounds up).
We can then translate 89617 back to what it represents: $89617-100000=-10383$ as it should be.

This assumes that you're using 10s complement as a didactic tool to understand computer arithmetic, which uses 2s complement with fixed word length. If we're approaching this from a more mathmematical angle, the principled thing would be to have infinitely many digits, with numbers stretching to the left as long as the digits are eventually all 9 or eventually all 0.
(In fancier words, this corresponds to calculating with the homomorphic image of $\mathbb Z$ in the 10-adic integers).
We would then represent
$$ (-9742) + (-641) = {?} $$
as
$$ {.}{.}.9990258 + {.}{.}.999359 = {.}{.}.99989617 $$
and then we don't need to hedge stuff about overflow, because this result unambiguously represents $-10383$.
Comment: best answer in my opinion!
Comment: How to know that 89617 or any result represents a negative number and I have to again do a 10's complement to get the original number?
Answer: Let $a=9742$ and $b=641$. Then you have computed
$$
(10^4-a)+(10^4-b)=2\cdot 10^4-a-b
$$
and subtracted $10^4=10000$ to have
$$
10^4-a-b=-383
$$
If you subtract another $10^4=10000$, you should be good. Each time you have used a $10$'s complement, you have added a power of $10$. All of those powers of $10$ must be subtracted in the end.

For negative numbers though, it seems simpler to compute
$$
\begin{array}{rl}
9742&+\\
641&\\
\hline
10383
\end{array}
$$
and then simply change the sign afterwards.

Last alternative:
$$
10000-9742=258,\quad1000-641=359
$$
and
$$
258+359=617
$$
which has complement
$$
1000-617=383
$$
which yields $617-1000=-383$ from which we then still need to subtract the $10000$ from the first $10$'s complement. So you even do not have to use the same power of $10$, as long as you keep track. Here we have subtracted $1000$ and $10000$ respectively from the sum $617$ achieved using the complements with these powers of $10$ respectively.
Comment: actually the answer should come -10383.
Comment: @AmitSinha: And it does. Either way.
Comment: but why would we subtract another 10000? can you explain the reason from foundation?
Comment: @AmitSinha: My algebra shows that we have added $10^4=10000$ twice, since we have used $10$'s complement twice.
Comment: thanks for the answer, mate.


Error invoking Method 'addNewDriveToSadranTable': Internal server error [500]

Question: I have a problem with Meteor.Call and methods.
I put console.log('test') in the method code. The console shows it, and I can see new doc in the collection for a millisecond (and then it is gone).
what can be the bug?
client/sidurEditor.js
Template.sidurEditor.helpers({
    showForSadran: function() {
        return ForSadranDrives.find({},{sort: {askedDate: 1, since: 1}});
    }

lib/methods.js
Meteor.methods ({
addNewDriveToSadranTable: function (askedDate, since, until, askedDrive, askedUser) {
    console.log('click');
    ForSadranDrives.insert({
        askedDate: askedDate,
        since: since,
        until: until,
        askedDrive: askedDrive,
        driveCar: "chooseCar",
        driveCarName: "car undefined",
        driveDriver: "driver undefined",
        askedUser: askedUser,
        askedNickName: Session.get('nickName'),
        onEditDriveRow: false
    });
    console.log('click2');
} });

collection/collections.js
ForSadranDrives = new Mongo.Collection('forsadrandrives');

Comment: Session is not available on the server, so this is probably your error. Send all of the required data to the server as arguments.
Comment: @masterAM how can i send all the required data to the server as arguments?
Comment: From your client, send `askedNickName` as an argument the same way you send `askedDate`, etc.
Comment: @MasterAM
thanks!!! that solved the problem
i wrote it as the answer (you wrote me as comment)
thanks again!!
Answer: The bug was that I wrote a Session inside the method... i putted it in the Meteor.call(...) as argument and it runs great!!
thanks to @masterAM for the comment and the answer
so it look now like that:
client/navbar.js
            Meteor.call('addNewDriveToSadranTable',askedDate, since, until, askedDrive, askedUser, Session.get('nickName'));

lib/methods.js
Meteor.methods ({
addNewDriveToSadranTable: function (askedDate, since, until, askedDrive, askedUser, askedNickName) {
    console.log('click1');
    ForSadranDrives.insert({
        askedDate: askedDate,
        since: since,
        until: until,
        askedDrive: askedDrive,
        driveCar: "chooseCar",
        driveCarName: "אין רכב מוגדר",
        driveDriver: "אין נהג מוגדר",
        askedUser: askedUser,
        askedNickName: askedNickName,
        onEditDriveRow: false
    });
    console.log('click2');
}});

Answer: What you are seeing is Meteor's latency compensation - the record is inserted into the local db (minimongo), but disappears when the database refresh from the server occurs. It is most likely because your subscription to the data is either missing or your filter is exluding the data.
You can check by looking for the record in the mongo shell, with the command
meteor mongo

Make sure your cd is in the project directory
Comment: i am not sure what should i do, i put the methods outside the Meteor.isServer and Meteor.isClient
what should i add? or where should be that filter you wrote about?


Uniqueness of cyclic groups up to isomorphism.

Question: I am reading something about abstract algebra. Can anyone please tell me if the following statements are saying: a cyclic group can only be isomorphic to either $\mathbb{Z}/n\mathbb{Z}$ if it is finite or $\mathbb{Z}$ if it is infinite?
Thanks a lot.
The group $\mathbb{Z}$ is the only infinite cyclic group, up to isomorphism.
The group $\mathbb{Z}/n\mathbb{Z}$ is the only cyclic group of order $n$, up to isomorphism
Comment: That's correct.
Answer: Suppose that $G$ is a cyclic group, and let $g$ be a generator of $G$. Define a group homomorphism $\phi:\mathbb{Z}\to G$ by $\phi(n)=g^n$.
$\phi$ is surjective since $g$ generates $G$, and $\ker(\phi)$ is a subgroup of $\mathbb{Z}$, hence either $\ker(\phi)=\{0\}$ or $\ker(\phi)=n\mathbb{Z}$ for some natural number $n$.
In the first case we get $G\simeq \mathbb{Z}$, and in the second $G\simeq \mathbb{Z}/n\mathbb{Z}$.
Answer: Yes, your statement is correct with the 2 given statements in mind.
Related: Link 1
Also worth checking out (See Theorem 9.8) - Link 2
Answer: Yes, that is correct.  If a group $G$ is cyclic, then $G$ is generated by (the positive and negative powers of) a single element $a$, i.e there exists an $a \in G$ such that $G=\{a^n: n \in \mathbb{Z} \}$. If $G$ is finite, then there exists an isomorphism from $G$ to $C_n$, and if $G$ is infinite, then there exists an isomorphism from $G$ to $\mathbb{Z}$.


Security of BitLocker with no PIN from WinPE?

Question: Say you have a computer with the system drive encrypted by BitLocker and you're not using a PIN so the computer will boot up unattended. What happens if an attacker boots the system up into the Windows Preinstallation Environment? Will they have access to the encrypted drive?
Does it change if you have a TPM vs. using only a USB startup key?
What I'm trying to determine is whether the TPM / USB startup key is usable without booting from the original operating system. In other words, if you're using a USB startup key and the machine is rebooted normally then the data would still be protected unless an attacker was able to log in. But what if the hacker just boots the server into a Windows Preinstallation Environment with the USB startup key plugged in? Would they then have access to the data? Or would that require the recovery key?
Ideally the recovery key would be required when booted like this, but I haven't seen this documented anywhere.
Answer: TPM is secure because it's "watches" the boot process; when your normal Windows installation boots, it follows the "normal" boot path and TPM recognizes this and will only store/retrieve keys when this process has been followed. If you boot any other way, even just safe mode, you'll "change" that process and TPM will not "unlock".
Technically the key is stored in the TPM chip, and it's theoretically possibly to slice open this chip and get to the data. TPM is a vault like any other, it's always theoretically possible to break into a vault given enough time and resources. To publicly available knowledge, this has never happened. But this half the reason the PIN and USB Key options exist. Trying to brute-force the actual AES-256 encryption key would take a ridiculous amount of time.
If your drive only requires the USB Key, then it would be possible to use only that even from WinPE to unlock the drive.
We use BitLocker where I work. Each drive has to protectors, the TPM key and a Recovery Key that is automatically published to Active Directory. The computer starts like normal and users don't know it's encrypted except if they look. When I take the computer in to be serviced/wiped/etc I use the manage-bde command line tool in WinPE to unlock and access the drive, using the Recovery Key to unlock the drive.
Also keep in mind that the GUI doesn't present all of the available BitLocker options. The command line tool manage-bde does. For most people the GUI is good enough to get started, but the CLI tool will be necessary for advanced setups and may present you with a better understanding of the technology.
Comment: Based on your information, I played with this a bit and you're absolutely correct that when only using the USB key you can unlock the drive from the WinPE environment. It's NOT necessary to use the recovery key. I don't have a TPM so I can't verify the "watching the boot process" part, but I've heard that before so I assume you're correct on that. In the end, I suppose that's the whole point of TPM. Unfortunately there doesn't appear to be a way to add TPM to an existing machine that doesn't already have it.
Comment: Some machines can have TPM added, but it's a bit rare. I'd at least call the manufacturer to verify as the add-on modules are usually very reasonably priced.
Comment: I hoped that someone made a TPM module on a USB header that could be plugged onto a motherboard header, but I sure can't find one. It appears that TPM requires special BIOS support so it's either a feature of the motherboard or it isn't. Looking at newegg.com, it looks like TPM on the motherboard is a pretty rare option at this point. Perhaps that will change with Windows 8 and it's secure boot support?
Comment: TPM does require BIOS support. Most DIY motherboards do no have it; those MBs aren't meant for corporate America so no point in including it. It's getting hard to find a desktop/laptop system from Dell, HP, or the others that doesn't include TPM however.
Answer:
Bitlocker encrypts the data with a key , so no matter if another user boots up the environment he will not have access to the data directly . The downside is that he can try to crack the encryption because he has physical access to the hard disk (which can be partlly prevented with an usb start-up key .
As far as I know the TPM / USB key is unusable when booted from another OS without the PIN\PASSWORD .
Someone who would like access would go to the following route : a) get laptop b)get key c) get pin d)get access .
They would still need the recovery key or the PIN , unless they would try to brute force directly without the key .

I hope this helps .
Comment: I did some experimentation based on your and Chris' answers. The problem with using the USB key without TPM is that if it's present in the machine when you boot into the WinPE environment, it gives you access to the encrypted drives. So the USB startup key is sufficient access for the encrypted data regardless of knowing any account information. You DO NOT need the recovery key in this context.
Comment: Uh I didn't know that it was possible , thanks for the info!


How to perform exponential regression with more than one predictors using R

Question: Fitting exponential regression of form $y=ab^{x_1}c^{x_2}$
Here $x_1$ and $x_2$ are predictors and $y$ is dependent variable
how to calculate $a,b,c$ using R tool
Comment: Are you expecting the errors to be additive ($y=ab^{x_1}c^{x_2}+\epsilon$) or multiplicative ($y=ab^{x_1}c^{x_2}\epsilon$)?
Answer: If the model is:  log(y) ~ a + b*X1 + c*X2 with Poisson errors, .... then it would be as simple as:
glm( y ~ X1 + X2, data = dfrm, family="poisson")

You could get one kind of "additive" model with:
glm( log(y) ~ X1+X2, data=dfrm, family="gaussian")

Comment: Then look at `?nls`.
Comment: you can use `glm(y ~X1+X2, data=dfrm, family=gaussian(link="log"))`; log-transformation is not involved ...
Comment: Considering additive errors,Model that is to be fit is y=ay=ab^(x1)c^(x2) and if this equation is being log trransformed then for zeros in dataset R cannot generate equation as log(0) becomes infinity.
Comment: ... and the statistical model is actually `Y~Poisson(lambda=exp(a+b*log(X1)+c*log(X2)))` (equivalent to `lambda=exp(a)*X1^b*X2^c`), so that should be `glm(y~log(X1)+log(X2), ...)`


Hiding instance declaration from Prelude

Question: I am playing with Monoids now and wanted to define my instances of <> and mempty for a list. I wrote this:
instance Semigroup [a] where
  (<>) = (++)

instance Monoid [a] where
  mempty = []

But got an error:
Duplicate instance declarations:
     instance Monoid [a] -- Defined at newtype.hs:25:10
     instance Monoid [a] -- Defined in 'GHC.Base'

Probably, I need to add this at the beginning of file:
import Prelude hiding (???)

What should I write in place of "???"?
Comment: You can not hide instance declarations. I do not really see why you want to do that anyway, since for a list, the instances are, exactly defined as you defined these.
Comment: You can however explicitly not import the `Prelude` at all, but then you thus will not import any function of the prelude.
Comment: As @willem-van-onsem explains, you cannot hide implementations. If your goal is pedagogical, a possible viable approach is to define alternative classes Semigroup' and  Monoid', and then implement the instances.
Answer: The Haskell report says:

Instance declarations cannot be explicitly named on import or export lists. All instances in scope within a module are always exported and any import brings all instances in from the imported module. Thus, an instance declaration is in scope if and only if a chain of import declarations leads to the module containing the instance declaration.

It is thus not possible to exclude a certain instance. That being said, here it is not necessary at all to implement your Semigroup and Monoid for a list, since it is already defined. Indeed if, we inspect the source code, we see for Semigroup [src]:
-- | @since 184.108.40.206
instance Semigroup [a] where
        (<>) = (++)
        {-# INLINE (<>) #-}

        stimes = stimesList
and for Monoid [src]:
-- | @since 2.01
instance Monoid [a] where
        {-# INLINE mempty #-}
        mempty  = []
        {-# INLINE mconcat #-}
        mconcat xss = [x | xs <- xss, x <- xs]
So this is already implemented exactly the way you implemented this yourself.
It is usually considered an anti-pattern to implement an instance of a typeclass you did not implement yourself, on a data type you did not implement yourself. This is called an orphan instance [haskell-wiki]:

An orphan instance is a type class instance for class C and type T which is neither defined in the module where C is defined nor in the module where T is defined.

Usually one wraps a type into another data constructor (with newtype) to define different instances for that type for a typeclass.
Comment: I guess it was for pedagogical purpose. I also happened to have the same need: I found that re-implementing some system instances and then comparing the produced code with the system implementation is a very effective way for learning.


Firing JobService without constraints

Question: I have small problem when on some devices my notification that is no background not fires sometimes on android O (Particularly on Xiaomi). I am using Awareness API which I receive data from BroadcastReceiver .So... what I thought to do is put my notification in JobService and maybe get some of those processing time, and then call it like so:
<code>PersistableBundle bundle = new PersistableBundle();
            bundle.putString("KEY1", "Test");

            JobInfo job = new JobInfo.Builder(0, new ComponentName(context, AppNotification.class))
                    .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
                    .setExtras(bundle)
                    .build();

            JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
            jobScheduler.schedule(job);
</code>
But when I run it without
<code>.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
</code>
I recive an error "You're trying to build a job with no constraints, this is not allowed". But I do not need any constraints, and this is the one I found most likely to always work. But what is the constraints that actually always work?
How can I fire JobService without any constraints?
Answer: I am using .setOverrideDeadline(0). It basically runs the job as soon as it is scheduled and I see no harm in it. I think it is a better constraint than network as it is always satisfied, whereas it is impossible for a user to have network 100% of the time.
I have found no way to set no constraints successfully.

Firing JobService without constraints


Why do some WinAPI functions need sizes of structs passed as their parameters?

Question: For example, consider SendInput. The signature looks like this:
UINT WINAPI SendInput(
  _In_ UINT    nInputs,
  _In_ LPINPUT pInputs,
  _In_ int     cbSize
);

The documentation says:

cbSize [in] Type: int The size, in bytes, of an INPUT structure. If
  cbSize is not the size of an INPUT structure, the function fails.

Since the function already uses the INPUT structure (and probably does something with its various fields), shouldn't it be aware of the structure's size beforehand?
The only reason I can imagine is that this is some kind of odd backwards-compatibility trick to make older library binaries compatible with newer header files that may have introduced new fields at the end of the struct.
Comment: Yes, this allows for the evolution of the structure. This way, members could be added to the structure later, but the implementation can still work for older clients that didn't know about them. As one example I happen to remember off the top, see `OPENFILENAME`, and in particular the mention of `OPENFILENAME_SIZE_VERSION_400` in the documentation.
Comment: @Xearinox, what is so bad about my question?
Comment: Another example involves the [`RegisterClassEx`](https://msdn.microsoft.com/en-us/library/windows/desktop/ms633587(v=vs.85).aspx) function and the associated [`WNDCLASSEX`](https://msdn.microsoft.com/en-us/library/windows/desktop/ms633577(v=vs.85).aspx) type. With the original `RegisterClass` function, you can't set the small icon of the window. Also, `WNDCLASS` has no `cbSize` member, so you can't mix `RegisterClass` and `WNDCLASSEX` or `RegisterClassEx` and `WNDCLASS` safely. The `cbSize` member is a way to correct this in future API versions to avoid creating a `RegisterClassEx2` function.
Comment: This is worst question, what I see, -1
Answer: It's a simple form of versioning for the structures.
A later version of the API could add more fields to the end of the structure, which would change its size.  Programs written for the older version won't have set values in the newer fields and the cbSize parameter will reflect that.  That API can check cbSize and know which version of the structure it really has, and, if necessary, provide default values for the new fields.
The alternative would be to define a new structure that has a lot in common with the old structure, and then make a new API that works a lot like the old one.  That's a lot of code duplication, and it makes it harder for older programs to be recompiled using a newer SDK and continue to work.
Using a size field eliminates the need for a bunch of duplicate code.  It was a common way to do things in C, but it's less type-safe.
But it's also a little dangerous.  If the caller doesn't set the size field correctly or if the API implementation isn't very careful, this scheme could lead to access violations, reading of uninitialized fields, or writing past the end of a the structure.
Answer: Yes, this is done so Microsoft can change the INPUT structure in a future version of winapi.  From the passed cbSize, it can tell whether the program uses the old or the new version of the structure.  This is not otherwise easy to discover from the structure itself.
Passing it as an argument to the function isn't that common, they usually embed cbSize as a member of the structure.  Compare to WNDCLASSEX, MENUITEMINFO, SCROLLINFO, MSGBOXPARAMS for example.  It is just easier to do it with a single argument for functions like SendInput() and GetMouseMovePointsEx() because they take arrays of structures.
Another approach is taken for structures like LVITEM, LVCOLUMN, etcetera, they don't use a cbSize at all.  Using their api requires specifying the desired version explicitly in a manifest.
Comment: It is a separate parameter because you are passing an array of structures, and it would be annoying to have initialize the size member of every structure (and what if the sizes don't all agree?)


Get column number by cell value in Excel

Question: I'm trying to get the column number of a cell in the first row with a specific value.  The code I'm using isn't working for some reason.
Dim colNum As Integer
'sheetName is a String
With ActiveWorkbook.Sheets(sheetName)
colNum = column(.Match("ID", 1:1, 0))

It's telling me it's expecting a "list separator or )".  How do I make it work?
Thanks
Answer: Try this code:
Dim colNum As Integer
'sheetName is a String
colNum = WorksheetFunction.Match("ID", ActiveWorkbook.Sheets(sheetname).Range("1:1"), 0)

Comment: WORKING CORRECT WHAT I WANT ,,THANKS
Answer: Note that if the match is not found it will return an error; try this to handle that.
Dim Result As Variant
If Not VBA.IsError(Application.Match(...)) Then
    Result = Application.Match(...)
End If

This tries the match and if there is an error on the function it will not assign a result.
WorksheetFunction.Match Method (Excel)


Every ray from a point in the interior of a compact convex set intersects with its boundary.

Question: Let $C$ be the compact convex set of $\mathbb{R}^n$ and let $R$ be the ray, and $O$ be the initial point of $R$. Then $R \cap C$ is a line segment(!). Let the other endpoint of $R \cap C$ $P$. if $P \in \operatorname{int}(C)$ then there is $B_\epsilon(P) \subset C$ so we can extend the line segment, leading to a contradiction. So $P \in \partial C$. How can we prove (!) ?
Answer: Since both $R$ and $C$ are convex, $R\cap C$ is convex too. Besides, $O\in R\cap C$. But the only convex closed subsets of $R$ are the closed intervals of $R$. If $R\cap C=R$, then $C$ would not be compact (since $R$ is unbounded). And the only intervals of $R$ to which $O$ belongs are those that go from $O$ to a point $P\in R$.
Comment: So you are using that $R$ is homeomorphic to $[0, \infty)$ (mapping $O$ to $0$)?
Comment: I did not think in those terms, but that's a way of doing it.
Comment: In fact, the ray intersects the boundary in exactly one point.


Atualização de Dados Power BI

Question: Tenho um servidor SQL Server e um gráfico pronto.
Estou utilizando DirectQuery.
Quando entro no dashboard do power bi e mando 'atualizar agora', no histórico, consta como atualizado com sucesso. Porém, ao acessar meu gráfico (publicado na web) os mesmos não estão atualizados..
Comment: Caso voce crie um relatório novo como esses dados eles permanecem antigos , ou estão atualizados? E qual a versão do PowerBi? Na versão gratuita existem algumas limitações para atualização das informações
Comment: Quando crio um novo, os dados ficam atualizados! É a versão gratuita, de estudante.
Answer: Daniel oque está acontecendo é o seguinte.
Os dados/dashboards do powerBI podem ser trabalhados em dois formatos diferentes.
O primeiro é o DESKTOP
Nele você trabalha com o aplicativo instalado no seu PC
O segundo é o ONLINE
Voce manipula os dados aqui através da web, sem ser necessária nenhuma instalação prévia em seu PC.
No seu caso você criou seu gráfico no DESKTOP, e vinculou alguns dados do seu SQL. Após ter realizado isso você publicou o arquivo, e nesse momento tanto seu gráfico quanto seus dados (que ficam dentro do próprio arquivo do powerBI) foram para a nuvem, e ficaram disponíveis para acesso ONLINE.
Acontece que quando você clica em 'ATUALIZAR' no app Desktop ele atualiza o arquivo na sua máquina e não na web. Ou seja, para atualizar tanto o gráfico quanto os dados que você deseja será necessário novamente 'PUBLICAR' o arquivo ( substituindo assim o anterior).
Para não ter de publicar novamente toda vez que atualizar alguma coisa voce pode utilizar um item chamado 'Gateway de dados'
Segue um link explicando essa questão:
Gateway de Dados

Atualização de Dados Power BI


Problem with restoring a Blackberry configuration database on Microsoft SQL Server

Question: I am attempting to restore a Blackberry configuration database on Microsoft SQL Server 2005. The command goes like this:
restore database besmgmt-test from disk = "C:\besmgmt-test.bak"; with move "besmgmt-test" to "E:\Data\besmgmt-test.mdf", move "besmgmt-test_log" to E:\Logs\besmgmt-test.ldf"
When I try to execute it, I receive the error "Incorrect syntax near '-'."
I've figured out that it doesn't like the dashes in the database's name, because I tested it out on another database without dashes. Even tried putting quotes around the database name in the command, but still received an error.
Is there any way around this besides changing the database's name?
Answer: Try [Square-Brackets] around the name


integrate Re$z$ along the square $\{x+iy: \vert x \vert \leq 1, \vert y \vert \leq 1\}$

Question: So I need to integrate Re$z$ along the square $\{x+iy: \vert x \vert \leq 1, \vert y \vert \leq 1\}$ with counterclockwise direction.
I know Re$z$=$\frac{z+\overline{z}}{2}=\frac{x+iy+x-iy}{2}$ = $x$ so am I just breaking up the integral of $x$ along each line segment so I have
$$\oint_{\{x+iy: \vert x \vert \leq 1, \vert y \vert \leq 1\}} \text{Re}z dz = \int_{1-i}^{1+i}xdx+\int_{1+i}^{-1+i} x dx+\int_{-1+i}^{-1-i}xdx+\int_{-1-i}^{1-i}x dx$$
Does this work? Also, Am I missing a factor of $i$  as $dz = d(x+iy)=i$ ?
Also, sorry if this is a duplicate, I could not find one.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/139279/discussion-between-mymathyourmath-and-anne-bauval).
Comment: The second and fourth terms have $dz=dx$ because $dy=0$, just as you've reasoned; but the first and third terms have $dz=idy$ because $dx=0$.
Comment: so am I integrating the first and third terms w.r.t. $y$ and the second and fourth terms w.r.t. $x$? @J.G.
Comment: Yes, and correct accordingly (in each of the four pieces) your bounds and your integrand.
Comment: @AnneBauval so I have that $\oint \text{Re}z dz = \int_{1-i}^{1+i} ix dy+ \int_{1+i}^{-1+i} xdx +\int_{-1+i}^{-1-i} xi dy + \int_{-1-i}^{1-i}xdx = xi(2i)=-2x+ (\frac{x^2}{2})\bigg\vert_{1+i}^{-1+i}+...$
Comment: No. you forgot to correct the bounds of your four integrals, and the integrand in the first and third ones.
Comment: is the integrand in the first and third one just $i$ ? @AnneBauval
Comment: What is the value of the integrand, i.e. of Re(z), in these two integrals?
Answer: For further reference, the conclusion of our chat (+later correction of the LHS) was:
$$\oint_{\{x+iy: x=\pm1,y=\pm1\}} \text{Re}z dz = \int_{-1}^11idy+\int_1^{-1}xdx+\int_1^{-1}(-1)idy+\int_{-1}^1xdx\\=2i+0+2i+0=4i.$$
The final result may also be viewed as a consequence of Green's theorem:
$$\oint_{\{x+iy: x=\pm1,y=\pm1\}}xdx+xidy =\iint_{\{x+iy: \vert x \vert \leq 1, \vert y \vert \leq 1\}}\left(\frac{\partial xi}{\partial x} - \frac{\partial x}{\partial y}\right) dx\, dy\\=\iint_{\{x+iy: \vert x \vert \leq 1, \vert y \vert \leq 1\}}idx\, dy=4i.$$


SPF problems with Google Apps

Question: I currently have an SPF record with a hostname of @ that is:
v=spf1 mx ip4:x.x.x.243/32 include:_spf.google.com include:amazonses.com ~all

I also have another record of"
spf2.0/pra mx ip4:x.x.x.243/32 include:_spf.google.com include:amazonses.com ~all

We have had a lot of email being bounced back because of spam and now when I go to http://www.kitterman.com/spf/validate.html? and check the "Does my domain already have an SPF record? What is it? Is it valid?" it says no spf record exists.
However, when I send an email using our Amazon SES script and check the headers it says it passes the SPF test.
Is there something I am missing?  Do I need to place that text in quotes ""?  Any help would be greatly apprecaited.
Answer:
Do I need to place that text in quotes ""?

The missing quotes should be the problem indeed, as explained e.g. in Record Types Supported:

Unlike with most other record types, for TXT records the Data field is
  essentially free-form and may even include spaces. Please note: When
  entering a string that includes spaces, such as SPF records, you must
  enclose the string in double quotes; otherwise, individual words will
  be separately quoted and break up the record into multiple parts.

Here are the records we currently use successfully for Amazon SES as per Authenticating Your Email Address (it's indeed unfortunate that their documentation doesn't address the quoting needs):
"v=spf1 include:amazonses.com ~all"
"spf2.0/pra include:amazonses.com ~all"

Your records should simply look like so accordingly:
"v=spf1 mx ip4:x.x.x.243/32 include:_spf.google.com include:amazonses.com ~all"
"spf2.0/pra mx ip4:x.x.x.243/32 include:_spf.google.com include:amazonses.com ~all"

SPF problems with Google Apps


Copy to Clipboard in Ruby, HTML or C#

Question: How do you copy text to the clipboard in Ruby?
Sounds simple right? But I've been trying to do this for 5 days now, with no success.
I searched on internet, but all I got is how to do it in newer versions of Ruby (I'm using 1.8.7 and no I can't use a newer version).
So I tried making a HTML file to do it for me. After trying 4-5 different ways (from online guides), in 3 browsers, and even looking at Photobucket's source code to try figuring how it copies img codes, I gave up. Nothing worked for me.
So I made a C# .exe and made my Ruby program call it. Finally something is being sent to the clipboard. It's a step forward, but still, it's only the first word in a string. When I try copying two words, only two is copied.
my Ruby program looks like this:
system  ("CopyClip.exe #{text}")

and in C# (in CopyClip), it does:
Clipboard.set_text(args[0])

Basically, I don't care if you help me do it in Ruby, HTML, C#, or any other language, as long as it works.
Comment: Is your c# code using the string arguments from `Main`? Basically, the command line arguments? If there is a space in the arguments it will treat each spaced item as a different argument.
Comment: Do you know how to use gems? If yes, it may help you: https://github.com/janlelis/clipboard  (this is the 2nd link in google and looks very fine) and there is no need in c#
Answer: This answer works great for OSX:
def pbcopy(input)
 str = input.to_s
 IO.popen('pbcopy', 'w') { |f| f << str }
 str
end

def pbpaste
 `pbpaste`
end

Comment: Using `clip` instead of `pbcopy` works for copying to clipboard on Windows
Comment: This is great. I suggest everyone adds these to their `~/.irb.rb` (they have to be in a `class << self; ... end` block)
Answer: I suspect if you wrap the argument to your C# app in quotes, you'll get all the text in args[0]:
system("CopyClip.exe '#{text}'")

Alternatively, and probably better in case your text contains apostrophes or other special shell characters:
system("CopyClip.exe", text)

Or perhaps even better, use the clipboard gem - this works for me on 1.8.7, but I haven't been able to test it on Windows:
require 'clipboard'
Clipboard.copy text

Comment: I think c# / command arguments is looking for values to be wrapped in double quotes.
Answer: The clipboard gem allows you to access the clipboard on Liunx, MacOS and Windows. The focus is on simple text. You can copy a string with Clipboard.copy("string") and paste it with Clipboard.paste().
That's it, basically.
Now let's take a closer look at the specific platforms.

Linux
For Linux support, the little utility xclip is needed. You can install it on Ubuntu with sudo apt-get install xclip.
Furthermore, you can choose from which clipboard you want to paste (the default is PRIMARYCLIPBOARD). copy() copies to all the clipboards in Clipboard::CLIPBOARDS, fo example Clipboard.paste :primary.
macOS
On the macOS, it works fine.
Answer: For those writing GTK+ applications (which the OP isn't), writing to the clipboard is quite straightforward:
Gtk::Clipboard.get(Gdk::Selection::CLIPBOARD).set_text(content).store

You can also use the primary (Gdk::Selection::PRIMARY) or secondary (Gdk::Selection::SECONDARY) X selections.
See also the full ruby API and its underlying C API.
Answer: Seems like you are using windows, this works with Ruby 1.9.3 under windows 7.
For the original answer, see Ruby copy to clipboard with Fiddle
require 'open3'

module Clipboard; end

module Clipboard::Windows
  extend self

  CF_TEXT = 1
  CF_UNICODETEXT = 13
  GMEM_MOVEABLE = 2

  # get ffi function handlers
  begin
    require 'ffi'
  rescue LoadError
    raise LoadError, 'Could not load the required ffi gem, install it with: gem install ffi'
  end

  module User32
    extend FFI::Library
    ffi_lib "user32"
    ffi_convention :stdcall

    attach_function :open,  :OpenClipboard,    [ :long ], :long
    attach_function :close, :CloseClipboard,   [       ], :long
    attach_function :empty, :EmptyClipboard,   [       ], :long
    attach_function :get,   :GetClipboardData, [ :long ], :long
    attach_function :set,   :SetClipboardData, [ :long, :long ], :long
  end

  module Kernel32
    extend FFI::Library
    ffi_lib 'kernel32'
    ffi_convention :stdcall

    attach_function :lock,   :GlobalLock,   [ :long ], :pointer
    attach_function :unlock, :GlobalUnlock, [ :long ], :long
    attach_function :size,   :GlobalSize,   [ :long ], :long
    attach_function :alloc,  :GlobalAlloc,  [ :long, :long ], :long
  end

  # see http://www.codeproject.com/KB/clipboard/archerclipboard1.aspx
  def paste(_ = nil)
    ret = ""
      if 0 != User32.open( 0 )
        hclip = User32.get( CF_UNICODETEXT )
        if hclip && 0 != hclip
          pointer_to_data = Kernel32.lock( hclip )
          data = ""
          # Windows Unicode is ended by to null bytes, so get the whole string
          size = Kernel32.size( hclip )
          data << pointer_to_data.get_bytes( 0, size - 2 )
          if RUBY_VERSION >= '1.9'
            ret = data.force_encoding("UTF-16LE").encode(Encoding.default_external) # TODO catch bad encodings
          else # 1.8: fallback to simple CP850 encoding
            require 'iconv'
            utf8 = Iconv.iconv( "UTF-8", "UTF-16LE", data)[0]
            ret = Iconv.iconv( "CP850", "UTF-8", utf8)[0]
          end
        if data && 0 != data
          Kernel32.unlock( hclip )
        end
      end
      User32.close( )
    end
    ret || ""
  end

  def clear
    if 0 != User32.open( 0 )
      User32.empty( )
      User32.close( )
    end
    paste
  end

  def copy(data_to_copy)
    if ( RUBY_VERSION >= '1.9' ) && 0 != User32.open( 0 )
      User32.empty( )
      data = data_to_copy.encode("UTF-16LE") # TODO catch bad encodings
      data << 0
      handler = Kernel32.alloc( GMEM_MOVEABLE, data.bytesize )
      pointer_to_data = Kernel32.lock( handler )
      pointer_to_data.put_bytes( 0, data, 0, data.bytesize )
      Kernel32.unlock( handler )
      User32.set( CF_UNICODETEXT, handler )
      User32.close( )
    else # don't touch anything
      Open3.popen3( 'clip' ){ |input,_,_| input << data_to_copy } # depends on clip (available by default since Vista)
    end
    paste
  end
end

Clipboard::Windows.copy("test")
puts Clipboard::Windows.paste

In my collection I had another script that used to work in Windows 7 32 bit, if you have trouble with the first one and only use 32 bit, try this one
#!/usr/bin/env ruby -w
# win32 only

require 'singleton'
require 'thread'
require 'Win32API'

class Clipboard
  include Singleton

  CF_TEXT = 1

  def initialize
    @@mutex = Mutex.new
    @@open = Win32API.new("user32","OpenClipboard",['L'],'L')
    @@close = Win32API.new("user32","CloseClipboard",[],'L')
    @@empty = Win32API.new("user32","EmptyClipboard",[],'L')
    @@set = Win32API.new("user32","SetClipboardData",['L','P'],'L')
    @@get = Win32API.new("user32", "GetClipboardData", ['L'], 'L')
    @@lock = Win32API.new("kernel32", "GlobalLock", ['L'], 'P')
    @@unlock = Win32API.new("kernel32", "GlobalUnlock", ['L'], 'L')
  end

  def copy
    @@mutex.synchronize do
      @@open.Call(0)
      str = @@lock.Call(@@get.Call(CF_TEXT))
      @@unlock.Call(@@get.Call(CF_TEXT))
      @@close.Call
      return str
    end
  end

  def paste(str)
    @@mutex.synchronize do
      @@open.Call(0)
      @@empty.Call
      @@set.Call(CF_TEXT, str)
      @@close.Call
      @@lock = Win32API.new("kernel32", "GlobalLock", ['L'], 'P')
      @@unlock = Win32API.new("kernel32", "GlobalUnlock", ['L'], 'L')
      return nil
    end
  end
end

clip = Clipboard.instance
puts clip.copy
puts str
clip.paste("foo")
puts clip.copy

If you don't mind to install a gem, here is a much simpler solution, works on windows7 64 bit, Ruby 1.9.3.
#gem install clipboard
require 'clipboard'

Clipboard.copy("This is a sentence that has been copied to your clipboard")
puts Clipboard.paste

Copy to Clipboard in Ruby, HTML or C#


Taylor series evaluation

Question: I have the following Taylor series and I don't know how to get to the correct answer. The series is:

$$ \sum_{n=0}^{\infty}p\frac{i^nt^n}{n!},~~p \in \mathbb{R} $$

My reasoning is:
$$ \sum_{n=0}^{\infty}p\frac{i^nt^n}{n!} = p\sum_{n=0}^{\infty}\frac{(it)^n}{n!} = pe^{it} $$
$~$
However, the correct answer is $(1 - p) + pe^{it}$. Would someone please show the correct way of evaluating this series? Thanks.
Edit: Adding Context

Let $X$ be a discrete random variable, all whose moments are given by $E(X^k) = p$, $k = 1, 2, ...$, where $0 < p < 1$. Find the characteristic function of $X$.

My solution:
$$ \varphi_X(t) = \sum_{n=0}^{\infty} \varphi_X^{(n)}(0)\frac{t^n}{n!} = \sum_{n=0}^{\infty}i^nE(X^n)\frac{t^n}{n!} = \sum_{n=0}^{\infty}i^np\frac{t^n}{n!} $$
Comment: The whole term $1-p$ serves to convert the first term of the series for $pe^{it}$ i.e. $p$ into $1$ as it must be.
Comment: The error is in the last step of your procedure from the probability problem: you have $E[X^0]=1$, not $p$.
Comment: @Ian and where would the $-p$ come from?
Comment: They have not given you $E(X^0)$. This has to be $1$ and so your series should have been the one I suggested.
Comment: @Ian thanks. Got it.
Answer: Your answer is correct.
The book answer you give is for the sum $$1+\sum_{n=1}^{\infty}p\frac{i^nt^n}{n!}.$$
Is there something before this summation which could explain this?
Comment: I added context.

Taylor series evaluation


Quais são os benefícios de se usar HTTPS?

Question: Onde eu trabalho, o pessoal sempre costuma comentar que tem que colocar HTTPS nos sistemas para ele ficar mais seguro.
Eu gostaria de saber:

Em quê o SSL torna mais seguro um site?

Quais são os tipos de ataques que eles evitam?

Na implementação de um SSL, existe alguma relação de segurança contra alguns tipos de ataque como CSRF por exemplo?
Comment: @bigown Embora estejamos usando os comentários para chat offtopic, eu devo dizer que a sua reputação reflete muito mais do que apenas dedicação, reflete também qualidade, expertise, competência técnica e de comunicação comprovada. E se você for alguém medíocre no site, então isso significaria que não haveria ninguém que seja bom aqui (o que não é verdade). Pode ter certeza que ninguém em sã consciência te considera medíocre por aqui e as suas contribuições são de um altíssimo nível de excelência muito difícil de ser alcançado.
Comment: Não, o fato de eu responder bastante e ter reputação alta, não dá para me comparar com o Jon Skeet que tem competência técnica e capacidade de comunicação comprovada. Minha reputação só reflete a dedicação ao *site*, nada mais que isto. Me considero um profissional medíocre e invejo os usuários daqui que dominam muitas coisas melhor que eu. E não é falsa modéstia, até porque eu não tenho essa qualidade/defeito :P É só constatação da realidade. No máximo sou a sujeira debaixo da unha do Jon Skeet :)
Comment: @bigown Não é todo dia que consigo ser mais rápido que o Jon Skeet brasileiro. :D
Comment: O cara é humilde :)
Comment: Eu estava respondendo mas como você já está satisfeito com a resposta dada nem preciso postar mais nada.
Comment: @Victor E cadê ele? :P
Comment: @bigown Adivinha? Dica: é o cara que tem a maior reputação do site e é conhecido pelo seu olho.
Answer:
Em quê o SSL torna mais seguro um site?

Criptografia. No HTTP normal, os dados são enviados em plaintext dentro dos pacotes de rede e alguém que estiver usando um sniffer, que é um programa que captura os pacotes, poderá ver o conteúdo deles.
No entanto, se o conteúdo dos dados que trafegam na sua conexão forem de importante confidencialidade (ex: dados bancários, e-mails pessoais, etc), o SSL* lhe provê uma criptografia forte e muito difícil de ser quebrada** (e o HTTPS nada mais é do que o HTTP sobre o SSL). Desta forma se alguém inspecionar os seus pacotes de dados sem conhecer as chaves criptográficas usadas, o conteúdo consistirá apenas de uma sequência de bytes aparentemente aleatória e sem sentido.

Quais são os tipos de ataques que eles evitam?

Principalmente ataques baseados em interceptação de dados. Se os pacotes forem interceptados, para quem não tiver conhecimento das chaves criptográficas usadas, o conteúdo deles não fará nenhum sentido.
Além disso, sem o SSL, alguém poderia maliciosamente alterar o conteúdo dos pacotes entre a origem e o destino, afinal eles transitam em plaintext, sem criptografia. Com o SSL, isso torna-se praticamente impossível, pois sem ter as chaves criptográficas não dá para introduzir alterações significativas no pacote sem fazer com que ele pareça estar simplesmente corrompido (sendo então descartado por completo). O máximo que um atacante conseguirá com isso é destruir os pacotes, e não modificá-los.

Na implementação de um SSL, existe alguma relação de segurança contra alguns tipos de ataque como CSRF por exemplo?

Não. Isso daí ja é algo que deve ser implementado pela aplicação, não é responsabilidade da camada de transporte (que é aonde o SSL está).

(*) - O SSL (Secure Sockets Layer) foi substituído pelo TLS (Transport Layer Security), mas isso daí é um detalhe irrelevante para a sua pergunta. O SSL teve três versões: 1.0, 2.0 e 3.0. E depois veio o TLS 1.0, 1.1, 1.2 e o 1.3 está sendo projetado. Na prática o TLS 1.0 nada mais é do que um SSL 3.1 que decidiram mudar de nome para padronizá-lo com a IETF (Internet Engineering Task Force).
(**) - Na realidade o SSL permite que ambas as partes negociem qual protocolo criptográfico será usado de fato, e se ambos concordarem com um protocolo fraco então a segurança não estará assegurada. Por isso é importante configurar o servidor para rejeitar cipher suites inseguras, muitas delas habilitadas por padrão na instalação. O ssllabs possui ferramentas interessantes para testar o servidor e o navegador.
Agradeço ao Omni e ao mgibsonbr pelas sugestões dadas em seus comentários.
Comment: a versao informal do TLS1.0 e SSL3.1 e nao SSL4.0. Gostei da sua nota, mas acrescentaria a razão da troca de nome (standardização do protocolo pela IETF)
Comment: @Omni Feito. :)
Answer: São dois grandes benefícios:

todos os dados trafegados por este protocolo são criptografados, então tem pouca utilidade se alguém interceptar os pacotes entre o cliente e o servidor. Isto é feito de forma transparente, sua aplicação não precisa saber lidar com a criptografia.
ele fornece uma identificação confiável dos agentes envolvidos na comunicação impedindo que dados sejam alterados no meio do caminho após as duas pontas concordarem que vão se comunicar de forma segura (hand shaking).

Então ele é útil para garantir a autenticidade e integridade do dado transportado.
Além disto para usar o HTTPS é preciso ter um certificado. Se ele for obtido por uma autoridade certificadora confiável a identidade do servidor pode ser comprovada. Isto não é uma ganho direto, mas é importante. Em tese, isto deveria prevenir alguns ataques sociais, mas as pessoas não colaboram.
Ataques feitos à aplicação como o CSRF ou XSS não serão prevenidos já que estamos falando um protocolo de transporte. Ele previne ataques como o Man in the Middle (só um exemplo). Qualquer ataque que tente se beneficiar dos dados transportados são prevenidos com o HTTPS.
O uso deste protocolo não diminui em nada a necessidade de cuidado para desenvolver a aplicação ou de manter o servidor seguro, afinal se um invasor se apoderar do seu servidor de nada adiantará a comunicação estar segura. Ele não previne ataques de negação de serviço
Tentei dar mais algumas informações relevantes
Coloquei no GitHub para referência futura.


State 2 values of $x$ for which the value of $3x^2+4x-14$ is a perfect square.

Question:
State 2 values of $x$ for which the value of $3x^2+4x-14$ is a perfect square.

I can't seem to factor it and I'm really lost. Does using the quadratic equation for it work? Help I need it for grade 10 quadratics test.
Comment: The quadratic formula is indeed a way to solve this. You want this polynomial to be a perfect square at $x$, so you want $$3x^2+4x-14=n^2\iff 3x^2+4x-(14+n^2)=0$$for some $n\in\Bbb N$.
Comment: Note, if you consider $0$ a perfect square, you just find the two roots of this polynomial and you're done.
Answer: $$(1)\quad3x^2+4x-14=a^2$$ $$\implies 3x^2+4x-(14+a^2)=0\implies x=\dfrac{-4\pm\sqrt{16-12(-14-a^2)}}{6}$$
This does not need to be an integer. This says that for $(1)$ to be true, just choose an $a$ here and it will give you an $x$ value that satisfies. For example, $a=1$: $$x=\dfrac{-4\pm\sqrt{16-12(-15)}}{6}=\dfrac{-4\pm\sqrt{196}}{6}=\frac{10}{6},-3$$
Plugging either one of these values into the original equation will give you $a=1$.
Answer: $$3x^2+4x-14=n^2\\x=\frac{-4\pm\sqrt{16+12(14+n^2)}}{6}=-\frac23\pm\frac13\sqrt{46+3n^2}$$
Setting $n=1$ gives a nice value for the square root: $7$. In this case, you get $x=-3,\frac53$ as two values of $x$ for which your quadratic gives a square number, namely $1$, as the value.
This choice of $n$ is not unique, you could have chosen any natural number. This is just the simplest one.
Answer: I AM ASSUMING THAT THE QUESTION IS ASKING FOR $x$ an integer.
I finished up. There are a two-ended sequence of positive $x$ values (integers) that work, the linear recurrence can be used in either direction,
$$ x_{n+2} = 14 x_{n+1} - x_n + 8,  $$ all positive are
$$ ...,  8853,  635, 45,3,  5, 75, 1053, 14675,...$$
The double ended sequence of negative $x$ values is
$$  ... -33043, -2373, -171, -13, -3, -21, -283, -3933, -54771,...  $$
Together these are ALL integer $x$ values.
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
This becomes a Pell type equation,
$$  (3x+2)^2 - 3 y^2 = 46. $$
By nature, there are answers both with positive $x$ and negative $x.$
If you prefer positive $x,$ there are two infinite sequences. One is
$$  3, 45, 635, 8853, ... $$
with
$$ x_{n+2} = 14 x_{n+1} - x_n + 8.  $$
For this one the results of $3x^2 + 4 x - 14$ are $y^2,$ with $y$ in
$$ 5, 79, 1101, 15335,... $$  and
$$ y_{n+2} = 14 y_{n+1} - y_n .  $$
The other positive sequence is
$$  5, 75, 1053, 14675,...  $$
also with
$$ x_{n+2} = 14 x_{n+1} - x_n + 8.  $$
For this one the results of $3x^2 + 4 x - 14$ are $y^2,$ with $y$ in
$$ 9, 131, 1825, 25419... $$
 and
$$ y_{n+2} = 14 y_{n+1} - y_n .  $$
=====================================================================================
jagy@phobeusjunior:~$ ./Pell_Target_Fundamental
  Automorphism matrix:
    2   3
    1   2
  Automorphism backwards:
    2   -3
    -1   2

  2^2 - 3 1^2 = 1

 w^2 - 3 v^2 = 46

Sat Dec  2 10:20:49 PST 2017

w:  7  v:  1  SEED   KEEP +-
w:  11  v:  5  SEED   BACK ONE STEP  7 ,  -1
w:  17  v:  9
w:  37  v:  21
w:  61  v:  35
w:  137  v:  79
w:  227  v:  131
w:  511  v:  295
w:  847  v:  489
w:  1907  v:  1101
w:  3161  v:  1825
w:  7117  v:  4109
w:  11797  v:  6811
w:  26561  v:  15335
w:  44027  v:  25419
w:  99127  v:  57231
w:  164311  v:  94865
w:  369947  v:  213589
w:  613217  v:  354041
w:  1380661  v:  797125
w:  2288557  v:  1321299
w:  5152697  v:  2974911
w:  8541011  v:  4931155
w:  19230127  v:  11102519
w:  31875487  v:  18403321

Sat Dec  2 10:21:49 PST 2017

 w^2 - 3 v^2 = 46

In this one I told it to show the  positive $x$ when the left hand number in the line is $2 \pmod 3,$ otherwise give $x$ negative.
Sat Dec  2 15:38:39 PST 2017
                   7                  -3                   1
                  11                   3                   5
                  17                   5                   9
                  37                 -13                  21
                  61                 -21                  35
                 137                  45                  79
                 227                  75                 131
                 511                -171                 295
                 847                -283                 489
                1907                 635                1101
                3161                1053                1825
                7117               -2373                4109
               11797               -3933                6811
               26561                8853               15335
               44027               14675               25419
               99127              -33043               57231
              164311              -54771               94865
              369947              123315              213589
              613217              204405              354041
             1380661             -460221              797125
             2288557             -762853             1321299
             5152697             1717565             2974911
             8541011             2847003             4931155
            19230127            -6410043            11102519
            31875487           -10625163            18403321
Sat Dec  2 15:39:02 PST 2017

Answer: 3x^2+4x-14=0.
Let q and w be 2 roots of the equation.
q+w=4,qw=-42
(q-w)^2=(q+w)^2-4qw
So q-w=√184=2√46
On solving q+w=4and q-w=2√46
We get w=q={4+2√46}÷\2
Now put the value of w andq and solve it.on verifying q+w is not equal with 4 . slight deviations will come as we have taken imaginary roots.


Restrict node list in entity reference field based on node field

Question: My "Article" nodes have a "domain" field that links to a taxonomy term.
My "Article" nodes also have a repeatable "entity reference" field "more like this" that links to other "article" nodes.
How can i restrict the list in the "more like this" field to show only the nodes that have the same "taxonomy term" that the node i am currently editing ?
Thanks a lot !
Comment: Do you need a programming (PHP) or Views-Config solution?
Comment: It doesn't matter to me. maybe a PHP version could be more configurable for future use case ... but i'm open to anything :)
Answer: For the PHP solution you have to provide an EntityReferenceSelection Plugin. I give you an example from my "proreos" project:
<code>namespace Drupal\proreos\Plugin\EntityReferenceSelection;

use Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection
...

/**
 * Plugin implementation of the 'selection' entity_reference.
 *
 * @EntityReferenceSelection(
    *   id = "default:proreos",
    *   label = @Translation("proreos selection"),
    *   entity_types = {"address_entity", "anwalt_entity", "library_entity"},
    *   group = "default",
    *   weight = 1
    * )
    */
class OwnEntitiesSelection extends DefaultSelection {

  protected function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {
      $query = parent::buildEntityQuery($match, $match_operator);
      ... your code here to modify the query ...
      ... (I do $query->condition('user_id', $currentUid);) ...
      return $query;
   }}
</code>
You may also need to override validateReferenceableNewEntities().
Look for more examples in the core modules.
Comment: Hello, seems to be exactly  what i am looking for, unfortunately i can't make it work.
I created a plugin "node_domain" and put src/Plugin/EntityReferenceSelection/NodeDomainSelection.php with a class  NodeDomainSelection extends DefaultSelection   but this file seems to never be loaded (plugin is activated, cache cleared, ...) any clue on how to delcare it properly ?
Comment: Hm, there is nothing special about it. Have your module activated? Have the correct annotation (@EntityReferenceSelection), have the correct psr path (src/Plugin/EntityReferenceSelection). Should work. What do you mean by "I created a plugin"? Is this a module?
Comment: Check out this known bug: https://www.drupal.org/project/drupal/issues/2743773


Make sure that string follows the required format

Question: I am attempting to check if a string follows a certain format by checking that:

item[]= is repeated four times
item[]= is followed by a number and & symbol (e.g item[]=2&), except the last number doesn't have & after it
The numbers after item[]= consist of only either 1-4 and can be in any order, but not repeated

Here are a few examples of how the string would look (as you can see, the order of the number changes) - note that there will only be one string at a time!
1)
$list = 'item[]=1&item[]=3&item[]=2&item[]=4';

2)
$list = 'item[]=3&item[]=1&item[]=4&item[]=2';

3)
$list = 'item[]=4&item[]=3&item[]=2&item[]=1';

This is how far I've got:
// check item[]= is repeated four times
if(substr_count($list, "item[]=") == '4') {

   // strip the string to only numbers, then will need to check each number if between 1-4
   $numbers = preg_replace("/[^0-9]/","",$list);

   // strip the string to only numbers and the character after it, will need to ensure it is & (except for the last number)
   preg_replace("/[^0-9]/","",$list + 1);

}

Comment: So you've completely ignored my suggestions from when you asked this earlier today?
Comment: @MarkBaker Hi Mark, I did point out that after you had posted your comment, I realised that I had missed some of the criteria out from my question.
Comment: And you aren't familiar with PHP's max() and min() functions: `parse_str($list, $output); if (isset($output['item']) && count($output['item']) == 4 && count(array_unique($output['item'])) == 4 && min($output['item']) == 1 && max($output['item']) == 4) { echo 'All OK!'; }`
Answer: You can use:
$list    = 'item[]=1&item[]=3&item[]=2&item[]=4';
$pattern = "/^(item\[\]=[1-4])(&(item\[\]=[1-4])){3}$/";

if (preg_match($pattern, $list)) {
    // check for repetition
    $matches = [];
    preg_match_all("/\d+/", $list, $matches);

    if (count(array_count_values($matches[0])) == 4) {
        // All are unique values
        echo 'All conditions met';
    }
}

Comment: 1-4 and can be in any order, **but not repeated**
Comment: Hello, seem to get this error `preg_match_all(): Delimiter must not be alphanumeric or backslash -- at line 9`
Comment: @TheCodesee Sorry, forgot to include `/`. Updated answer
Comment: @Jomoos That's alright, but your code isn't displaying 'All conditions met'
Comment: @TheCodesee Updated
Comment: @TheCodesee Try using `([1-9]|10|11|12)` instead of `[1-12]`
Comment: @TheCodesee `$pattern = "/^(item\[\]=([1-9]|10|11|12))(&(item\[\]=([1-9]|10|11|12))){11}$/";`
Comment: May I ask what `{3}` did and now `{11}` does?
Comment: @TheCodesee `{11}` tells `(&(item\[\]=([1-9]|10|11|12)))` has to be repeated `11` times. [See this](http://www.regular-expressions.info/repeat.html)
Comment: If I had `(&(item\[\]=([1-9]|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31|32|33)))` would `{11}` stay the same, or have to be changed?


Aspas dentro de aspas (html, php)

Question: Tenho um código html e gostaria de colocar na tag  que está dentro do evento onclick de um botão, o endereço que ela deve ir após o click em "SIM", porém acho que estou errando na hora de colocar as aspas. Ao invés dele criar o botão com a notificação correta, é isso que está acontecendo com o botão.

Como corrigir para que redirecione dentro deste onclick? Segue código html abaixo.

                                                        <button class="btn btn-danger btn" id="excluir" onclick="return toastr.warning('Deseja realmente excluir o produto <?= $value['nome_ProdutosEmpresa'];?>?

<a href="<?= base_url('produtos/atualizar/' . $value['id']) ;?>">SIM')">

</button>
Comment: Pergunta besta: por que colocar tudo isso direto no `onclick` do elemento ao invés de definir uma função no JS e apenas executá-la no clique?
Comment: Obrigado pela ajuda... se estou perguntando dessa maneira é pq quero entender o que estou errando, sei que posso usar da maneira que você comentou, mas minha pergunta não foi essa, abraços
Answer: Na hora de definir o href, falta um ponto após o $value['id'], consigo notar inicialmente apenas esse erro.
 <button class="btn btn-danger btn" id="excluir" onclick="return toastr.warning('Deseja realmente excluir o produto <?= $value['nome_ProdutosEmpresa'];?>?

<a href="<?= base_url('produtos/atualizar/' . $value['id'] .'') ;?>">SIM')">

</button>

Aspas dentro de aspas (html, php)


Question mark (?) in XML attributes for Android

Question: Can anyone explain the question mark means in Android XML attributes?
<TextView
    style="?android:attr/windowTitleStyle"
    More attributes
/>

Answer: The question mark means it's a reference to a resource value in the currently applied theme. See the linuxtopia Android Dev Guide or the android.com Dev Guide for more about it.
\? escapes the question mark.
Comment: Dev Guide articles have been restructured, this is the new direct link: http://developer.android.com/guide/topics/resources/accessing-resources.html#ReferencesToThemeAttributes
Comment: I think it makes the most sense when considering multiple themes containing the same custom resource attribute. Say you have movie-related themes like MyThemeTransformers and MyThemeHobbit, and both have an attribute called movieIcon.  And movieIcon points to a @drawable resource, say a robot or a hobbit image, in each theme definition. You can refer to "?attr/movieIcon" anywhere the theme is in effect (like in a toolbar or dialog or whatever kind of View layout), and it will automatically point to the correct drawable when you switch between themes. I hope that helps.
Comment: I think it would be better to point your second link to: http://developer.android.com/guide/topics/resources/resources-i18n.html#ReferencesToThemeAttributes
Comment: I think it's more appropriate to say ? is used to "Referencing style attributes" rather than "reference to a resource value in the currently applied theme". According to android.com dev guide link you provided.
Comment: @DevonBiere it helped! It'd be great if you submit your comment as an answer.
Comment: I am still confused, even after reading the two links provided. What does  "reference to a resource value in the currently applied theme" mean exactly? Isn't a resource referenced with '@' taken from the current theme too? (for instance, @android:color/black)
Comment: @Tiago: The at sign (@) is required when you're referring to any resource object from XML.  It's not specific to themes.
Answer: The ? lets you refer to a style attribute instead of a specific hard-coded resource. See "Referencing style attributes" in the Android Dev Guide for details.
So, how is this actually useful?  It makes the most sense when considering multiple themes containing the same custom resource attribute.
Say you have movie-related themes like MyThemeTransformers and MyThemeHobbit, and both have an attribute called movieIcon. And that movieIcon attribute points to a different @drawable resource, say robot.png or hobbit.png, in each theme definition.
You can refer to "?attr/movieIcon" anywhere the theme is in effect (like in a toolbar or dialog or whatever kind of View layout), and it will automatically point to the correct drawable when you switch between themes.  You don't need any theme-dependent logic to use the different drawables. You just define the movieIcon attribute for each theme and the Android framework takes care of the rest.


How do I pass an array to a constructor?

Question: I want to pass an array to a constructor, but only the first value is passed--the rest looks like garbage.
Here's a simplified version of what I'm working on:
#include <iostream>

class board
{
    public:
        int state[64];
        board(int arr[])
        {
            *state = *arr;
        }
        void print();
};

void board::print()
{
    for (int y=0; y<8; y++)
    {
        for (int x=0; x<8; x++)
            std::cout << state[x + y*8] << " ";
        std::cout << "\n";
    }
}

int main()
{
    int test[64] = {
        0, 1, 2, 3, 4, 5, 6, 7,
        1, 2, 3, 4, 5, 6, 7, 8,
        2, 3, 4, 5, 6, 7, 8, 9,
        3, 4, 5, 6, 7, 8, 9,10,
        4, 5, 6, 7, 8, 9,10,11,
        5, 6, 7, 8, 9,10,11,12,
        6, 7, 8, 9,10,11,12,13,
        7, 8, 9,10,11,12,13,14 };

    board b(test);
    b.print();

    std::cin.get();
    return 0;
}

Can someone explain why this doesn't work and how to properly pass an array? Also, I don't want to copy the array. (And do I really have to indent every line by 4 spaces for code? That's pretty tedious.)
Comment: int (arr&)[64] is the type of your array, and arrays cant be copied.  Easiest to just use std::array
Comment: about the indentation, the IDE usually does this for you.
Comment: About the indentation - you don't need to manually do it for each line separately. Highlight the code and press the button above the edit box that has a pair of braces - `{}` - on it.
Comment: @Default: Yeah, I realized that I just had to go into my IDE, select all, hit tab, and then it's all formatted for this site. Silly me.
Comment: @Michael Burr: Thanks. I'll try that method next time.
Answer: In this case it might be best to use a reference to the array:
class board
{
    int (&state)[64];

public:
    board(int (&arr)[64])
        : state(arr)
    {}

    // initialize use a pointer to an array
    board(int (*p)[64])
        : state(*p)
    {}

    void print();
};

A couple of advantages - no copying of the array, and the compiler will enforce that the correct size array is passed in.
The drawbacks are that the array you initialize the board object with needs to live at least as long as the object and any changes made to the array outside of the object are 'reflected' into the object's state.  but those drawbacks occur if you use a pointer to the original array as well (basically, only copying the array will eliminate those drawbacks).
One additional drawback is that you can't create the object using a pointer to an array element (which is what array function parameters 'decay' to if the array size isn't provided in the parameter's declaration). For example, if the array is passed through a function parameter that's really a pointer, and you want that function to be able to create a board object referring to that array.
Comment: @Svad: the reference is just an alias for the object it's initialized with. The reference has no effect on that object's lifetime.  If you need the `board` object to live longer than the array used to initialize it, then I'd suggest copying the array (which you indicated several times you didn't want to do).  An alternative might be to use `shared_ptr` to manage the array's lifetime; for that you'd need to  create the array in dynamic memory somehow.
Comment: This works! Thank you. How does this compare with vvnraman's solution?

Also, can you explain what `: state(arr)` does?
Comment: `state(arr)` initializes the reference to the array that's passed as the constructor parameter.
Comment: Can someone explain why the array is bound to `test` and is thus destroyed when it goes out of scope? If two variables are pointing to the same array, why does one have precedence over the other?
Comment: I don't want to copy because I plan to make a very large number of board objects, and copying an array every time would be costly.

So it seems I need to allocate memory. Avram mentioned `new` in another response. I'll also look into `shared_ptr`. Thanks for the explanation and advice.
Answer: Attempting to pass an array to a function results in passing a pointer to the first element of the array.
You can't assign arrays, and taking a parameter like T[] is the same as T*. So
*state = *arr;

Is dereferencing the pointers to state and arr and assigning the first element of arr to the first element of state.
If what you want to do is copy the values from one array to another, you can use std::copy:
std::copy(arr, arr + 64, state); // this assumes that the array size will
                                 // ALWAYS be 64

Alternatively, you should look at std::array<int>, which behaves exactly like you were assuming arrays behave:
#include <array>
#include <algorithm>
#include <iostream>

class board
{
    public:
        std::array<int, 64> state;

        board(const std::array<int, 64> arr) // or initialiser list : state(arr)
        {
            state = arr; // we can assign std::arrays
        }
        void print();
};

void board::print()
{
    for (int y=0; y<8; y++)
    {
        for (int x=0; x<8; x++)
            std::cout << state[x + y*8] << " ";
        std::cout << "\n";
    }
}

int main()
{
    // using this array to initialise the std::array 'test' below
    int arr[] = {
        0, 1, 2, 3, 4, 5, 6, 7,
        1, 2, 3, 4, 5, 6, 7, 8,
        2, 3, 4, 5, 6, 7, 8, 9,
        3, 4, 5, 6, 7, 8, 9,10,
        4, 5, 6, 7, 8, 9,10,11,
        5, 6, 7, 8, 9,10,11,12,
        6, 7, 8, 9,10,11,12,13,
        7, 8, 9,10,11,12,13,14 };

    std::array<int, 64> test(std::begin(arr), std::end(arr));

    board b(test);
    b.print();

    std::cin.get();
    return 0;
}

Comment: @SvadHisthana nope, you cannot pass a real array by value in C++. You can pass an array by reference though (and that only helps to figure out the size of it) but that's it.
Comment: Thank you. That explains why I'm only getting the first value.

I don't want to copy the array, however. Nor do I want to use vectors. Surely there's a way to properly pass an array?
Comment: I wasn't intending to pass by value. vvnraman's solution is what I was going for. Sorry if I didn't phrase my question better. Thanks for your help!
Comment: @SethCarnegie: You have reversed the `std::copy` arguments. They are: `std::copy(first, last, output)`.
Comment: @ChristianAmmer thanks, fixed. Feel free to edit my posts for silly mistakes like that.
Comment: Do note that you can get rid of `arr` in your code.  Since `std::array` is an aggregate you can initialize it like you do a regular array.  This cuts out a step.
Answer: #include <iostream>

class board
{
    public:
        int * state;    //changed here, you can also use **state
        board(int *arr)               //changed here
        {
          state = arr;
        }
        void print();
};

void board::print()
{
    for (int y=0; y<8; y++)
    {
        for (int x=0; x<8; x++)
            std::cout << *(state + x + y*8) << " ";   //changed here
        std::cout << "\n";
    }
}

int main()
{
    int test[64] = {
        0, 1, 2, 3, 4, 5, 6, 7,
        1, 2, 3, 4, 5, 6, 7, 8,
        2, 3, 4, 5, 6, 7, 8, 9,
        3, 4, 5, 6, 7, 8, 9,10,
        4, 5, 6, 7, 8, 9,10,11,
        5, 6, 7, 8, 9,10,11,12,
        6, 7, 8, 9,10,11,12,13,
        7, 8, 9,10,11,12,13,14 };

    board b(test);
    b.print();

    std::cin.get();
    return 0;
}

or you can use it as:
class board
{
    public:
        int state[64];
        board(int arr[])
        {
            for(int i=0;i<64;++i)
               state[i] = arr[i];
        }
        void print();
};

EDIT 1:
stable solution
class board
    {
        public:
            int * state;    //changed here, you can also use **state
            board(int *arr)               //changed here
            {
              state = new int[64];
              for(int i=0;i<64;++i)
                   state[i] = arr[i];
            }
            void print();
    };

Comment: Your first example doesn't compile. You can't initialize a member outside a function using new(). A second issue is that the constructor doesn't copy the contents of the array into the allocated block of memory. It just re-assigns the pointer to point to the array passed into the constructor. This would work in your example code, but in a real program, that memory would become invalid as soon as the array test goes out of scope. The memory allocated and assigned to state would just be leaked.
Comment: Thank you. Though when I tried compiling your first solution, I received an error for line 6: "only static const integral data members can be initialized within a class"

vvnraman's solution seems to be working.
Comment: which is the line? i cant find any assignment of class members outside constructor
Comment: oh sorry i didnt see it was outside constructor. yeah you can assign memory inside the constructor and copy array contents to avoid out of scope issues.
Answer: *state = *arr; is using dereferencing, which returns the value at the address of the pointer.
This is the same as state[0] = *arr; because *arr is an int.
See this article for info on pointers. See the deference section.
To solve this problem you want to do this:
for (int i = 0; i < 64; i++) state[i] = arr[i]

Comment: Thank you.
However, my program won't compile if I try to change `*state = *arr;` to `state = arr;` I get an error for state saying "expression must be a modifiable lvalue".
Comment: @SvadHisthana See the last line, it will do it for you
Comment: Thank you, but I don't want to copy the array. vvnraman's solution seems to be working for me.
Comment: But you might have scope problems in a bigger program. ie if you orginal array goes out of scope
Comment: Beware. That solution will work in this case. However, test is a local variable and a pointer to it won't be valid after the function returns. Of course when main returns the program is done, but you can run into trouble if test wasn't from main. It's a poor design decision to allow this to happen.
Comment: @SvadHisthana Just be careful of the drawbacks if you just copy the pointer, as commented by Seth Carnegie on vvnraman's answer.
Comment: @Avram: Is there any way to keep the array alive independently of `test` without copying it? I guess I don't understand why the array is destroyed when `test` goes out of scope even if another variable is pointing to the array. Can I just make `test` point to something else, or does that affect `state`?
Comment: Short answer, no. The thing with a pointer is that it is little more than an int and its value is a memory address. So just like a variable int i in a function is gone when that function ends, so to test is gone when main ends. And just because some pointer has it's address stored test isn't saved any more than i is. If you want to not have it go, then new/delete are the keywords you need to become familiar with.
Comment: Thank you for explaining this. I'll look into new and delete.
Answer: The name of an array is the address of the first element in it.
Hence the line *state = *arr will set state[0] to arr[0].
Since right now you have defined state as int state[64];, state is const pointer of type int whose address cannot be changed.
You can change it to int *state; and then state = arr will work.
Comment: @SvadHisthana remember though that if you do it that way, `state` will point to the same array as `arr` and any changes you make to one will be made to the other. Also if `arr` goes out of scope, `state` will point to a destroyed array
Comment: I tried your suggestion and got the error "expression must be a modifiable lvalue" for state.
Comment: @SvadHisthana I updated the answer as there was a bug in the previous one. I didn't notice that `state` is declared as `int []` which makes it a `const pointer` and hence its address cannot be changed.
Comment: Good to know. That was the desired behavior.

However, is there any way to preserve `state` in case `arr` does go out of scope?
Comment: To preserve `state`, you would need to allocate memory for it (`state = new int[64];` and then copy the contents of `arr` to `state` (`std::copy(arr, arr + 64, state);` ). Of course if you are going to do this, you would have to implement the [Rule of Three](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three), as now state is a resource.
Comment: So there's no way to preserve `state` without copying the array since the original array declaration is bound to `test`? I just started learning C++ yesterday, so forgive my naivete. ;)
Answer: *arr gives the value that is stored at arr[0] . In c++ , the name of the array is a pointer to the first element in the array.
So when you do *state = *arr , you store the value at arr[0] in the variable state.
Now , if you want to pass the array without having to copy each element explicitly , I suggest that you make another array of the same size in the method which you are calling and then pass the name of the array from the caller , in essence :
methodWhereArrayisPassed(int *arrayName)
{
    int arrCopy[64];
    arrCopy = arrayName;

// Do more stuff here
}

methodWhichPassesArray()
{
    // do stuff here
    int arr[] = {
       0, 1, 2, 3, 4, 5, 6, 7,
       1, 2, 3, 4, 5, 6, 7, 8,
       2, 3, 4, 5, 6, 7, 8, 9,
       3, 4, 5, 6, 7, 8, 9,10,
       4, 5, 6, 7, 8, 9,10,11,
       5, 6, 7, 8, 9,10,11,12,
       6, 7, 8, 9,10,11,12,13,
       7, 8, 9,10,11,12,13,14 };

methodWhereArrayisPassed(arr);

// do stuff here
}

Comment: You can't assign arrays like `arrCopy = arrayName`


Método de login sempre retorna false

Question: Criei um método que retorna um valor boolean para acesso em um programa que estou fazendo. Se o usuário conseguir efetuar login, então retorna true, se não, retorna false. Porém está sempre retornando false, independente se o login e senha estão certos, e não estou entendendo o porquê.
Usei JOptionPane pois quis umas interações com o usuário melhor do que simplesmente usando System.out.print
   List<String> user = new ArrayList<>();
   List<String> pass = new ArrayList<>();

    //Aqui tem um código onde insiro valores nos ArrayList user e pass.
    //Que por sinal aparentemente está correto. Printei os arraylist pra ter certeza disso
    //Não coloquei nesse post pois é meio grande.

    public boolean login() {
    String log = JOptionPane.showInputDialog(null, "Digite o login");
    System.out.println("login digitado: "+log);
    String pas = JOptionPane.showInputDialog(null, "Digite a senha");
    System.out.println("Senha digitada: "+pas);
    for (String c : user) {
        System.out.println("valor de 'c' : "+c);
        //aqui ele printa o valor de 'c'(login), e por sinal esta correto
        if (c == log) {
        //mesmo se atribuir o valor correto a 'log' e ele for igual a 'c' o programa não lê este 'if'

            System.out.println("usuario valido"); //isso ñ printa
            for (String s : pass) {
                if (s == pas) {
                    System.out.println("senha válida");
                    return true;
                }
            }
            System.out.println("incompativel senha");
        }
        System.out.println("incompativel login"); //por fim, ele printa isso
    }
    // e sempre retorna false
    return false; //independente se o usuario digitou tudo certo ou ñ
}

Por que não está funcionando esse sistema de login?
Comment: Acho que tu lógica foi pro brejo. Ex: Usuario 1 - Senha 123, Usuario 2 - senha 456. Agora loga com Usuario: Usuário 1 e coloca a senha 456 hehehe. Acho que alguem logou com uma senha que não te pertence hehehe
Comment: Boa tarde Felipe, seja bem vindo a Stack Overflow em Portugues, recomendo que da proxima vez faça titulos mais intuitivos ao problema.
Answer: Ao invés de if(s == pass),  faça: if(s.equals(pass)).
Mesma coisa para:
if(c == log)

Faça:
if(c.equals(log))

Comment: @BrunoGomes valeu pela explicação! ^^
Comment: Bom, deixando um pouco mais claro, oq o Luiz fez acima é o correto, para comparar uma string, é sempre equals, o "==" para o resto, inteiro, real, booleano e outros.
Comment: @Luiz muito obrigado pela ajuda!

Método de login sempre retorna false