Does a Diablo 3 guest pass let you play with regular players?

Question: Can people using guest passes interact with people with the standard game?
Specifically, if I give one to a friend, can we add each other as friends, and play a game together (up to the Skeleton King only of course)?
Comment: I don't why blizzard would put a restriction on this. I mean after all people can communicate via other means...
Comment: possible duplicate of [What exactly is a "guest pass" and how do I give it to a friend?](http://gaming.stackexchange.com/questions/67974/what-exactly-is-a-guest-pass-and-how-do-i-give-it-to-a-friend)
Answer: Per their official website:

Act I up to the Skeleton King is available
Level 13 cap
Matchmaking available only with other Starter Edition players
No Real Money Auction House access
Global Play is not available. Players attempting to connect to Diablo III Starter Edition in a region other than their Battle.net Account's home region will receive Error 12. See the Global Play support article for more information.

"Starting Edition" player, meaning players using the guest pass. So you are limited to interacting with them only.
Comment: No, you can't play with your friends who have the full version either. I've tested it.
Comment: I saw that in the FAQ, but I wasn't sure if that meant the default matchmaking, or if it totally prevented you from playing with friends with the standard version. Has anyone tried this in-game?
Comment: `So you are limited to interacting with them only.` I think that's pretty self explanatory. :P
Comment: This limitation is clearly to prevent AH abuses, like listing more than 10 items per account (bought game). Otherwise everybody would create starter edition accounts to sell level 60 items.
Answer: Players using the guest pass are restricted to playing with other guest pass users. You can not play or trade between the normal game and the guest pass version


Why is daily power usage measured in kWh and not just kW?

Question: It seems redundant to measure power per hour per day. Is there a good way to understand why they do it this way?
Comment: kWh is power *times* hour, not power per hour.
Comment: Rather, kW is power, kWh is energy. But there's already an answer for that.
Comment: @steveowen *"They charge energy in kw hours per day"* No. They don't. They charge in kWh. To use the speed/distance analogy. You were travelling at 30mph for an hour, so you've travelled 30miles. If you're using a 3kW (power) load for an hour, you will have used 3kWh (energy)
Comment: You confuse "kWh" as meaning "kW/h".
Comment: May be a better question would be: Why don't they use kJ instead of kWh?
Comment: Energy (kWh) is like distance. Power (kW) is like speed. We tend not to say _"They traveled  per day"_, but _"They traveled  per day"_.
Comment: If you want kW•days, just divide by 24 ;^) But nobody uses that unit.
Comment: A kW is the amount of power, a kWh is the amount of power used over time (hour)
Comment: @marcelm yes, but we don't say we travel 60miles per *hour* today -it's just miles per day. They charge energy in kw hours per day.
Comment: ...that's power times hours per day, or equivalently joules per second times hours per day = joules per 1/24 of a second. It's a very silly unit.
Comment: Thx everyone for your efforts to shed light on this matter - much appreciated getting the various explanations and approaches to it. Hard to pick best answer.
Comment: @N.Virgo I'm not sure which unit you mean but I wonder if there might be a math mistake in there? A joule per (1/24 of a second) is not an amount of power which has any particular significance. It's just 24 watts.
Comment: @DavidZ shoot, you're right, sorry. I meant to say 1 kWh = (1000 joules / sec) * (1 hour) = 1000 * (number of seconds in an hour) joules, I just got it completely wrong.
Comment: This rampant confusion makes me wish the electrical industry settled on measuring and billing customers in megajoules (MJ) which is the true metric unit, because the hour and anything based on it is only quasi-metric
Comment: after reading the numerous responses below, i cannot help reminisce Terminator 2 when John Connor says *we're not gonna make it are we, people I mean*.
Comment: @Mausy5043 MegaJoules more likely - but kWh is used because it's an easier conversion for the average person, who counts hours instead of seconds. But if the asker (I want to see a google ngram search for "asker" vs "querent") does want to measure energy in MJ, it's also not a hard conversion on any calculator: 1 kWh is 3.6 MJ
Comment: @SiHa Technically, it's like saying "You were travelling at 30mph for an hour, so you've travelled 1,25mphday", which is just silly. Of course it makes much more sense to measure energy consumption in kWh because it makes it easier to relate it to power consumption (in kW).
Answer: The source of your misunderstanding can be found in your comment above:

@marcelm yes, but we don't say we travel 60miles per hour today -it's just miles per day. They charge energy in kw hours per day.

They don't.
Power companies price energy in dollars (or whatever your local currency is called) per kilowatt-hour.  And the size of your electricity bill is directly proportional (at least if you have a fixed-price contract, and ignoring any flat service fees added on top) to the number of kilowatt-hours of energy you've consumed during the billing period, whatever it may be.
It's indeed possible that your power company is reporting your average electricity usage in "kilowatt-hours per day".  This is a somewhat silly unit that just equals 1/24 kilowatts, but it kind of makes sense if:

your power company is billing you by the kilowatt-hour, and
they're reporting your total measured electricity usage per day.

In that case, if you've used a total of X kilowatt-hours of electricity during a particular day, then your average usage during that day is X kilowatt-hours per day (or, equivalently, X/24 kilowatts).

What may be confusing you is that a kilowatt-hour is a somewhat silly unit in the first place.
For most things, such as water, we measure total usage in simple units like liters (or gallons or cubic meters or whatever) and usage rate over time in derived units like liters per hour (or gallons per hour, etc.).
But, for some historical reasons, for electricity (and energy in general) we've decided to start with a unit (the watt, or more commonly the kilowatt, which is just 1000 watts) measuring usage rate over time, which then means that we have to multiply the usage rate unit (e.g. kilowatts) with some unit of time (e.g. hours) to get a unit for measuring total usage.
It's a bit like if we decided to measure water flow in "firehoses" (you know, how fast an industry standard fire hose can spray out water) and then had to measure total water volume in "firehose-hours" (i.e. the amount of water that a stardard firehose sprays out in an hour).  And if you wanted to know how much water you used in your house per day on average, your water company might then report that in "firehose-hours per day" (equivalent to the number of hours it would take a standard fire hose to spray out the same amount of water as you used in an average day).

In fact we could've adopted a more sensible system for energy, too.  The stardard SI unit of energy is the joule, equal to one watt-second, so one kilowatt-hour is equal to 3600 kilojoules (since one hour is 3600 seconds) or 3.6 megajoules.
If power companies started billing by, say, megajoules of energy used, then they could report average energy usage rates e.g. in megajoules per day, or simply in kilowatts (= 86.4 megajoules per day, since one 24-hour day is 86.4 kiloseconds).  But for historical reasons the power delivery industry is firmly stuck with kilowatt-hours and unlikely to change any time soon.

In any case, for practical purposes, just think of a "kilowatt-hour" as a measure of total energy (since that's what it is), just like a liter (or a gallon or a cubic meter, etc.) is a measure of total water volume.
Just like water, energy is a "substance" that you consume, and your power company bills you for the total amount of energy you've consumed, just like your water company bills you for the total amount of water you've consumed.
Here's a convenient table illustrating the parallelism:

Water
Energy (kWh)
Energy (MJ)

Total amount
Liters
Kilowatt-hours
Megajoules

Usage rate (per second)
Liters per second
Kilowatt-hours per second
Megawatts (= MJ / sec)

Usage rate (per hour)
Liters per hour
Kilowatts (= kWh / hour)
Megajoules per hour

Usage rate (per day)
Liters per day
Kilowatt-hours per day
Megajoules per day
Comment: The **firehose-hours per day** is a good analogy, I'll certainly reuse that in my own explanations to non-engineers...
Comment: In fact, in the spreadsheet I use for tracking home energy costs, I convert both kWh and therms of oil into megajoules so I can get a combined total and see how moving between heat pump and furnace affects my actual usage. (Yes, that ignores relative cost of the two energy sources; total _cost_ of operation would be a different column, and is also affected by which electricity source mix I'm paying for. I haven't attempted to come up with a formula for "greenness" that accounts for all impacts; I'll leave that for experts.)
Comment: It's not silly to have a measure of power before a unit of energy. Consider literal horsepower. People needed to figure how many horses they need to pull a coach. They didn't really care about energy, it was just a given that horses needed to eat and could only run for a certain amount of time. It's only in our home lives, having effectively unlimited power, that the distinction between power and energy seems confusing. If you tow a boat then there's no confusion between horsepower and how full the gas tank is.
Comment: Another good illustration of circular reasoning is measuring the length of your boat in knot-seconds...
Comment: Many [photographic flash devices](https://photo.stackexchange.com/questions/105305/why-is-flash-power-given-in-watt-seconds-ws-and-not-joules-j) have their output rated in watt-seconds instead of joules
Comment: kWh makes sense as a unit for consumers, who buy appliances rated in (k)W and consider usage in hours.  Most of us who are interested in MJ, or even known what a Joule is, can do the conversion if we really want - probably in our heads to sufficient precision (better precision than I can remember the price I pay per kWh anyway).
Comment: I think it makes sense to measure electricity usage with a unit based on power (and not energy directly) since the usage mode is often a bit different than e.g. for water. For water, you might count the number of times you take a bath (and thus use lots of water), but the time spent in the bath doesn't matter. With e.g. a TV or a computer it's harder say what a single "usage" would be, but relatively simple to count the hours the device is on. For something like a washing machine, it would make sense to give the electrical energy used per wash, though.
Comment: My supplier certainly tells me my usage in kWh/year, which is handy for comparing the effect of behavioural and efficiency changes (it converts gas usage to the same units).  A previous supplier used to tell me my daily average (kWh/day) on a quarterly basis, which is nice for comparing winter and summer.
Comment: Could just be me, but I feel _more_ confused after reading this. It's simpler, imo, to think of watts/kilowatts as your _instantaneous_ energy usage; watt-hours/kilowatt-hours are your total consumption over time. With things like 'Rate/hour' not really making sense for electrical devices, as most won't pull a constant load for an entire hour.  The table might be more clear as Total amount -> Liters/kWh, Rate (instant) -> Liters per second/kW, Consumption/hour -> Liters/kWh, Consumption/day -> Liters per day/kWh per day.
Comment: And as for (kilo)watt-hours vs. (mega)joules, I suppose it's just that an hour is a simpler unit for practical everyday purposes than a second. Again, if you watch a movie on that TV, or heat up the sauna, it's easier to count about two hours, rather than seven thousand and some hundred seconds. For something like a refrigerator, you could even use kilowatt-_days_, but that'd be awkward for something that's only used for part of the day (like the TV).
Answer: kW measures energy per unit time. kWh measures energy. If you consume a steady 1000 Watts for a full hour, you'll have consumed 1 kWh of energy. The power company wants to measure your energy consumption because they charge based on energy consumption. They give you energy consumption in kWh and a price per kWh, where the simple product is your energy cost for the month.
Think of a graph of your household's Watts (energy per unit time) consumed over the course of a month. Turn on a light, then the line jumps up by the light's 10 Watts. Turn off a computer, then the line jumps down by the computer's 200 Watts. The power company charges you based on the area under the line on that graph.
Comment: @steveowen, you don't "use 10kW per day." A kW is an energy consumption _rate._ You pay for how much energy you consume, not how fast you consume it. "Us[ing] 10 kW per day" is analogous to "printing 10 ppm per day." The power company's 5 kWh per day is telling you your average daily energy consumption. They just took your monthly energy consumption and divided it by 30.
Comment: @Ecnerwal Sorry, you need to check your units: "kW is just plain power. It has no time element" as a Watt is defined as a Joule per second. Therefore is does have a time element.
Comment: Funnily enough, I had to explain exactly this misunderstanding to someone with a BEng in electrical and electronic engineering the other day. The best way this was explained to be at school was to mathematically show that 1 KWh = 3,600,000 J.
Comment: kW is just plain power. It has no time element.
Comment: @Ecnerwal, you didn't read my statement closely enough. "Power _or_ energy per unit time."
Comment: @popham — add a comma after "power" in the first sentence to make it perfectly clear. I tried to make that edit, but I don't have enough rep to make a 1-character change.
Comment: @steveowen, I run one generator for 40 minutes and generate a steady output of 1.5kW. After these 40 minutes I've burned exactly 1kWh worth of gasoline (3/2kW)(2/3h) = 1kWh. Now I run a weaker generator for 80 minutes and generate a steady output of 0.75kW . After these 80 minutes I've burned exactly 1kWh worth of gasoline (3/4kW)(4/3h) = 1kWh. Since I've burned exactly 1kWh of gasoline in both instances, both scenarios cost the exact same amount of money.
Comment: @steveowen, how about a bit of units theory? How would you respond if I asked you to convert 10 meters to centimeters? Now how would you respond if I asked you to convert 25 seconds to liters?
Comment: @keshlam, I think that I can Socratically convince steveowen that kW-h can meaningfully be converted to gallons of gasoline, whereas parallel reasoning maps kW to gallons of gasoline per hour.
Comment: @Darren, upon reflection, my first exposure to dimensional analysis was 10th grade chemistry class. All of those d/dt's in calculus also prime your intuition for kW versus kWh. Without those two building blocks, though, I'm curious how well I could be introduced at my current age.
Comment: @Pete Becker, that's bad grammar, but I'll change it for better clarity.
Comment: Thx, yeah I get that, but the usage is for each day - like on a bill etc. So it is referring to time twice. If i use 10kw per day, it is charged at so many cents per kW regardless of how long it took to use within the day. Unless they are billing per hour, then it matters.
Comment: @Pete Becker, a comma before "or" is for independent clauses, where my heuristic is that the ", or" can be replaced with a ".  ". It's for two separate sentences that you've chosen to combine into a single sentence, but there's still all of the subject-verb-object structure of complete sentences on both sides of the ", or".
Comment: Based on your graph idea (very useful) - if you averaged out the kW value per month from the graph, the answer would be so many kW/month.
Comment: Moved my explanation of Days&per-month being time per time and thus unitless into my answer. Usage over any duration would still be measured in kWh (or kWs if you want to go with pure SI dimensions.)
Comment: Dealt with amps vs. joules in the addendum to my answer. If you're using amps, that time factor is already accounted for, and indeed cancels nicely.
Answer: It isn't "power per hour per day" -- that would be written, for example, as kW/h/day. The divide symbol / is read as "per."
The unit "kWh" could be more explicitly written kW ⋅ h. The dot signifies multiplication. Mathematicians and engineers don't verbalize it, though: when we read "kWh" we simply say "kilowatt hours." A person is supposed to recognize that:

the "kilo" prefix means one thousand,
Watt is a unit of power,
hour is a unit of time, and
when two units are given sequentially, without the word "per" or symbol "/" (slash, as I call it) intervening, it is inferred that the two units are multiplied together.

So kWh is not "power per hour" but rather "power times (multiplied by) hours." Scientifically speaking, power is a quantity measured at an instant in time -- not unlike voltage, or amps, or PSI in water pressure.
The electric utility bills for energy, and one way of expressing energy is power multiplied by time.
Comment: @Nayuki There's a unicode expert in every crowd. ;-) Thanks!
Comment: Pretty good answer! Nitpick - your "•" (U+2022) is the "bullet" character. You want to use the [dot operator](https://en.wikipedia.org/wiki/Interpunct) (U+22C5) for [kW⋅h](https://en.wikipedia.org/wiki/Kilowatt-hour#Unit_representations).
Answer: You write:

[W]e don't say we travel 60miles per hour today -it's just miles per day.

That's exactly right, and the same goes for electric power, too.
A kilowatt is kind of like a mile per hour. It's a "speed" at which you're consuming energy. A kilowatt hour, on the other hand, is kind of like a mile. It's an actual amount of energy.
Just like you can say "we travel 60 miles per day," you can say "we consume 60 kilowatt hours per day." But since a kilowatt is like a mile per hour, saying "we consume 60 kilowatts per day" would be like saying "we travel 60 miles per hour per day."
Answer: Watts is an instantaneous measurement; an LED bulb draws about 10 watts whenever it is on
Watthours is total usage over a time period; if the 10w bulb is on for 1.5 hours that's 15 Wh; the same would be true of a 15 watt device running for 1 hour, or a 30W draw for half an hour.
Over a billing cycle of a month, I use (and pay for) something like 300 kWh. That means my average usage per day is approximately 10kWh. If we call a day 25 hours to make the math easier, that means the devices in my house are drawing about 400W at any average moment.
I could add up the demand from lights and appliances in the house, figure out how often and how long they're in use, and should come up with roughly the same average use of 400W or (multiplying by hours in a month) 300 kWh over a month.
Note that dividing by 30 to get an average day doesn't remove time from the equation. Months times days per month equals days, still a unit of time,and still typically given in kWh rather than kWd(ay). To convert to the latter, you'd need to multiply by hours per day, and it would still be per unit time since hours per day is time per time and dimensionless.
(Dimensional analysis works, but only if you are careful to track the dimensions of every value.)
ADDENDUM:
Watts, by the way, is volts times amps. Amps is coulombs per second, but unless you are going down to coulombs that's irrelevant.
The analogy between speed and distance, with watts as speed and watt hours as distance, is entirely valid. Speed is distance per unit time; multiply it by time to get distance. Amps is  coulombs per hour, scaled, if you want to go to that level; the "per hour" is cancelled out by the "times hours" in watt-hours to give you units of coulombs times voltage, which is a pretty decent measurement of how much "oomph" was delivered/consumed during that measurement period. (BAD analogy: if coulombs were mass, volts would be pressure, sort of; amps would be how fast you are releasing that pressure to get work done.)
Does that help? If we go much further I'm going to have to issue a freshman physics quiz...
Comment: So as part of the dimensional analysis that you mention a Watt is defined as a Joule per second... So Watts does include time...
Comment: The Wikipedia article does not disagree with me. There are multiple ways to derive any unit from other units (there have to be if they're to be consistent), , and when starting with volts and amps seconds don't appear because they're already part of the ampere's definition. Unless you want to go down to coulombs, which aren't used in the home improvement domain
Comment: (I once got extra points from a science teacher by pointing out that power in Watts was both directly proportional to resistance, and inversely proportional to resistance, depending on whether you were holding volts or amps constant.)
Comment: See https://en.wikipedia.org/wiki/Watt and don't confuse with Joule-second... Perhaps you need to start with just using M, L and T to derive the units.
Comment: dropped objects? like improvement or provement? But do you favor Rayleigh or Buckingham?
Comment: Neither. Not my circus, not my monkeys.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/148843/discussion-between-keshlam-and-solar-mike).
Comment: "Amps is coulombs per hour" - do you mean "per second"? Or do you mean "is equivalent to", or "is like", or "plays the role of", or something along those lines?
Comment: Yes, per second. Sorry. i was ignoring scaling factors in a sloppy attempt to make the parallel with Wh easier to see. I should have said "per unit time". Apologies for the sloppiness; I'm trying to write a curriculum in realtime on a cellphone keyboard...
Answer: Let's clarify some concepts.

why is Daily power usage measured in kWh and not just kW?

kWh is not a unit of power, it is a unit of energy. In contrast, kW is a unit of power.
Why is that?
By definition, power is the rate at which work (or energy) is done per unit of time. Mathematically:

Where:

P is the power, measured in watts (W) in the SI
W is the work (or energy), measured in (J) in the SI
t is the time, measured in seconds (s) in the SI

Note that:

From the above equation it is evident that if we multiply the power by a time (T), we will obtain a unit of energy.
For example, suppose we have 1 kW, and we multiply it by 1 h which is equal to 3600 s:

This demonstrates that 1 kWh = 3600 kJ, which is a unit of energy.
Finally, power can be understood as the rate at which energy is supplied or consumed. When you pay your electricity bill, you are actually paying for the energy consumed, not for the power. This makes more sense. For example, a 9-watt lamp consumes 9 joules per second. Therefore, you need to know how long the lamp is on to determine the total energy consumed. If the lamp is on for 1 hour, then 9 watt-hours have been consumed, or 9·3600 = 32400 joules.
Answer: Watts is an instantaneous rate.  While its units may be the same as kWh/day it doesn't convey the same idea.
By analogy, km/h is a rate.  If you go 10km/h for one hour each day for a month, you've gone 300km.  You could say "I've gone 10 km per day this month".  You would not say "I went 0.42 km/h this month".  In a contrived way you did, but it fails to communicate what you want.
Similarly daily power usage is expressed in kWh/day rather than just kW because it provides a familiar, accessible way for people to understand the energy usage.  Although it can mathematically be reduced to kW, the resulting number is not meaningful to most people.   "I used 100 Watts this month" sounds like you have a 100 Watt light bulb that was on all month, not what you probably mean if you consumed energy at various rates and times, averaging 2.4 kWh/day, even though that's mathematically equivalent.
Answer: One can measure in either.
If you measure your daily usage in kWh - you get to add together your 30 daily usages and you get your monthly power bill.
On the other hand, you may divide the above by 24 (hours) and you will get the average power over the day (in kW). This may be somewhat useful number if you are debugging your power usage.
Answer: To clear up some terminology. You consume energy, not power. Power is energy used per unit time.
The simple answer to your actual question is because power companies believe the public is uneducated.
Most home appliances list power consumption in Watts (1 joule of energy per second). So it's inherently understandable that if you use 1kW for 1h you get billed for 1kWh.
1kWh is directly equivalent to 3600kJ of energy.


Finding the sum of many square root values (greatest integer function)?

Question:
I am not really sure how to go about this mathematically, but I used my programming skills to find the answer quite quickly:
<code>public static void main(String[]args)
{
int x;
int p = 0;

for(x = 0; x <= 36; x++)
{
p+=Math.sqrt(x);
}
System.out.println(p);
}
</code>
What this does is adds each square root value to the past value all the way to sqr(36). The sum ends up being 131 or B. I can't really get anywhere outside of this, so any help is appreciated.
Answer: Hint: You need to pay attention to the values $N$ such that $\sqrt{N}$ is an integer, namely $1,4,9,16,25$ and $36$. Now, for instance, if $4 \leq N < 9$, then $2 \leq \sqrt{N} < 3$, so that $\lfloor{\sqrt{N}}\rfloor = 2$. So, for instance, $\lfloor{\sqrt{4}}\rfloor + \lfloor{\sqrt{5}}\rfloor + \lfloor{\sqrt{6}}\rfloor + \lfloor{\sqrt{7}}\rfloor + \lfloor{\sqrt{8}}\rfloor = 2 + 2 + 2 + 2 + 2 = 5 \cdot 2 = 10$.
Can you finish it from here?
Comment: So sqr(9)+sqr(10)+sqr(11) = 5 • 2 = 10 as well?
Comment: No. Do you understand what the "greatest integer function" or "floor function" means?
Comment: Doesn't it mean to round down?
Comment: So your saying that numbers within 4≤N< 9 since sqr(4) = 2 and your rounding down. So 9≤N<16 = 3? And 16≤N<25 = 4? etc...?
Comment: That's right. Now just add everything up and you get the answer. You can do this rather fast if you notice that there are $2n+1$ integers between $n^2$ (inclusive) and $(n+1)^2$ (exclusive).


Computing the Quadratic residue

Question: Given that $a$ is a quadratic residue $\pmod p$ where $p$ is prime is there a way to efficiently compute $x$ without enforcing any constraints on $p$ such that :
$$ x^2 \equiv a\pmod p $$
Comment: There are a number of good algorithms. Popular ones are variants of [Tonelli-Shanks.](http://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm)
Comment: If $p \equiv 3 \bmod 4$ you have $x = \pm a^{(p+1)/4}$
Comment: You seem to ask for "general purpose." As pointed out by Cocopuffs, $p\equiv 3\pmod{4}$ can be done by binary method of exponentiation. There is a similar procedure for $p\equiv 5\pmod{8}$.
Answer: As was said in the comments, one method for solving this problem is the Tonelli-Shanks Algorithm.
Comment: Therfore if I have $n = pq$ can I find a quadratic residue $\pmod n$ given the fact I can find $R_1^2 \equiv a\pmod p$ and $R_2^2 \equiv a\pmod q$? Can I combine these two in a solution $\pmod n$ ?

Computing the Quadratic residue


Checked items on listbox with 2 columns to be moved on top of the list

Question: I have an MultiSelect Listbox with 2 columns and 100 items. It is possible that the selected items to go on top of the listbox?
For example, this is the listbox:
Azerty      120ms
QWERTY      12,56ms
RAW         450,25ms
doWn        235,00 ms
alfa        258,7ms
etc....

If I check 'doWn and RAW' to go on top of the list like this (the order is not important):
doWn        235,00 ms
RAW         450,25ms
Azerty      120ms
QWERTY      12,56ms
alfa        258,7ms
etc....

Answer: I have done it like this.
The code is in a textbox change status.
Add Items of listBox in an array.
Loop through list box to see which item is selected.
Add selection numbers in a string, Strings in an array of selected_items and not_selected_items.
Loop array to rearrange the items based on selection and original array
code:
Private Sub TextBox2_Change()

    Dim arr()
    Dim arrYes() As String
    Dim arrNo() As String
    Dim i As Long, j As Long
    Dim yes As String, no As String

    On Error GoTo nirvana
    arr = Me.ListBox2.List

    For i = 0 To Me.ListBox2.ListCount - 1
        If Me.ListBox2.selected(i) = True Then
            yes = i & "," & yes
        Else
            no = i & "," & no
        End If
    Next

    arrYes = Split(StrReverse(Left(yes, Len(yes) - 1)), ",")
    arrNo = Split(StrReverse(Left(no, Len(no) - 1)), ",")

    i = -1
    For j = 0 To UBound(arrYes())
        i = i + 1
        With Me.ListBox2
            .List(i, 0) = arr(arrYes(j), 0)
            .List(i, 1) = arr(arrYes(j), 1)
            .selected(i) = True
        End With
    Next j

    For j = 0 To UBound(arrNo())
        i = i + 1
        With Me.ListBox2
            .List(i, 0) = arr(arrNo(j), 0)
            .List(i, 1) = arr(arrNo(j), 1)
            .selected(i) = False
        End With
    Next j
nirvana:
    Exit Sub
End Sub


Get a list of constants outside of PHP class

Question: I'm trying to get a list of all the constants that are defined outside of a PHP class but only if they start with a specific prefix (see this tutorial) and saw the ReflectionClass::getConstants functionality but this requires a class.
How do I achieve the same functionality if the constants are defined outside of a class?
Comment: Maybe try [`get_defined_constants`](https://www.php.net/manual/en/function.get-defined-constants.php)?
Comment: Thanks! An obvious solution eluded me.. I should hand my developer membership card now.
Answer: You can use the built-in function get_defined_constants. It will list all the constants even the ones coming from Core PHP and loaded extensions. You can pass true as the parameter to categorize them. To get just userland constants (both from const and from define()) use get_defined_constants(true)['user']
<?php

define('DEFINED_CONST', 'foo');
const myConst = 1;

print_r(get_defined_constants(true)['user']);

prints:
Array
(
    [DEFINED_CONST] => foo
    [myConst] => 1
)


How do you delete a pointer without deleting the data the pointer points to?

Question: I have a pointer that points to an array and another pointer referencing the same array. How do i delete any one of those pointers without killing the array such that the second undeleted pointer still works?
for example:
int* pointer1 = new int [1000];
int* pointer2;
pointer2 = pointer1;

Now i want to get rid of pointer1, how would i do it such that i can continue to access the array normaly through pointer2?
Answer: Those pointers are on the stack; you don't have to delete them. Just ignore pointer1 and it will go away at the end of the block.
Comment: @Faken- To be clear, "a pointer is simply a variable on the stack" is not a true statement.  The pointer in your code sample is a stack variable because you declared it statically.  A pointer can also be declared dynamically, as Neil Butterworth shows in his example.  It's all in how you declare it, there's nothing special about the object being a pointer.
Comment: @bta: I don't see anything statically declared. Perhaps you mean "automatic", the actual term. (That is, things are not stack allocated, but they are automatically allocated.)
Comment: Ahh this explains it the best to me. So a pointer is simply a variable on the stack, that makes sense. So this means it can't be accessed out of scope and i won't accidentally use it elsewhere out of scope and cause problems. Ok, thank you.
Comment: The compiler is allowed to "make the pointer go away" as soon as the compiler deems it not in use.  A pointer may go away before the end of the block.
Answer: Let it go out of scope?
You don't 'delete' pointers, you delete what they point at.  So if you just want to get rid of the variable 'pointer1' the only way to do that is for the scope it was created in to be terminated.
Answer: You don't pass that pointer to  delete at all.  You just stop using that pointer.  If you want to make sure you don't access the array through that pointer again, you can set it to null.
C and C++ do not keep track of how many pointers point to an object or an array.  If you want reference counting, you need to use a reference-counted container, like shared_ptr, or in this case, shared_array (you can find both of those in Boost and there is a high likelihood that your implementation already has them in <memory> either in the std namespace or in std::tr1).
Answer: When you statically declare a pointer with int* pointer1;, you can't free it.  You can only free dynamically-allocated memory that you allocated using new, malloc, etc.  The only way to "get rid of" pointer1 is to let it go out of scope, such as when the function returns.  If you are done using pointer1 and want to prevent it from accidentally being used to alter the array, use pointer1 = NULL;.
Answer: Normally to make a pointer "safe" just set it to NULL which makes it point to nothing at all. Or you can just let it go out of scope.
For example, if you have two pointers.
int *a = new int;
int *b = a;

// somewhere
b = NULL;

delete b; // does nothing now
delete a; // deletes a

Or you can let it fall out of scope.
int *a = new int;

{
 int *b = a;
 // blah blah blah
}

// don't have to worry about b
delete a;

Comment: Does `b = NULL; delete b` do anything?  Is it defined?  I was under the impression that that's some sort of bug or undefined behavior.
Comment: @Nathan: `foo = NULL; delete foo;` is pefectly legal and harmless. Means you don't have to always look for non-NULL-ness before deleting.
Answer: It's a stack variable (the way you've written it) and therefore bound to the scope you declared it in.  Once you hit the closing curly brace of that particular scope, it will get cleaned up without you having to do anything about it.
If you want to make absolutely sure nothing else can use pointer1 any longer, you could set pointer1=NULL once you're done with it.
Answer: int** pointer1 = new int *;
* pointer1 = new int [1000];
int* pointer2;
pointer2 = * pointer1;
delete pointer1;

Comment: @Faken Consider it a Zen lesson :-) Basically, as others have pointed out, your question as asked does not make too much sense.
Comment: Heh, you've been very helpful to me in the past, but this time you've just confused me instead, heh.
Comment: @Faken- He's showing you what you would have to do if you wanted to be able to delete the pointer.  He creates a "pointer-to-a-pointer" and assigns it the address of a `int*` created through `new`.  Since `pointer1` is allocated dynamically in this case, you can `free` it once you are done with it.  The complexity of this solution probably indicates that you need to re-think whether you really need to delete the pointer.
Comment: @Neil: Ignorance is bliss. That's what happens to me when i get thrown off the deep end. Not having any having any real programming experience or training before jumping into a massive programming project tends to have that effect. Notice how all my reputation is earned from pure up votes to my questions...heh...Needless to say, stackoverflow has saved my life.
Answer: Just ignore the pointer, and it will go away when you're done with your function or block. Just remember that once you no longer have a pointer to something, it won't be able to be accessed. Of course, it will still be there using up memory, but you won't be able to get to it. So, before you consider letting go of the pointer, make sure you either have another pointer to it somewhere, or you get rid of it.


setup include path in eclipse CDT in mac os (headers from framework)

Question: for example I need to include a header
<code>#include <OpenGL/glext.h>
</code>
while it is actually a header file glext.h under OpenGL.framework/Headers/.
Therefore it is no way to give eclipse a physical path about "OpenGL/glext.h", and I always get unresolved inclusion warning.
I can still build and run them (with managed makefile project) but it is impossible to browse the functions or definitions from those "resolved" header files.
is there any solution?
Comment: it seems a bug in cdt https://bugs.eclipse.org/bugs/show_bug.cgi?id=69529#c37
Comment: yeah it is a bug. 2 years later still not resolved. Workaround1: use Netbeans. Workaround2: add the framework folder in the includes
Answer: While not ideal, my solution to this has been to create a folder "/Developer/Framework Headers" (though the name isn't important), and link from e.g. "/System/Library/Frameworks/Foo.framework/Headers" to "Foo" under said folder. Then in Eclipse I add "/Developer/Framework Headers" to a project's includes.
I say not ideal because apart from having to create links for the frameworks you need and add an include to each project, Eclipse seems to have trouble in certain cases such as nested frameworks (e.g. CoreGraphics beneath ApplicationServices), but YMMV.
Answer: Yes there is one. Right click on the project in "Project Explore" window and click on the "property". In there Open "C/C++ General" column and choose "Path and symbols". Now you see all of the include library path for this project. If your using C then add the OpenGL library into GNU C, or if you use C++ then add it into GNU C++. Unfortunately you have to do this for every new project. I have been searching for a while how to do this by default but nothing really useful. Hope this help you get rid of those annoying yellow wave lines.
Comment: You described the normal process, but that doesn't work here, because there is no real path of "OpenGL/glext.h".  The Mac compiler translates that #include to "OpenGL.framework/Headers/glext.h" to find the file, but Eclipse doesn't understand this.
Answer: Since current Eclipse CDT releases don't perform sub-framework header inclusion correctly, you can avoid sub-framework problems (like those generated by the CoreServices header files) by creating symbolic links to the include directories of each sub-framework. I elaborated on this subject, which stems from danhan answer on this question, in this blog post.
In order to automate this process, I've created a Z shell script which automates this process and creates the symlink to the specified frameworks' header directory, together with the links to the include directory of each one of their sub-frameworks. The script can be found in this GitHub repository.
Hope this helps.


Transformation for isothermal coordinates of energy of harmonic maps between Riemann surfaces

Question: I am currently reading section "3.6 Maps Between Surfaces. The Energy Integral. Definition and Simple Properties of Harmonic Maps" in "Compact Riemann surfaces" by Jürgen Jost and he defines the energy of a map as follows

Let $\Sigma_1$ and $\Sigma_2$ be Riemann surfaces; suppose $\Sigma_2$ carries a metric, given in local coordinates by
$$
\rho^2(u)du d\overline{u}.
$$
Let $z = x + iy$ be a local conformal parameter on $\Sigma_1$.
Now let
$$
u: \Sigma_1 \to \Sigma_2
$$
be a map, of class $C^1$ to start with. We define the energy integral of $u$ as
$$
\begin{align}
E(u) &:= \int_{\Sigma_1} \rho^2(u) (u_z \overline{u}_{\overline{z}} + \overline{u}_z u_{\overline{z}}) \frac{i}{2} dz d\overline{z} \\
&= \frac{1}{2} \int_{\Sigma_1} \rho^2(u(z))(u_x \overline{u}_x + u_y \overline{u}_y)dxdy
\end{align}
$$
($u_z := \frac{1}{2} (u_x − iu_y), u_{\overline{z}} := \frac{1}{2} (u_x + iu_y)$, etc., subscripts denoting partial
derivatives.)

What I don't understand basically boils down to one question:

By plugging in $u_z := \frac{1}{2} (u_x − iu_y), u_{\overline{z}} := \frac{1}{2} (u_x + iu_y)$, etc., in the first line of the definition of the energy integral I managed to get the $(u_x \overline{u}_x + u_y \overline{u}_y)$ part of the second line but I don't understand how the differentials transform and how they seem to "suck up" the imaginary $i$.
Comment: For starters, $\frac i2 dz\wedge d\bar z. = dx\wedge dy$.
Comment: Argh, of course it is!
Answer: With the little nudge from Ted Shifrin in the comments I can answer my own question:

By plugging in $u_z := \frac{1}{2} (u_x − iu_y), u_{\overline{z}} := \frac{1}{2} (u_x + iu_y)$, etc., in the first line of the definition of the energy integral I managed to get the $(u_x \overline{u}_x + u_y \overline{u}_y)$ part of the second line but I don't understand how the differentials transform and how they seem to "suck up" the imaginary $i$.

We plug in $u_z := \frac{1}{2} (u_x − iu_y), u_{\overline{z}} := \frac{1}{2} (u_x + iu_y)$, etc., and $z = x + iy$ to get
$$
\begin{align}
E(u) :&= \int_{\Sigma_1} \rho^2(u)(u_z\overline{u}_\overline{z} + \overline{u}_z u_\overline{z})\frac{i}{2}dzd\overline{z} \\
&= \int_{\Sigma_1} \rho^2(u)(u_z\overline{u}_\overline{z} + \overline{u}_z u_\overline{z})\frac{i}{2}dz \wedge d\overline{z} \\
&= \int_{\Sigma_1} \rho^2(u(z))\left(\frac{1}{2}(u_x -iu_y)\frac{1}{2}(\overline{u}_x + i\overline{u}_y) + \frac{1}{2}(\overline{u}_x - i\overline{u}_y)\frac{1}{2}(u_x + iu_y)\right)\frac{i}{2}d(x+iy) \wedge d(x - iy) \\
&= \int_{\Sigma_1} \rho^2(u(z))\left(\frac{1}{4}(u_x\overline{u}_x + iu_x\overline{u}_y -i\overline{u}_xu_y + u_y\overline{u}_y ) + \frac{1}{4}(u_x\overline{u}_x + i\overline{u}_xu_y - iu_x\overline{u}_y + u_y\overline{u}_y )\right)\frac{i}{2}d(x+iy) \wedge d(x - iy) \\
&= \int_{\Sigma_1} \rho^2(u(z))\frac{1}{2}(u_x\overline{u}_x +  u_y\overline{u}_y)\frac{i}{2}d(x+iy) \wedge d(x - iy) \\
&= \int_{\Sigma_1} \rho^2(u(z))\frac{1}{2}(u_x\overline{u}_x +  u_y\overline{u}_y)\left(\frac{i}{2}(dx+idy \wedge dx - idy)\right) \\
&= \int_{\Sigma_1} \rho^2(u(z))\frac{1}{2}(u_x\overline{u}_x +  u_y\overline{u}_y)\left(\frac{i}{2}(dx\wedge dx -idx \wedge dy +idy\wedge dx + dy \wedge dy)\right) \\
&= \int_{\Sigma_1} \rho^2(u(z))\frac{1}{2}(u_x\overline{u}_x +  u_y\overline{u}_y)\left(\frac{i}{2}(0 - idx \wedge dy - idx\wedge dy + 0)\right) \\
&= \int_{\Sigma_1} \rho^2(u(z))\frac{1}{2}(u_x\overline{u}_x +  u_y\overline{u}_y)dx\wedge dy \\
&= \int_{\Sigma_1} \rho^2(u(z))\frac{1}{2}(u_x\overline{u}_x +  u_y\overline{u}_y)dxdy
\end{align}
$$
which is exactly the second line.


Difference between MQTT and MODBUS protocol?

Question: I've been reading about these two protocols lately and wasn't quite able to understand why to use MQTT when we have MODBUS (or vice versa).
Since, MODBUS is used to transmit data over serial communication between PLC's under low bandwidths, but as far as i understood, MQTT does the same using its PUBLISH/SUBSCRIBE methodology (I know MQTT uses a broker and MODBUS doesn't, but that's not the point).
Can somebody provide a clear distinction between them?
Comment: I'm sorry there is little evidence of doing any basic research here. Modbus and MQTT are incredibly different
Comment: @hardillb i did, jusst kept the question as concise as possible
Answer: They are quite different, but both are popular in their own era.
Modbus is originally published in 1979, it is designed mainly for control/monitoring software to communicate with filed devices in a limited scale, e.g. a factory/building. So it has the following key considerations,

One-to-many topology, there is always one master to poll multiple slaves
Simplicity over flexibility, it only support request-response pattern
deterministic timing over performance, it is to support the strict real time requirement in control system

MQTT started in 1999, large-scale network and internet becomes much more popular and more complex communication ways between software and devices are needed since then, like event-based, machine-to-machine communication. So MQTT emerges to meet the following needs,

Many-to-many topology, all participants can communicate each others via the common broker.
Large scale, it works well in large network, e.g. internet.
Flexibility, all participants are decoupled, and it provides QoS to meet different delivery agreement.

In a nutshell,

If you are a software architect, use MQTT if possible, because it is well designed for modern IoT world,
If you are designing a smart device, you may consider Modbus for compatibility with traditional PLC/SCADA system.

Bonus: You can consider to bridge Modbus to MQTT world, like this modpoll tool.
Answer: Normal Modbus is a serial communications protocol often used for connecting industrial electronic devices.
MQTTis a messaging protocol for use on top of the TCP/IP protocol often used for sending measurements from electronic devices to another party.
Maybe this link help a bit.
A Comparison of IoT Gateway Protocols: MQTT and Modbus
Answer: Modbus has lots of varients. But if we will compare one Modbus varient with MQTT, it should be Modbus TCP.
*MQTT is a newer protocol than Modbus and developed as Internet of Things(IoT) in mind. Some old devices doesn't support MQTT but just support Modbus TCP.
*With MQTT, you can send data to multiparts by message broker, but Modbus TCP just send data to the its  server.
*MQTT is more secure than the Modbus TCP protocol.
*MQTT is supported by many software languages and main cloud service providers such as Amazon AWS, Microsoft Azure, IBM Bluemix and Google Cloud.
*As a result, if your devices and system support MQTT, use it instead of Modbus TCP.


Launching a WPF window from a Console application

Question: I'm trying to use a WPF window as a message popup that will close once a task has been performed. All the documentation I've seen says that this can't be done with a messageBox, that's why I'm going with the WPF. I found one code snip that allowed me to open the WPF window but it wouldn't progress the application to the next process. Below is the last code example I found that I thought showed promise but the window isn't opening -
        [STAThread]
        static void Main(string[] args)
        {
            try
            {
                string filePath = "my new directory";
                var popup = new PopupTest();

                popup.Dispatcher.BeginInvoke
                    (System.Windows.Threading.DispatcherPriority.Normal,
                    (Action)(() =>
                    {
                        popup.Show();

                    }));

                // Do some console application stuff

                do
                {
                    Directory.CreateDirectory(filePath);
                } while (!Directory.Exists(filePath));

                popup.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
            }
        }
    }

The cs.xaml file is just the default
    /// Interaction logic for PopupTest.xaml
    ///
    public partial class PopupTest : Window
    {
        public PopupTest()
        {
            InitializeComponent();
        }
    }

I feel like this should be simpler than I'm making it. Anything that can point me in the right direction is appreciated.
Comment: IMHO, just create a WPF application if you want to show some sort of window. Why are you mixing console and ui projects, why do you need both? [This may be worth](https://stackoverflow.com/questions/4509714/how-to-start-the-wpf-window-from-console-programmatically) checking out as well.
Comment: This functionality, a warning popup until an action is completed, is being included into a larger existing application. What I included was just an approach that I found online. I checked out the link you included and `Application app = new Application (); app.Run(new Window1());` opens the window but doesn't allow the application to proceed. I tried adding that line to it's own thread ` var popup = new PopupTest();
            Application app = new Application(); Thread thread1 = new Thread(()=> app.Run(popup)); thread1.Start(); `  But that doesn't open the window either
Answer: You need to reference the WPF assemblies and create and run a System.Windows.Application on the STA thread:
[STAThread]
static void Main(string[] args)
{
    var app = new System.Windows.Application();
    app.Run(new PopupTest());
}

The Run method blocks and doesn't return until the app is shut down.
If you want to do some stuff while the app is running, you need to do this on another thread:
    [STAThread]
    static async Task Main(string[] args)
    {

        Task t = Task.Run(() =>
        {
            string filePath = "my new directory";
            do
            {
                Directory.CreateDirectory(filePath);
            } while (!Directory.Exists(filePath));
        });

        var app = new System.Windows.Application();
        app.Run(new MainWindow());

        await t;
    }

Comment: Step in the right direction but I can't get the Window to close after the Task completes. Using the code above as a jumping off point I tried placing `app.MainWindow.Close();` after `app.Run` but it appears that line never gets hit. I tried instaniating the window before the Task and placing `app.MainWindow.Close()` within the Task, after the while loop, but that seemed to freeze up the application.
Comment: You don't await the task *until*  the window and application has been closed. As I said, "the `Run` method *blocks* and *doesn't return* until the app is shut down." What exaclty are you trying to accomplish? When and how do you want to close the window?


Querying rows multiple times from ROOM database while using a Bitmap Type Converter class is crashing the App

Question: So I have Recycler View with a paging adapter, the recycler view list item has an imageView and a couple of text views. The data for the textViews are being retrieved by the adapter from another ROOM Database whereas the images for each those specific list items are being retrieved from another ImageHolder ROOM Database.
In the onBind method of the adapter in addition to binding the textViews there is a separate call to the ImageHolder ROOM Database for the associated image. The Recycler View has about 100 items and while the UI is scrolled quickly, about 100 queries are made to the ImageHolder Database. This works fine but it slows down the app as the user scrolls and crashes the app. How do I do avoid the crash?
Here is the code:
The data class
<code>@Entity(tableName = IMAGE_HOLDER_TABLE)
data class ImageHolder(

    @PrimaryKey(autoGenerate = false)
    var contentId: String = "",
    var imageBitmap : Bitmap,  // I am using a Converter class to convert a Bitmap to a ByteArray
    var timeStamp : Long = System.currentTimeMillis()
)
</code>
The Dao Interface
<code>@Dao
interface ImageHolderDatabaseDao {

    @Query("SELECT * FROM $IMAGE_HOLDER_TABLE WHERE contentId = :contentId")
    suspend fun getImageHolder(contentId : String): ImageHolder

    @Query("SELECT imageBitmap FROM $IMAGE_HOLDER_TABLE WHERE contentId =
    :contentId")
    suspend fun getImage(contentId : String): Bitmap
}
</code>
The method to get the image in the Adapter's onBindViewHolder method
<code>val imageHolderDatabase = ImageHolderDatabase.instance(getApplicationContext())
    val imageHolderDatabaseDao = imageHolderDatabase.databaseDao
    private val scope = CoroutineScope(Dispatchers.Main +
CoroutineName("notificationsAdapterCoroutine"))

    private fun populatePhotoFromLocalDb(senderUserId : String) {
        scope.launch {
            val imageBitmap = imageHolderDatabase.withTransaction {
                imageHolderDatabaseDao.getImageHolder(senderUserId)
            }

            Glide.with(getApplicationContext())
                .load(imageBitmap.imageBitmap)
                .placeholder(R.drawable.black_color_rectangle)
                .apply(glideRequestOptionsForCache)
                .transition(DrawableTransitionOptions.withCrossFade(glideCrossFadeDuration))
                .listener(glideFinishedLoadingListener(senderUserId, true, null))
                .into(binding.image)
        }
    }
//I am using the Paging 3 adapter to populate the textViews from another Room Database
</code>
I realize there are 100 query calls made to the ImageHolder Room Database since there are 100 items in the Recycler View. I am using Glide but not using its Caching for now.
What is a memory-efficient way to do this?
Comment: I think your whole idea is wrong. Why do you need to download the whole image and save it as byte array in a database? Just save the url inside the database and than use Glide to download the image and show it inside the adapter. In this way at the beginning you will be downloading only text data, without any images.
Comment: As I understand you are doing 100 database queries to get 100 images? Why do not get all of them with one query and store them in an array which after that you can use to populate your RecyclerView?
Comment: Also you can add the stacktrace of the crash too.
Comment: Hi @hardartcore, the database fetches data from a Network database in batches of 20 at a time as the user scrolls so getting all 100 would be too expensive since all data would have to be downloaded over the network
Comment: It depends on how you are downloading it. As I understand you download all the images and save them in a database as byte array and then recreate them as bitmap object and pass to Glide?
Comment: Yes, download if the database is empty and the next time the activity is created and if the database has items then get data from the database itself without querying it from the network
Comment: @hardartcore, yes I realized the type converter from ByteArray to Bitmap is causing too much memory usage, I have now implemented exactly what you've suggested...
Answer: The type converter from ByteArray to Bitmap is causing too much memory usage, this is actually a good way to store images but the wrong use case for using the handy Type converters for ROOM (unless it's used in a non recyclerView adapter), I have instead changed the logic to store the downloadUrls only in the Room Db and using glide to load images via the download Url since glide has offline cache system built in, this logic works even with the internet being unavailable temporarily...


why does Parse cloud code save one object but not the other?

Question: I am new to Parse Cloud Code.. however I am trying something that theoretically should be straight forward and I cannot understand why it won't work!
in my User class i have an array of playableFriends, when i create a Game object I wish to remove the player and opponent from each others playableFriends Array
The code to remove the opponent from the players array works.. but for some reason unknown to me the code to remove the player from the opponents array does not.. even if it is the only code being run.
I have output the player and opponent objects to the console to ensure they exist and I have also tried using the fetch command on the opponent but that didn't work either
Parse.Cloud.afterSave("Game",function(request, response){

  //return if existing game
  if (request.object.existed()){
      return;
  }

  //get player
  var player = request.object.get("playerIdle");
  //get opponent
  var opponent = request.object.get("playerTurn");

  //remove opponent as playable friend
  player.remove("playableFriends", opponent);
  //remove player as opponents playable friend
  opponent.remove("playableFriends", player);

  player.save();
  opponent.save();
});

any help would be greatly appreciated
regards
Byron
Answer: The problem is that the two save operations at the end of your functions are asynchronous. Basically, this means that when your player.save(); is reached, the execution continues on to the next line even though your save operation may not have completed (in your case it seems that it's the second save that is not completed). There are a couple ways of overcoming this: callbacks and promises.
A callback is a block of code that is passed into your async function that will be executed when the function completes. A promise, on the other hand, allows you to be notified when an async function completes. With promises, you use the then() function to continue execution once the original promise is fulfilled, which can either be resolved if the async operation was successful, or rejected if the async operation returned an error.  Using promises, the last two lines of your function could be adapted as follows:
player.save().then( function(result){
    return opponent.save();
}, function (error){
    // We had an error saving the player
}).then( function(result){
    console.log("Successfully saved user and opponent");
}, function(error){
    // We had an error saving the opponent
});

I suggest you read up on both callbacks and promises as asynchronous functions are a fundamental part of working in the Parse Cloud Code environment. This blog post would be a great place to start. Callbacks may be easier to understand in the short term, but may lead to code that is harder to understand and maintain as your application grows in complexity.
EDIT
Since the ACLs on your opponent user restrict write operations to only that user, you'll also need to use the master key when saving that objects.
Comment: Thanks Todd for the awesome response! I love Promises.. have done a lot of reading and implemented them as you recommended.. The problem still arises although now I was able to output the error message from the promise (error.message) and turns out it is failing because a session/token is required to alter the opponent.. UserCannotBeAlteredWithoutSessionError
Comment: Sounds like you'll need to use the master key to bypass the ACLs on the opponent. Try putting 'Parse.Cloud.useMasterKey();' at the top of your function.
Comment: Parse only allows User objects to be changed by the logged in user.. I was able to use a master key to override this check. opponent.save(null, { useMasterKey: true });
Comment: yeah thanks Todd.. just researched that behaviour! I was able to tighten up the security by setting the useMasterKey variable to only apply to that call and not the whole function.. thanks again for your guidance


Satellite L750 Screen resolution problem

Question: I am new in Ubuntu, I just replaced my windows 7 with it, but after installation I am stuck with a resolution of 1024x768 and I have tried most of the fixes I find here and this is my 3rd time reformatting my laptop due to fail attempts on getting my desired resolution which is 1368x768.
Can anyone help me?
My Graphics card is Geforce GMT 525
Answer: The Built in Linux drivers for Geforce video cards while good are not perfect,
and that could be part of the problem.
However you "might" have an option to install the drivers from Nvidia.
Here is how you do it:
First I would do a full update for the system from the update manager, and reboot to enable any new kernel stuff that would be put on the system (this really might be all thats needed).
Next open the "Additional Drivers" application and let it look for any drivers that might work. If it finds any it will display a list. you simply click on the one you want and click the activate button. (On a side note, for me I normally avoid drivers marked "post release".) After it completes the install you will need to reboot.


Get content of protected web pages using Python

Question: How can you get content of protected pages using Python and urllib2?
I need to specify a username and password for the pages that I am trying to retrieve..
e.g.
content = urllib2.urlopen(URL, username, password).read()

I know that is not part of the urllib2 API.. Just give an example of what I would need, from the API.
Comment: HTML pages are usually protected in on of two ways; using a cookie token or using the HTTP Authentication header. You need to figure out which, then either get that cookie (usually by POSTing the username and password to a specific login form action), or by adding a [Authorization header](http://stackoverflow.com/questions/635113/python-urllib2-basic-http-authentication-and-tr-im)
Answer: I suggest you look at the python requests library.
It has great support for basic http authentication out of the box.
e.g.
import requests
content = requests.get(URL, auth=('user', 'pass'))

Using requests you can also set up sessions (for cookie management) and easily POST data (e.g. a login form) and keep the cookie to browse all the pages only accessible to logged in users.
Read more about session objects and posting data in the excellent documentation.
If you absolutely have to use urllib2 here's a useful snippet taken from another thread for basic HTTP authentication:
import urllib2, base64

request = urllib2.Request("http://api.foursquare.com/v1/user")
base64string = base64.standard_b64encode('%s:%s' % (username, password))
request.add_header("Authorization", "Basic %s" % base64string)
result = urllib2.urlopen(request)

Answer: You can do this with urllib2 just look at the Urllib docs
its actually a lot easier to enter into form using a web driver like selenium but the thing about selenium is it opens an actual window while urllib is in the background but selenium is much easier to use
Selenium API
those are just some suggestions that i hope helped


How to performantly sum all products of unordered pairs in a set of binary strings

Question: Given a set of binary strings S, where each binary string has length L, I want to find the sum of all products of unordered pairs of elements in these strings for each unique unordered pair. I then want to position these in a matrix such that position i,j is the sum of the products of the unordered pair of indices i,j over all binary strings.
For example:
Let S = {101, 110, 111}
The first binary string s∈S = 101 has the unordered pairs {10, 11, 01}, whose indices are {12, 13, 23}. The products of each unordered pairs is {0, 1, 0}.
The second binary string s∈S = 110 has the unordered pairs {11, 10, 10}, whose indices are {12, 13, 23}. The products of each unordered pairs is {1, 0, 0}.
The third binary string s∈S = 111 has the unordered pairs {11, 11, 11}, whose indices are {12, 13, 23}. The products of each unordered pairs is {1, 1, 1}.
Summing the products, we have {0, 1, 0} + {1, 0, 0} + {1, 1, 1} = {2, 2, 1}.
Now I want to position these in an array based on the indicies of the unordered pairs {12, 13, 23}, whose order remained constant in the above. Thus:
0, 2, 2
2, 0, 1
2, 1, 0

I've written some Python code which achieves this in nested for-loops, and for small numbers of short binary strings it works well. However, I need to calculate this for 150 strings of length 10,000.
import numpy as np

n_strings = 3
len_strings = 3

ordered_sum_matrix = np.zeros((len_strings,len_strings))

for s in range(0, int(n_strings)):
    binary_string = np.random.binomial(1, 0.5, len_strings)
    for i in range(0, len(binary_string)):
        for j in range(0, len(binary_string)):
            if i == j:
                continue
            ordered_sum_matrix[i,j] = ordered_sum_matrix[i,j] + (binary_string[i] * binary_string[j])

Are there some tricks of linear algebra, binary strings, or Python magic that could help speed things up?
Answer: Thanks to a numpy-maestro friend who provided the following solution:
import numpy as np

def sum_of_prods_of_pairs(M):
    # note: this function performs slightly better if given booleans
    # e.g. M = np.random.choice([True, False], (len_strings, n_strings))
    n_strings, len_strings = M.shape
    MT = M.T
    M_sum = np.zeros((len_strings, len_strings))

    for i in range(len_strings):
        M_sum[i, i+1:len_strings] = np.sum(np.multiply(MT[i], MT[i+1:len_strings]), axis=1)
    M_sum += M_sum.T
    return M_sum

# n_strings = 150
# len_strings = 10000

# np.random.seed(91)
# C = np.random.choice([True, False], (n_strings, len_strings))
# C = np.random.binomial(1, 0.1, (n_strings, len_strings))
C = np.array([[1,0,1], [1,1,0], [1,1,1]])

ordered_sum_matrix = sum_of_prods_of_pairs(C)

print(ordered_sum_matrix)

which prints
[[0. 2. 2.]
 [2. 0. 1.]
 [2. 1. 0.]]


Spring security makes a session when a user access the log in page

Question: I'm making log in page, following official guide.
I want to add a function which makes redirect to home if a user join.
The logic is like this.

A user join with email, password and username.
Joinpage redirect to log in page.
if there is authentication, directly go to home.

How can I redirect to home with authentication?
<code>@Slf4j
@Controller
@RequiredArgsConstructor
public class LoginController {

    @GetMapping("/login")
    public String loginForm(@ModelAttribute LoginForm loginForm) {

        return "login/loginForm";
    }
}

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private final UserSecurityService userSecurityService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests() // 인가 요청 받기
                .antMatchers("/", "/home", "/join",
                        "/css/**", "/*.ico", "/error").permitAll()
                    .anyRequest().authenticated()
                    .and()
                .formLogin()
                    .loginPage("/login")
                    .defaultSuccessUrl("/")
                    .failureUrl("/login")
                    .usernameParameter("email")
                    .permitAll()
                    .and()
                .logout()
                    .logoutUrl("/logout")
                    .logoutSuccessUrl("/login")
                    .invalidateHttpSession(true);
    }
</code>
Answer: basically, the security generates user session along the SessionCreationPolicy value when the user logins successfully.
if you want to change the session system to stateless system.
but following the below code.
<code>    protected void configure(HttpSecurity http) throws Exception {
        http
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
    }
</code>
and then, you need to set the authentication object.
<code>SecurityContextHolder.getContext().setAuthentication(
                    new UsernamePasswordAuthenticationToken("principal", "credentials", null));
</code>


What do the "spending" categories include in StarCraft II replays?

Question: In a replay, there is a "Spending" display that includes 3 categories:

Economy
Technology
Army

While it seems fairly straightforward that workers = economy, upgrades = tech, army = units, what do unit producing structures count as?  Or upgrade structures for Zerg? etc...
Answer: Economy

Command Centre / Nexus / Hatchery
Refinery / Assimilator / Extractor
Supply Depot / Pylon / Overlord
SCV / Probe / Drone
Queen

Technology

Unit producing structures (or in the case of Zerg, buildings which enable the spawning of units from larvae)
Structures where upgrades can be purchased (e.g. Engineering Bay, Forge, Evolution Chamber)
Upgrades (e.g. attack upgrades, building armour upgrades)

Army

All other units

My testing found that morphing buildings (e.g. Orbital Command, Planetary Fortress, Lair, Hive, Greater Spire) isn't counted at all, nor is the process of morphing units (e.g. Overseer). It also seems as if the construction of some buildings (e.g. Infestation Pit) isn't counted either, so it would appear as if the Spending Tab is somewhat buggy.


Ubuntu 20.04 Login loop after lots of updates

Question: I can get to the login screen, and try to login, but then it just flashes and takes me right back.
I've uninstalled my Nvidia drivers since that was one of the things that got updated. And I tried to disable my gnome extensions since I have a login background one, but gnome-extensions list doesn't show any. I had also re-chowed my user directory recursively, so there's now ownership issues.
journalctl cat -f -o /usr/bin/gnome-shell returns just
gvc_mixer_card_get_index: assertion 'GVC_IS_MIXER_CARD (card)' failed
gnome-shell: Fatal IO error 11 (Resource temporarily unavailable) on X server :0.

Unset XDG_SESSION_ID, getCurrentSessionProxy() called outside a user session. Asking logind directly.
Will monitor session ci
Error looking up permission: GDBus.Error: org.freedesktop.portal.Error.NotFound: No entry for geolocation
Not starting gsd-xsettings; waiting for gnome-session to do so
Regersring session with gdm
warning: failed to start gsd-xsettings
JS WARNING: [resource: ///org/gnome/shell/ui/layout.js 24]: reference to undefined property "MetaWindowXwayland"

and the output doesn't seem to get added to at all if I try going back to graphical and logging in again while journalctl is running.
So, unique from other instances of this issue on askubuntu, this has nothing to do with Nvidia drivers (since they were removed), doesn't produce any errors in Gnome itself, and isn't caused by user directory ownership/permissions issues.
Comment: I'm voting to close this question due to low quality, not really helpful for others.
Comment: Does this answer your question? [Ubuntu gets stuck in a login loop](https://askubuntu.com/questions/223501/ubuntu-gets-stuck-in-a-login-loop)
Answer: In this case... It was because I accidentally sourced my .profile from my .bashrc, when my .profile also sources my .bashrc creating a loop for any bash shell.
Bit of a face palm, but I guess the lesson it to start with the simplest stuff first.
So the part that is not mentioned in any questions here is that a malformed .profile or .bashrc can stop Gnome from loading, without throwing any errors to Gnome itself, causing a unique login loop.


Continuity at a point of a piecewise function

Question: Let
$
f(x) = \left\{
  \begin{array}{lr}
    \frac{x}{3} &  x ~\textrm{is rational},\\
    x & x ~\textrm{is irrational}.
  \end{array}
\right.
$
Show that $f$ is continuous at $a \in \mathbb{R}$ if and only if $a=0$.
My initial approach is to use the sequential criterion with the use of density of rational numbers but I wasn't successful. Any help is much appreciated.
Answer: Let $x \in \mathbb R$, $x$ constant. If $(\rho_n)$ be a sequence of rational numbers with $$\lim \rho_n = x \Rightarrow \lim f(\rho_n) = \lim \rho_n/3 = x/3$$
If $(a_n)$ is a sequence of irrational numbers with
$$\lim a_n = x \Rightarrow \lim f(a_n) = \lim a_n = x$$
then, it is
$$\lim f(\rho_n)\neq\lim f(a_n) \Leftrightarrow x \neq 0$$
Thus, $f$ is not continuous at $\mathbb R \setminus \{0\}$.
We will now show that $f$ is continuous at $0$. It is $f(0) =0$. For all $|x| < 1$, we have :
$$|f(x) - f(0)| = |f(x)| \leq \max\{|x|,|x|/3\} = |x|$$
thus $\lim_{x\to 0} f(x) = f(0)$ which means that $f$ is continuous at $0$.


Adding 12 gauge wire to 14 gauge circuit

Question: I am converting an existing single switched light/fan combo to separate switches for each function.  There is already a light/fan combo on the circuit, wired with 14/2 Romex.  Power comes in at the switch box.  The existing fixture branches off of that power.  The switch is in the middle of the run, so power also continues from the switch on to several outlets down the line.  The circuit has a 15A breaker and the circuit is wired with 14 gauge throughout.
My question is this: is it permissible by code (local code is NEC 2017) to use 12/3 gauge wire to power the light and fan? Are there any additional considerations I need to take into account?
Answer: Yes, using 12/3 into a 15 Amp circuit of 14/2 is OK. You could not go the other way and add a 14/3 to a 20 Amp circuit of 12/2.
Comment: Thanks. I'm assuming I can connect all 3 neutrals together at the box (one from the 14/2 coming into the box, one for the 14/2 leaving the box and one for the new 12/3)?  The fan/light kit's neutral will be connected to the other end of the 12/3's neutral.
Comment: Yes, you can and need to connect the 12/3  and the (2) 14/2 neutrals together.


How to install "PC Companion" software of Sony Xperia?

Question: I've successfully installed "PC Companion" Sony Xperia in Windows. Has anyone been able to install pc companion sony xperia in within Ubuntu or any other Linux distro?
Comment: http://android.stackexchange.com/questions/36376/cant-explore-files-on-my-sony-xperia-u-using-my-ubuntu-12-10-laptop
Comment: Use one of these instead for file transfer http://askubuntu.com/questions/189591/connecting-android-4ice-cream-sandwich-jelly-bean-kitkat-phone I've tried SSH SFTP and it just works (in addition to allowing you to run a shell when you need it).
Answer: Others have been using a virtual machine for this, sadly there isn't any support for Ubuntu on PC Companion (i just tried).
WINE support seems limited and running it on this end seems incredibly glitchy, but if it's only for the storage purpose then you can change the settings on your phone to USB Storage mode if you want to get into the contents on your device.
Answer: This program is specified for Windows only.
I searched but didn't find an alternate for Linux. So when a program simply does not exist for Linux, you cannot install it (at least with the native way).
You can use either Wine or VirtualBox and resolve your problem.
In case you just need to exchange files from pc to phone you can use ADB -> ADB and Sony xperia
From Ubuntu community wiki

How to install and use Wine --> WineDB Sony Companion
How to install and use VirtualBox--> Virtual Box and Sony Companion
Comment: this is like a general answer adding few info about how to solve the issue ... most of program run bad on wine or need some particular istructions
Answer:
Install virtualbox and extensionpack (for usb support) from their website
In your user/group settings (ubuntu) add your linux username in group 'vboxusers' (for rights adding usb devices)
Create windows session in vb
Connect your device and add them in usb settings (virtualbox settings. or windows won't recognize it. Has to be done for every device u want to use)
Connect in flashboot as well and add the usb device (turn phone on while holding volume up)
Start windows session and install windows
Download phonedriver and flashbootdriver from sony website and install in windows.
-Install pc companion and you should be fine.

I advise to make a proper backup with pc companion before upgrade, because sometimes windows crashes..
Easiest way is to ask someone with a windows machine ;-)
I tested with a windows 7 copy from digital river (official), didn't enter a serial and didn't avtivate.. So 30 day trial..
Thank god most updates are handled on the phone itself.. But the upcoming new android version can only installed by the companion..
Pc companion is the only thing i need windows for, so this is fine for me.
Answer: regarding installing PC Companion in Ubuntu (Linux)
Might be redundant, for sync and backup of phone contacts, calendar etcetera simply get a Google+ account and all these matters are solved. Works perfectly calendar functions simple aswell as more hardcore fex mailing a meeting to other participants that use Google+ and have Android phones, the reciepent answer and tells if they are taking part of it or not, if yes the booking appears in ther phone aswell :-)
For filebackup simply connect your Android smartphone (fex Experia S) via USB cable and all files appear in Ubuntu as a portable USB disc, just drag and drop.....
or, connect your Sony Xperia S to a USB portable disc using OTG (On the go) USB cable and move all files to that memory or harddrive :-) really simple.... Go Sony...
When in need of Android update of OS, well, depends on the carrier, Ive got Telia in Sweden and so far all updates have been via the phones internet connection. So choose your provider based on that.
Well, thats about it, think that most things are covered by that..
BR
Lars Lundblad


Keeping function names when stored in an object

Question: I am preparing a package where users have to store functions and their associated arguments in a list for later use. This is a typical example of how it works:
Preparation of the list containing function names and arguments
parameters <- list(a1 = list(fun = dnorm,
                             args = list(mean = 150, sd = 100)),
                   a2 = list(fun = dpois,
                             args = list(lambda = 40)))

Here is an example of how this parameters object is used in other functions:
x <- 1:100
myfunction <- function(x, var, parameters)
{
    results <- list(var = var,
                    y = do.call(parameters[[var]]$fun,
                                c(list(x), parameters[[var]]$args)),
                    parameters = parameters)
    class(results) <- "customclass"
    return(results)
}
myfunction(x, "a1", parameters)

Now suppose I want to print the names of the functions stored in parameters in the output of myfunction.
print.customclass <- function(X)
{
   cat("Function name:", X$parameters[[X$var]]$fun)
}

This custom print will not work:
> myfunction(x, "a1", parameters)
Error in cat(list(...), file, sep, fill, labels, append) :
argument 2 (type 'closure') cannot be handled by 'cat'

I have also tried other suggested solutions found elsewhere, such as:
print.customclass <- function(X)
{
   cat("Function name:", deparse(quote(X$parameters[[X$var]]$fun)))
}

> myfunction(x, "a1", parameters)
Function name: X$parameters[[X$var]]$fun

According to Harlan in this other question, the name of the function is lost when stored in another R object. He suggested to name the list of function with the function names, e.g.:
parameters <- list(a1 = list(dnorm = dnorm,
                             args  = list(mean = 150, sd = 100)),
                   a2 = list(dpois = dpois,
                             args  = list(lambda = 40)))

However, I wanted to keep the same names (fun) for every element of my list.
My question therefore is
Can anybody think of a way to keep the function name, when the function is stored in another object?
Thank you very much for your help!
Answer: I'd suggest to define your parameters argument with the function name, instead of the function itself and retrieve the function in the body of myfunction through match.fun:
    parameters <- list(a1 = list(fun = "dnorm",
                         args = list(mean = 150, sd = 100)),
               a2 = list(fun = "dpois",
                         args = list(lambda = 40)))

    myfunction <- function(x, var, parameters)
    {
        results <- list(var = var,
                y = do.call(match.fun(parameters[[var]]$fun),
                            c(list(x), parameters[[var]]$args)),
                parameters = parameters)
        class(results) <- "customclass"
        return(results)
    }

Comment: This is another nice answer, just as valid as @Roland 's answer. I have not yet decided which one I will implement, but both seem very valid to me.
Answer: You could use alists:
parameters <- list(a1 = alist(fun = dnorm,
                             args = list(mean = 150, sd = 100)),
                   a2 = alist(fun = dpois,
                             args = list(lambda = 40)))
#probably better to write a constructor method for parameters objects

x <- 1:100
myfunction <- function(x, var, parameters)
{ f <- function(x) do.call(fun, c(list(x), args))
  formals(f) <- c(formals(f), parameters[[var]])
  results <- list(var = var,
                  y = f(x),
                  parameters = parameters)
  class(results) <- "customclass"
  return(results)
}

print.customclass <- function(X)
{
  cat("Function name:", X$parameters[[X$var]]$fun)
}

myfunction(x, "a1", parameters)
#Function name: dnorm

Comment: That's a nice answer, I did not know about `alist`. You are right, I should write a constructor method for parameter objects. I am not yet sure how I can write it to make it very user-friendly.
Comment: @BorisLeroy I've changed the function a bit since `eval`ing like that seemed a bit clunky.


Convert Hebrew Letters into Equivalent Number

Question: Other then hard coding this by hand I was wondering if there was a way that the.net framework would have this built in automaticaly, I know it can automatically convert hebrew dates into georgian dates but I need to convert hebrew numbers into georgian
IE   א
= 1
     ב
= 2
This goes into the hundreds. See here for more info.
Comment: Do you mean "Gregorian" dates?  And perhaps "Arabic" numerals from Hebrew numbers?
Comment: NO I mean this http://www.i18nguy.com/unicode/hebrew-numbers.html
Comment: @Jim was commenting on the title. "Georgian" doesn't really make sense. You are trying to convert "gemtriya" (each hebrew letter has a numeric value) into Arabic Numerals (http://en.wikipedia.org/wiki/Arabic_numerals - ie: numbers)
Answer: Here is the approach that you should take:

Make Dictionary<char,int> that gives correspondence between each Hebrew letter and its numeric value
Parse the string one character at a time (best to do it right-to-left)
For each character, look up its value in the dictionary and add it to a running sum
Be sure to handle common scenarios for separating the hundreds-letters from the tens-letters (double-quotation mark) and separating the thousands-letters from the hundreds (single-quotation mark). For example, 5770 = ה'תש"ע.`. See the details in the link above for more on separations.

Edit: I just published a GitHub Repo that exposes functionality for converting Hebrew text to numbers, and numbers to their Hebrew letter equivalents.


A list of error in my site

Question: I don't know why my site give me this error. This is the list of errors.
plz lid me ! what shall i do ?
Fatal error: Out of memory (allocated 6029312) (tried to allocate 8192 bytes) in /home/lifegat/domains/life-gate.ir/public_html/includes/functions.php on line 7216

Fatal error: Out of memory (allocated 7602176) (tried to allocate 1245184 bytes) in /home/lifegat/domains/life-gate.ir/public_html/misc.php(89) : eval()'d code on line 1534

Fatal error: Out of memory (allocated 786432) (tried to allocate 1245184 bytes) in /home/lifegat/domains/life-gate.ir/public_html/showthread.php on line 1789

Fatal error: Out of memory (allocated 7340032) (tried to allocate 30201 bytes) in /home/lifegat/domains/life-gate.ir/public_html/includes/class_core.php(4633) : eval()'d code on line 627

Fatal error: Out of memory (allocated 2097152) (tried to allocate 77824 bytes) in /home/lifegat/domains/life-gate.ir/public_html/includes/functions.php on line 2550

Warning: mysql_query() [function.mysql-query]: Unable to save result set in [path]/includes/class_core.php on line 417

Warning: Cannot modify header information - headers already sent by (output started at [path]/includes/class_core.php:5615) in [path]/includes/functions.php on line 4513

Database error
Fatal error: Out of memory (allocated 786432) (tried to allocate 311296 bytes) in /home/lifegat/domains/life-gate.ir/public_html/includes/init.php on line 552

Fatal error: Out of memory (allocated 3145728) (tried to allocate 19456 bytes) in /home/lifegat/domains/life-gate.ir/public_html/includes/functions.php on line 8989

Fatal error: Out of memory (allocated 262144) (tried to allocate 311296 bytes) in /home/lifegat/domains/life-gate.ir/public_html/forum.php on line 475

Warning: mysql_query() [function.mysql-query]: Unable to save result set in [path]/includes/class_core.php on line 417

Warning: Cannot modify header information - headers already sent by (output started at [path]/includes/class_core.php:5615) in [path]/includes/functions.php on line 4513

Answer: Fatal error: Out of memory means that the server is out of reserved memory. This usually happens when you are working with big objects, such as images.
The solution is to use the & operator. This makes a variable point towards another object. Example:
$object = new BigObject();
$copy = $object;              // this copies the object thus more memory is required
$pointer = &$object;          // the & makes the $pointer variable point to $object

Because the variable is pointed to another variable, if you change one, the other will change as well.
$object = new BigObject();
$pointer = &$object;

$object->x = 12345;

echo $object->x;
echo $pointer->x; // will have the same output as $object->x

Pointers are often used in functions, like this:
$object = new BigObject();
x( $object );

function x( &$object ) {
     // do stuff with $object
}

The Warning: Cannot modify header information warning is usually given when you are trying to change the header data after sending output. You probably have a header(); call after you have echo'd something or have some whitespaces before you use the PHP open tag <?php.
Finally, the Warning: mysql_query() [function.mysql-query]: Unable to save result set error is usually a MySQL issue. But knowing you are out of memory, you might fix the other errors first.
Comment: Thx but where i can change that ?
Comment: I already gave you suggestions for the Out of memory error. For the other error you should just replace the `header();` function somewhere else or just don't echo stuff before the header call
Answer: Increase memory_limit in php.ini or slim your code.
Comment: I can't acces to php.ini . my server is shared .what shall i do ?
Comment: Try setting it via `.htaccess` - do you have access to that? If not, you are out of luck: The server doesn't allow you to use so much memory.
Comment: As I said: You are out of luck. Switch to a better hoster or slim your code.
Comment: so please lid me . how can i do that ?

A list of error in my site


Temporary push button power switch

Question: I'm building a remote button to flush a toilet and I need a temporary power switch - something that will run 120V for say 3 to 10 seconds....
I have googled extensively and have not found anything...anyone have a solution?
correction, power is 12v - motor I'm using is DC and I have a transformer.
Also, I found what I need: "timed delay relay".
The timed delay relay will power a motor that lifts the flush handle and then shuts off.  Like a piston crank shaft.
I will update with a DIY when/if I finish this.
Comment: So you don't want a momentary switch that's only on when you push it?  You essentially want a 3-10 second timer?
Comment: I'm not sure you're approaching this correctly and not sure having 120V interacting with a plumbing fixture is a good idea.  What exactly are you trying to accomplish? Have you looked at something like the [Kohler Touchless Toilet Flush Kit](http://www.us.kohler.com/us/catalog/productDetails.jsp?productNumber=1954) to see if it will meet your needs or if you can do something similar to how that works?
Comment: yes. I would prefer that...however, I just found a simple "auto-flip" switch - like a temporary paddle and I may use that to start.
Comment: Best I know of is a Belkin WeMo switch that can turn off automatically after 1 minute.  You can always build something with basic electrical circuits like a relay and a 555 timer (being very general here).  Link to the paddle switch?
Comment: I think I found what I need: google "timed delay relays"
Answer: You could reduce the timing on one of these:

and add a double pole switch.
Comment: These things always are more entertaining if you can incorporate a live animal into the mechanism.
Comment: You need to add a link to the Instructables, or Make, or whatever schematic for this thing.
Comment: Found this on [Think Geek](http://www.thinkgeek.com/product/ef0b/), and another one on [Amazon](http://www.amazon.com/Itself-Useless-Box-Machine-Assembled/dp/B00O0W386C/).  "Useless box" seems to be a good search term.
Comment: yes, I like this very much.I was actually planning on using a nautilus gear to lift and drop the plunger.  However, this is an elegant solution though it requires an additional contact switch, but removes the need for the relay. I will mull on both.
Comment: In fact, now that some pencil has been applied to some graph paper, this solution, combined with the nautilus gear the is more elegant.  Nautilus gear lifts the plunger.  Remote switch turns motor on, turning gear, lifting plunger off contact switch. Falling plunger lands on contact switch turning off motor.  Thanks!
Answer: See my edit: "timed delay relay".

Temporary push button power switch


Create Migration folder Using dataContext.Database.Migrate() in EF core

Question: I use EF core in My project and I want migrate my context using Programming (not command)
So I use these two concpets one by one
1.
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())

{

    var context = serviceScope.ServiceProvider.GetService<UserInformationContext>();

    context.Database.Migrate();

}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, UserInformationContext userContext)

{
   userContext.Database.Migrate();

}

Problem Is ,using this two concepts can not create any Migration Folder like add-migration command
Is there any way to Create Migration Folder and Migrate Context using Programming ??
Comment: Could you please tell me why you need the  Migration Folder and Migrate Context ? It seems this two things could only be created by using the command-line.
Answer: I think the method you can use here is generating migration files using the add-migration command and add the following line of code to do the migration when the application runs. The code checks if there are any pending migrations to be applied and if so it applies the migration
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, UserInformationContext userContext)
{
 if (userContext.Database.GetPendingMigrations().Count() > 0)
     {
         userContext.Database.Migrate();
      }

}


CSS bring two different font sizes in one line

Question: How do I both bring the "July" and the "2016" in the line, with the font-size differences and the "2016" being aligned right?

  July2016

Comment: Frankly, we don't know what he means. This needs confirmation from the asker about what "same height" means. (Align top, align bottom, align centre, same size... could mean a whole load of things at the moment)
Comment: Replace `` with ``
Comment: the author is not talking about the font-size @PraveenKumar
Comment: @PaulLemarchand That was a sarcastic *comment* only. One person has answered it. Please comment on n00b's answer.
Comment: I mean by "same height" that both texts should be on one line
Answer: Do you mean they should be aligned the same way? You can use vertical-align: bottom to get them aligned on the line, or middle to align them centered with each other.

  July 2016

Answer: remove:
position: absolute;
top:0;

Replace it by:
float: right;

Fiddle
HTML

  July2016

Comment: That's what I asked for - the July is still higher than the 2016 and I want it to be the same height
Comment: Since you already know the font-sizes you can move the small one a bit by giving it position: relative and top: 3px (=half of the difference in font size between the fonts in the spans). https://jsfiddle.net/j1L7Layk/2/


drive permissions problem

Question: I seem to be unable to write to my drives (NTFS). they worked fine until today, not sure what happened.
<code>UUID=xxxxxxxxx /media/stuff ntfs rw,auto,users,exec,nls=utf8,umask=003,gid=46,uid=1000 0 0 </code>
any help would be greatly appreciated.
EDIT The drive is currently mounted as follows:
<code>/dev/sdb2 on /media/stuff type fuseblk (ro,nosuid,nodev,relatime,user_id=0,group_id=0,default_permissions,allow_other,blksize=4096,x-gvfs-show)
</code>
Comment: Please enter the command `mount` in a terminal and paste the lines pertaining to the NTFS drive in your question. This will give us the current situation instead of the desired situation from `fstab`.
Comment: /dev/sdb2 on /media/stuff type fuseblk (ro,nosuid,nodev,relatime,user_id=0,group_id=0,default_permissions,allow_other,blksize=4096,x-gvfs-show)  is this what you mean?
Comment: The drive is mounted read-only, for whatever reason. Please try to unmount it and remount it read-write.
Answer: If you have a dual-boot system with Windows just turned off fast startup mode in windows and you will be able to write to NTFS drive. https://www.windowscentral.com/how-disable-windows-10-fast-startup.
Comment: Absolutely incredible.... thanks a bunch.... I have no clue why it messed with linux, as I have been running a dual boot for some time now without any issues.

drive permissions problem


Does nmbd binds on a IPv6-Only network?

Question: After moving my Samba to a IPv6-Only environment, nmbd doesn't start up anymore...
I tried this:
interfaces = 2001:db8:1:1::/64
and with this:
bind interfaces only = yes...
But, nmbd doesn't starts up, the log.nmbd shows:
[2014/04/21 03:36:38,  3] ../lib/util/util_net.c:70(interpret_string_addr_internal)
   interpret_string_addr_internal: getaddrinfo failed for name 0.0.0.0 [Address family for hostname not supported]

Any tips?! I'm totally newbie with Windows/Samba things and I don't even know if nmbd in fact, works with IPv6...
BTW, smbd works okay in a IPv6-Only environment, shares are working and, smbclient -L fileserver -N shows:
fileserver is an IPv6 address -- no workgroup available

This is because of nmbd is now, obsolete?
I'm thinking that nmbd have nothing to do with IPv6, am I right?
Using Ubuntu 12.04.4.
Cheers!
Thiago
Answer: Replace the line
hints.ai_flags = flags

with
hints.ai_flags = flags & ~AI_ADDRCONFIG;

in lib/util/util_net.c file of Samba. Compile and run the samba in only IPV6 environment.

Does nmbd binds on a IPv6-Only network?


Questions about eigenvectors and symmetric matrices

Question: I have a few questions about eigenvectors and eigenvalues, especially in symmetric matrices. So, straight to the point:

Why, for any matrix $A_{m \times n}$, is $A^{T}A$ an symmetric matrix?

I tried to figure it out by myself, i couldn't, so i looked up in the internet and couldn't find anything. I really dont have a clue about this.
Let's talk about another problem:

Given $A$ an symmetric matrix, with, for example, all elements on its main diagonal = $k$. If $A$ is $n \times n$, then the matrix will always have $n$ independent eigenvectors? And what about when there is $n$ distinct values in its main diagonal?
  Is there any proof of this?

And the last one:

Given $A$ a symmetric matrix, then $dim(colA)^{\perp} = Nul A^{T}$. How to prove?

Where $colA$ is the subspace generated by $S\{ u_1,u_2,...,u_n \}$, where $u_n$ are the vectors in the columns of the matrix $A$. What i did in this last one was:
for $T: W \rightarrow V, T(x)=Ax$
$$ dim W + ker T = dim V$$
in matrix form:
$$ dim(colA) + dim(NulA) = n$$,
where n is the number of columns of the matrix.
applying this to $A^{T}$:
$dim(colA^{T}) + dim(nulA^{T}) = m$, where $m$ is the number of lines of $A$.
Now, we know that: $dim(colA) + dim(colA)^{\perp} = m$, substituting in the first equation, i got to:
$dim(nulA^T) = dim(ColA)^{\perp}$. This proves about the dimension, but not about the space itself. How can i prove it?
Thanks.
Notes:
$ColA$ = subspace generated by the columns of $A$.
$NulA$ = null space of A.
$dim V$ = dimension of $V$.
Comment: Of course it's not a proof. It's meant to give you insight. Can you see from doing that why it will always work?
Comment: For your first question, try writing out a $2\times 2$ or $3\times 3$ matrix composed of general variables $a, b, c,...$ and see what happens when you multiply $AA^T$ or $A^TA$. Can you generalize to higher dimensions?
Comment: This is what i tried, i checked it correctly. But it's not a proof.
Answer:
Why, for any matrix $A_{m \times n}$, is $A^{T}A$ an symmetric matrix?

For any two matrices $A, B$ with compatible dimensions, $(AB)^T = B^TA^T$ If you apply that to $A^TA$, you see that it's equal to its own transpose.

Given $A$ an symmetric matrix, with, for example, all elements on its main diagonal = $k$. If $A$ is $n \times n$, then the matrix will always have $n$ independent eigenvectors? And what about when there is $n$ distinct values in its main diagonal?

A symmetric matrix will always be diagonalizable, which, in turn, means that it will have $n$ independent eigenvectors. It doesn't matter what values are in its diagonal.

Given $A$ a symmetric matrix, then $\dim(\operatorname{col} A)^{\perp} = \operatorname{Nul} A^{T}$. How to prove?

$\dim(\operatorname{col} A)$ is the same as the rank of $A$, and the dimension of the perpendicular space is then $n$ minus said rank. By the rank-nulity theorem, this is exactly the dimension of the kernel of $A$. This has nothing to do with $A$ being symmetric.
Comment: Thank you. I have a few questions about the third explanation.

This means that $dim ker A = dim(colA)^{\perp}$. Does that mean that
$ker A =  (colA)^{\perp}$? Why?
Comment: No. Just because two spaces have the same dimension does not mean they are equal. They are definitely connected, though. Or rather, their orthogonal complements are. The matrix $A$ gives a bijection from $\operatorname{Nul}A^\perp$ to $\operatorname{col}A$. Thus the dimensions of these two spaces are equal.
Comment: I mean from $\ker A^\perp$ to $\operatorname{col}A$.
Comment: So the statement kerA=(colA)⊥ is false?
Comment: @Dovah-king Yes, it is. $\ker A$ lives in the domain of the map given by $A$, while $\operatorname{col} A$ lives in the codomain. To make it a bit clearer, if $A$ isn't square, say it's $m\times n$, then $\ker A \subseteq \Bbb R^n$ while $\operatorname{col} A$ lives in $\Bbb R^m$.
Comment: Im sorry, i meant ker $A^T$.